From 4e35ec2f619ef4d95dfe44f6c5ccdd6a97d4133e Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Wed, 18 Nov 2026 17:23:06 -0500 Subject: [PATCH 01/35] Nested attachments in the preview and the plot Attachments, and the xrefs of a referenced drawing in the preview and the plot. - `d.xref(name, path, { attach: true })` writes an attachment. A drawing that references this one draws an attachment too, and never an overlay, which is still the default. `Xref` holds `attach`, and `toDXF` writes it. - `toSVG` and `toPDF` take a drawing in `xrefs` as `{ drawing, xrefs }`, with the drawings its own xrefs stand for, and draw its attachments and none of its overlays, as the leading CAD app draws them. A layer of a nested attachment is named by that attachment's own name, such as `BASE|C-BLDG`. A drawing given alone draws no xref of its own, as before. `inspectText` takes the same `xrefs`, and checks the texts of the drawings given for the drawing's own xrefs, not of their attachments. - A circular reference is broken where a drawing would be drawn inside itself, a chain is drawn `XREF_DEPTH`, 16, drawings down, and past 4,096 names given inside referenced drawings none of them is drawn. - `lint(drawing, { xrefs })` warns of each drawing given there that is not drawn, and why. `drawnXrefs(drawing, xrefs)` gives what a picture draws of them. - `tsdraft render` and `tsdraft dev` take the same in the export `xrefs`, lint each drawing given that they draw, at any depth, and `drawing.xrefs` gives each xref's `attach` and, for one that is shown, the `xrefs` of the drawing drawn for it. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 19 ++- CHANGELOG.md | 15 +++ GUIDE.md | 10 ++ cli/AGENTS.md | 6 +- cli/assets/page.html | 16 ++- cli/src/state.ts | 29 ++++- cli/src/worker.ts | 272 ++++++++++++++++++++++++++++++++-------- cli/test/render.test.ts | 167 +++++++++++++++++++++++- docs/command.md | 23 +++- docs/plotting.md | 10 +- docs/xrefs.md | 67 ++++++++-- src/blocks.ts | 256 ++++++++++++++++++++++++++++++++++--- src/drawing.ts | 21 +++- src/dxf-r2018.ts | 6 +- src/extents.ts | 43 ++++--- src/index.ts | 4 + src/inspect.ts | 12 +- src/lint.ts | 58 ++++++++- src/pdf.ts | 12 +- src/rules.ts | 43 +++++++ src/shape.ts | 4 +- src/svg.ts | 14 ++- test/bounded.test.ts | 116 +++++++++++++++++ test/shape.test.ts | 2 +- test/xrefs.test.ts | 160 ++++++++++++++++++++++- 25 files changed, 1239 insertions(+), 146 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7165172..aaa5535 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,11 +68,20 @@ nothing of its block. - An xref is a block record with a path: `Drawing.xrefs` holds a name and a path, and an insert places one by its name. It shares the blocks' names and the keys of their handles, - `block:KEY` and the two beside it, and is written as an overlay, which cannot make a cycle - the leading CAD app has to break. That app reads the path of a BLOCK once, so the DXF writes it - with `dxfOnce`. `eachDrawn` walks the drawing a caller gives for an xref as it walks a block, - with each layer as a `LayerRef` that says which drawing's layer it is. `src/` opens no - file: `toSVG` draws only the drawings it is given. + `block:KEY` and the two beside it, and is written as an overlay, unless `attach` is true. That + app reads the path of a BLOCK once, so the DXF writes it with `dxfOnce`. `eachDrawn` walks the + drawing a caller gives for an xref as it walks a block, with each layer as a `LayerRef` that + says which drawing's layer it is. `src/` opens no file: `toSVG` draws only the drawings it is + given. `referencedTree` in `src/blocks.ts` is the one reading of what is given in `xrefs`: a + tree of `Referenced`, one for each place, each with the drawings of its own attachments, + never of an overlay, cut where a drawing on the chain above comes again and past `XREF_DEPTH` + drawings down, with why in its problems, which `lint` reports with `xrefs`. Past `XREF_LOOKS` + names looked for inside referenced drawings it follows none, so the same given with drawings + left out cuts nothing the whole did not, which the command relies on; `drawnXrefs` gives the + tree in the form given. `eachDrawn` and the boxer read that tree, the boxer keeping a block's + box for each drawing and the drawings given for its attachments. `inspectText` reads the + drawings given for the drawing's own xrefs alone, once each, and checks no text of their + attachments: a cut for each place cost work outside its limit. - A layout is a sheet: `Drawing.layouts` holds each with its paper, its viewports and the entities drawn on it in paper units. `src/papers.ts` is the one list of papers and of plot style tables, with the name the leading CAD app stores for each paper. Add a paper only when diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c44220..b2cad18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +- Attachments, and the xrefs of a referenced drawing in the preview and the plot. + `d.xref(name, path, { attach: true })` writes an attachment, which a drawing that references + this one draws too, where an xref is an overlay by default, and `Xref` holds `attach`. `toSVG` + and `toPDF` take a drawing in `xrefs` as `{ drawing, xrefs }`, with the drawings its own xrefs + stand for, and draw its attachments, and none of its overlays, as the leading CAD app draws + them, 16 drawings down at most, `XREF_DEPTH`; a drawing given alone draws no xref of + its own, as before. A circular reference is broken where the chain would draw a drawing it + already draws, and past 4,096 names given inside referenced drawings none is drawn. + `lint(drawing, { xrefs })` warns of each drawing given there that is not drawn, and why, and + `drawnXrefs(drawing, xrefs)` gives what a picture draws of them. `inspectText` takes the same + `xrefs`, and checks the texts of the drawings given for the drawing's own xrefs, not of their + attachments. `tsdraft render` and + `tsdraft dev` take the same in the export `xrefs`, lint each drawing given that they draw, at + any depth, and `drawing.xrefs` gives each xref's `attach` and, for one shown, the `xrefs` of + the drawing drawn for it. [docs/xrefs.md](docs/xrefs.md) describes them. - The README lists a viewport's own frozen layers and its twist with what tsdraft draws, and no longer with what it does not have yet. - The README and the package's description name what tsdraft does now: plotting to PDF, diff --git a/GUIDE.md b/GUIDE.md index 1adbddc..bd7fc74 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -493,6 +493,8 @@ d.layer("X-BASE", { color: 8 }, () => d.insert("BASE", [0, 0])); - Layer `0` of the referenced file draws as the insert's layer does, and its other layers as themselves. - Place every xref at least once. `lint` warns of one that no insert places, which CAD drops. +- An xref is an overlay unless you write `d.xref("BASE", "base.dwg", { attach: true })`. A + drawing that references yours draws your attachments too, and never your overlays. The command opens no DWG, so the pictures leave an xref out unless the drawing file gives the drawing it stands for. When that drawing is a tsdraft file too, import it and export it under @@ -508,6 +510,14 @@ export default d.build(); The command checks each drawing you give as it checks yours. One with a `lint` error is not drawn: `shown` is false, and each error is a diagnostic that names the `xref`. +To draw what a referenced drawing attaches, give it as `{ drawing, xrefs }`, with the drawings +of its own xrefs. Its attachments are drawn and its overlays are not, as CAD draws them, and +`drawing.xrefs[].xrefs` lists them with their own `shown`: + +```ts +export const xrefs = { MODEL: { drawing: model, xrefs: { SURVEY: survey } } }; +``` + Read `drawing.xrefs` in the JSON before you trust a picture of a drawing with xrefs. A picture with `shown: true` shows the drawing you exported, which is only as current as the DWG file CAD will load is: write that file again from the same drawing when it changes. diff --git a/cli/AGENTS.md b/cli/AGENTS.md index fb9e746..f19777e 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -6,7 +6,11 @@ gained the inserts on layouts while layouts were unreleased. - The command opens no file an xref names. The worker draws an xref from the drawing file's named export `xrefs` alone, and `drawing.xrefs` says with `shown` which ones the pictures - have, so an agent knows what it is not seeing. + have, so an agent knows what it is not seeing, and for one shown, the same of its own `xrefs`. + A value given as `{ drawing, xrefs }` draws its attachments where the copy of tsdraft has + `drawnXrefs`. The worker takes from it what the pictures draw, lints each of those drawings + once, leaves out one with an error, which cuts nothing else, and passes the export to `lint` + for why a drawing given is not drawn. - `outputs.svg` and `outputs.png` are model space, with or without layouts, and `outputs.layouts` has each sheet. The worker draws a layout only with a copy of tsdraft that has `viewportView`, since an older one would draw model space for it. `without` leaves a diff --git a/cli/assets/page.html b/cli/assets/page.html index 3e67601..20462d8 100644 --- a/cli/assets/page.html +++ b/cli/assets/page.html @@ -730,10 +730,20 @@

Diagnostics

} } - // The page draws an xref only when the drawing file gave its drawing. + // The page draws an xref only when the drawing file gave its drawing. Inside a drawing it + // draws, an attachment its model space places and not drawn is missing too; CAD draws no + // overlay there, and nothing the drawing places elsewhere. function xrefsFact(xrefs) { - const missing = xrefs.filter((x) => !x.shown).length; - return missing ? `${xrefs.length}, ${missing} not drawn` : `${xrefs.length}`; + // A nested xref placed nowhere its drawing's model space reaches draws nothing below it. + const placed = (x, top) => top || (x.attach && x.inserts > 0); + const missing = (list, top) => + list.reduce( + (count, x) => + count + (!placed(x, top) ? 0 : x.shown ? missing(x.xrefs ?? [], false) : 1), + 0, + ); + const count = missing(xrefs, true); + return count ? `${xrefs.length}, ${count} not drawn` : `${xrefs.length}`; } // The standard the drawing file exports, beside the file's name. diff --git a/cli/src/state.ts b/cli/src/state.ts index 41fe5c6..38cd4dc 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -181,8 +181,11 @@ export interface PngFont { * leaves out, by itself or with its block or list, has no `kind`, `layer` or `bounds`, since * the entity was not drawn. * - * With `xref`, the problem is in that xref, or in the drawing the file gives for it: an error - * `lint` finds there is reported once for each, with its rule, and that xref is not drawn. + * With `xref`, the problem is in that xref, or in the drawing the file gives for it or for an + * attachment inside that drawing: an error `lint` finds there is reported once for each place, + * with its rule and the chain of xrefs in its message, and that drawing is not drawn there. A + * warning with `xref` may say why a drawing the file gives is not drawn: an overlay inside a + * referenced drawing, a circular reference, or a chain deeper than the pictures follow. * * With `layout`, the problem is on that layout: `entity` then counts the layout's entities, * `viewport` its viewports, and `bounds` is on the sheet, in paper units. A viewport has no @@ -394,7 +397,16 @@ export interface XrefSummary { readonly name: string; /** The path of the DWG file, from the folder of the file this drawing is written to. */ readonly path: string; - /** How many inserts place the xref, in model space, in blocks and on layouts. */ + /** + * True for an attachment, which a drawing that references this one draws too, and false for + * an overlay, which it does not. + */ + readonly attach: boolean; + /** + * How many inserts place the xref, in model space, in blocks and on layouts. For an xref of a + * drawing given for another, only those its model space reaches, directly or through its + * blocks: CAD draws nothing else of a referenced drawing. + */ readonly inserts: number; /** * Whether the pictures draw a drawing for the xref. The command opens no DWG file: it draws @@ -403,7 +415,10 @@ export interface XrefSummary { * `standard` has the xref as its border and a `preview`, it draws the preview. It cannot tell * whether that drawing is what the file at `path` holds, so `true` says what the pictures * drew and not what CAD will load. When this is false, the pictures and the extents have - * nothing of the xref, and CAD will still draw it. + * nothing of the xref, and CAD will still draw it, unless it is an overlay of a drawing given + * for another, which CAD does not draw either. It means the same at every depth: the pictures + * draw the drawing at each insert that draws, so one with no `inserts`, or only on a layer + * that is frozen or does not plot, draws nothing. */ readonly shown: boolean; /** @@ -413,6 +428,12 @@ export interface XrefSummary { * `drawing.units` each insert needs the scale between the two. */ readonly units: Units | null; + /** + * The xrefs of the drawing given for this one, when `shown`, each as this one is: the file's + * `xrefs` export gives their drawings as `{ drawing, xrefs }`. The pictures draw an attachment + * among them, and never an overlay, as CAD loads them. Empty when it is not shown. + */ + readonly xrefs: readonly XrefSummary[]; } export interface BlockSummary { diff --git a/cli/src/worker.ts b/cli/src/worker.ts index 9a41848..cc56583 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -143,8 +143,14 @@ export interface WorkerResult { readonly modules: { readonly read: number; readonly ahead: number }; } +/** What the `xrefs` export gives: a drawing, or `{ drawing, xrefs }`, by an xref's name. */ +type GivenXrefs = Readonly>; + interface Library { - readonly lint: (drawing: Drawing, options?: { standard: unknown }) => Diagnostic[]; + readonly lint: ( + drawing: Drawing, + options?: { standard?: unknown; xrefs?: GivenXrefs }, + ) => Diagnostic[]; /** A copy of tsdraft from before standards has none, and its `lint` takes no standard. */ readonly defineStandard?: unknown; readonly toSVG: ( @@ -152,7 +158,7 @@ interface Library { options?: { margin?: number; drawNoPlot?: boolean; - xrefs?: Readonly>; + xrefs?: GivenXrefs; layout?: string; view?: readonly [number, number, number, number]; }, @@ -160,7 +166,7 @@ interface Library { /** What is wrong with the text as it plots. A copy of tsdraft from before it has none. */ readonly inspectText?: ( drawing: Drawing, - options?: { drawNoPlot?: boolean; xrefs?: Readonly> }, + options?: { drawNoPlot?: boolean; xrefs?: GivenXrefs }, ) => TextWarning[]; /** Where the drawing does not hold to its intent. A copy of tsdraft from before it has none. */ readonly checkIntent?: (drawing: Drawing, intent: Intent) => IntentWarning[]; @@ -173,6 +179,11 @@ interface Library { readonly findBlock?: (drawing: Drawing, name: string) => Block | undefined; /** The xref an insert of a name places. A copy of tsdraft from before xrefs has none. */ readonly findXref?: (drawing: Drawing, name: string) => Xref | undefined; + /** + * What the pictures draw of the drawings given for the xrefs. A copy of tsdraft from before + * attachments has none, and draws no reference of a referenced drawing. + */ + readonly drawnXrefs?: (drawing: Drawing, xrefs: GivenXrefs) => GivenXrefs; /** A dimension's style and what it draws. A copy of tsdraft from before dimensions has neither. */ readonly findDimensionStyle?: (drawing: Drawing, name: string) => DimensionStyle | undefined; readonly dimensionPicture?: ( @@ -523,7 +534,7 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise>; + let referenced: GivenXrefs; let intent: unknown; let standard: unknown; try { @@ -538,7 +549,7 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise>; + referenced = (module.xrefs ?? {}) as GivenXrefs; intent = module.intent; standard = module.standard; } catch (thrown) { @@ -552,7 +563,12 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { - const given = givenDrawings(library, shown, referenced, previews); - const drawn = Object.fromEntries( - [...given.values()].filter((g) => g.errors.length === 0).map((g) => [g.name, g.drawing]), - ); - const linted = [ - ...found, - ...[...given].flatMap(([xref, g]) => g.errors.map((d) => inGiven(xref, g, d))), - ] + const given = givenDrawings(library, shown, exported, previews); + const drawn = drawnOf(given); + const linted = [...found, ...givenErrors(given, [])] .sort(errorsFirst) .map((d) => aboutEntity(library, shown, drawn, d)); timings.lint ??= now() - t; @@ -597,7 +608,7 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise>, + referenced: GivenXrefs, found: Diagnostic, ): BuildDiagnostic { const d = withPath(found); @@ -737,7 +748,7 @@ function aboutEntity( function textWarnings( library: Library, drawing: Drawing, - referenced: Readonly>, + referenced: GivenXrefs, drawNoPlot: boolean, ): BuildDiagnostic[] { try { @@ -825,20 +836,42 @@ function missingFile(thrown: unknown): FileVersion[] { /** * Says what is wrong with an `xrefs` export, or returns undefined: it is an object that gives - * a drawing for each xref the pictures are to draw, by the xref's name. + * a drawing for each xref the pictures are to draw, by the xref's name, as a Drawing or as + * `{ drawing, xrefs }` with the drawings that drawing's own xrefs stand for. */ function notXrefs(value: unknown): string | undefined { if (value === undefined) return undefined; const shape = - "The export `xrefs` must be an object that gives a Drawing for an xref's name, such as `export const xrefs = { BASE: base }`"; - if (typeof value !== "object" || value === null || Array.isArray(value)) return shape; - for (const [name, drawing] of Object.entries(value)) { - if (notADrawing(drawing, true)) return `${shape}. Its ${JSON.stringify(name)} is not a Drawing`; + "The export `xrefs` must be an object that gives a Drawing, or { drawing, xrefs } with the drawings of that drawing's own xrefs, for an xref's name, such as `export const xrefs = { BASE: base }`"; + // Each object given is checked once, so a circle of them ends. + const seen = new Set(); + const open: [xrefs: unknown, at: string][] = [[value, ""]]; + for (let next = open.pop(); next !== undefined; next = open.pop()) { + const [xrefs, at] = next; + if (typeof xrefs !== "object" || xrefs === null || Array.isArray(xrefs)) { + return at === "" ? shape : `${shape}. Its ${at} is not an object`; + } + if (seen.has(xrefs)) continue; + seen.add(xrefs); + for (const [name, given] of Object.entries(xrefs)) { + const here = `${at}${at === "" ? "" : " > "}${JSON.stringify(name)}`; + const { drawing, xrefs: inner } = givenOf(given); + if (notADrawing(drawing, true)) return `${shape}. Its ${here} is not a Drawing`; + if (inner !== undefined) open.push([inner, `xrefs of ${here}`]); + } } return undefined; } -/** Says what is wrong with a default export that is not a `Drawing`, or returns undefined. */ +/** The drawing a value of the `xrefs` export gives, and what it gives for that drawing's xrefs. */ +function givenOf(value: unknown): { readonly drawing: unknown; readonly xrefs: unknown } { + if (typeof value === "object" && value !== null && "drawing" in value) { + const nested = value as { readonly drawing: unknown; readonly xrefs?: unknown }; + return { drawing: nested.drawing, xrefs: nested.xrefs }; + } + return { drawing: value, xrefs: undefined }; +} + function notADrawing(value: unknown, hasDefault: boolean): string | undefined { if (!hasDefault) { return "The file has no default export. End it with `export default d.build()`"; @@ -1101,30 +1134,113 @@ interface Given { readonly preview: boolean; /** The errors `lint` finds in it. A drawing with any is not drawn. */ readonly errors: readonly Diagnostic[]; + /** What the file gives for each attachment of `drawing` that the pictures draw. */ + readonly nested: ReadonlyMap; } /** * The drawing given for each xref of the drawing, checked by the library that checks the - * drawing. A preview stands for an xref the file's `xrefs` gives no drawing for. + * drawing. A preview stands for an xref the file's `xrefs` gives no drawing for. Below them, each + * drawing the library's `drawnXrefs` says the pictures draw. Each drawing is linted once. */ function givenDrawings( library: Library, drawing: Drawing, - referenced: Readonly>, + referenced: GivenXrefs, previews: readonly (readonly [name: string, preview: Drawing])[], ): Map { - const given = new Map(); - const offered = [ - ...Object.entries(referenced).map(([name, other]) => [name, other, false] as const), - ...previews.map(([name, preview]) => [name, preview, true] as const), - ]; - for (const [name, other, preview] of offered) { + const linted = new Map(); + const errorsOf = (other: Drawing): readonly Diagnostic[] => { + let found = linted.get(other); + if (!found) { + found = library.lint(other).filter((d) => d.severity === "error"); + linted.set(other, found); + } + return found; + }; + // The file's own drawings for the xrefs come first, and a preview stands for one it does not + // give. + const exported = new Set(); + const taken = new Set(); + // An xref may be named `__proto__`, which an object with a prototype would not keep. + const offered: Record = Object.create(null); + for (const [name, value, own] of [ + ...Object.entries(referenced).map(([name, value]) => [name, value, true] as const), + ...previews.map(([name, preview]) => [name, preview, false] as const), + ]) { const xref = xrefNamed(library, drawing, name); - if (!xref || given.has(xref)) continue; - const errors = library.lint(other).filter((d) => d.severity === "error"); - given.set(xref, { name, drawing: other, preview, errors }); + if (!xref || taken.has(xref)) continue; + taken.add(xref); + if (own) exported.add(xref); + offered[name] = value; } - return given; + /** What is given for the xrefs of `of`, as the library draws it. */ + const read = (of: Drawing, tree: GivenXrefs, top: boolean): Map => { + const out = new Map(); + for (const [name, value] of Object.entries(tree)) { + const xref = xrefNamed(library, of, name); + if (!xref || out.has(xref)) continue; + const { drawing: other, xrefs } = givenOf(value) as { drawing: Drawing; xrefs?: GivenXrefs }; + const errors = errorsOf(other); + const below = + errors.length > 0 || xrefs === undefined ? new Map() : read(other, xrefs, false); + const preview = top && !exported.has(xref); + out.set(xref, { name, drawing: other, preview, errors, nested: below }); + } + return out; + }; + const drawn = library.drawnXrefs?.(drawing, offered) ?? flatOf(library, drawing, offered); + return read(drawing, drawn, true); +} + +/** The export `xrefs` with the first of its names for each xref of the drawing, and no other. */ +function exportedXrefs(library: Library, drawing: Drawing, referenced: GivenXrefs): GivenXrefs { + const taken = new Set(); + const out: Record = Object.create(null); + for (const [name, value] of Object.entries(referenced)) { + const xref = xrefNamed(library, drawing, name); + if (!xref || taken.has(xref)) continue; + taken.add(xref); + out[name] = value; + } + return out; +} + +/** What a copy of tsdraft from before attachments draws: each drawing given alone, as given. */ +function flatOf(library: Library, drawing: Drawing, offered: GivenXrefs): GivenXrefs { + return Object.fromEntries( + Object.entries(offered).flatMap(([name, value]) => { + const { drawing: other } = givenOf(value); + return xrefNamed(library, drawing, name) && other !== drawing ? [[name, other]] : []; + }), + ); +} + +/** What the pictures are given for the xrefs: each drawing given with no lint error. */ +function drawnOf(given: ReadonlyMap): Record { + return Object.fromEntries( + [...given.values()] + .filter((g) => g.errors.length === 0) + .map((g) => [ + g.name, + g.nested.size > 0 ? { drawing: g.drawing, xrefs: drawnOf(g.nested) } : g.drawing, + ]), + ); +} + +/** Every drawing the pictures are given for an xref, at any depth. */ +function drawingsOf(given: ReadonlyMap): Drawing[] { + return [...given.values()].flatMap((g) => + g.errors.length === 0 ? [g.drawing, ...drawingsOf(g.nested)] : [], + ); +} + +/** The errors of each drawing given, as problems of the chain of xrefs that leads to it. */ +function givenErrors(given: ReadonlyMap, chain: readonly string[]): Diagnostic[] { + return [...given].flatMap(([xref, g]) => { + const here = [...chain, xref.name]; + return [...g.errors.map((d) => inGiven(here, g, d)), ...givenErrors(g.nested, here)]; + }); } /** @@ -1176,43 +1292,91 @@ function standardSummary(standard: unknown, checked: boolean): StandardSummary | /** * A problem in the drawing given for an xref, as a problem of the xref. It keeps the rule, the * id and the call, and leaves out the entity's index, which counts another drawing's entities. + * `chain` runs from the xref of the drawing down to the xref the drawing is given for. */ -function inGiven(xref: Xref, given: Given, found: Diagnostic): Diagnostic { +function inGiven(chain: readonly string[], given: Given, found: Diagnostic): Diagnostic { const what = given.preview ? "its title block's preview" : "the drawing given for it"; return { rule: found.rule, severity: found.severity, - message: `Xref ${JSON.stringify(xref.name)}: ${what} has an error, so it is not drawn. ${found.message}`, - xref: xref.name, + message: `Xref ${chain.map((name) => JSON.stringify(name)).join(" > ")}: ${what} has an error, so it is not drawn. ${found.message}`, + xref: chain[0]!, ...(found.id === undefined ? {} : { id: found.id }), ...(found.call === undefined ? {} : { call: found.call }), }; } +/** + * Each xref of the drawing. For a drawing drawn inside another, `referenced`, only what its + * model space reaches is drawn, directly or through its blocks, so only those inserts count. + */ function xrefSummaries( library: Library, drawing: Drawing, given: ReadonlyMap, + referenced = false, + counts = new Map>(), ): XrefSummary[] { - const placed = new Map(); - for (const entities of [ - drawing.entities, - ...(drawing.blocks ?? []).map((b) => b.entities), - ...sheetEntities(drawing), - ]) { - for (const e of entities) { + // A drawing given at many places is counted once, and each name in it looked up once: one + // drawn inside another has passed lint, so its names are short. + let placed = referenced ? counts.get(drawing) : undefined; + if (!placed) { + placed = new Map(); + const named = new Map(); + const xrefOf = (name: string): Xref | undefined => { + if (!referenced) return xrefNamed(library, drawing, name); + if (!named.has(name)) named.set(name, xrefNamed(library, drawing, name)); + return named.get(name); + }; + const lists = referenced + ? reached(library, drawing) + : [ + drawing.entities, + ...(drawing.blocks ?? []).map((b) => b.entities), + ...sheetEntities(drawing), + ]; + for (const entities of lists) { + for (const e of entities) { + if (e.kind !== "insert") continue; + const xref = xrefOf(e.block); + placed.set(xref, (placed.get(xref) ?? 0) + 1); + } + } + if (referenced) counts.set(drawing, placed); + } + return (drawing.xrefs ?? []).map((x) => { + const found = given.get(x); + const inserts = placed.get(x) ?? 0; + const shown = found?.errors.length === 0; + return { + name: x.name, + path: x.path, + attach: x.attach === true, + inserts, + shown, + units: found?.drawing.units ?? null, + xrefs: shown ? xrefSummaries(library, found.drawing, found.nested, true, counts) : [], + }; + }); +} + +/** Model space and each block it reaches through its inserts, once each. */ +function reached(library: Library, drawing: Drawing): (readonly Entity[])[] { + const lists: (readonly Entity[])[] = [drawing.entities]; + const seen = new Set(); + // Each name is looked up once: the drawing has passed lint, so its names are short. + const named = new Map(); + for (let at = 0; at < lists.length; at++) { + for (const e of lists[at]!) { if (e.kind !== "insert") continue; - const xref = xrefNamed(library, drawing, e.block); - placed.set(xref, (placed.get(xref) ?? 0) + 1); + if (!named.has(e.block)) named.set(e.block, blockNamed(library, drawing, e.block)); + const block = named.get(e.block); + if (!block || seen.has(block)) continue; + seen.add(block); + lists.push(block.entities); } } - return (drawing.xrefs ?? []).map((x) => ({ - name: x.name, - path: x.path, - inserts: placed.get(x) ?? 0, - shown: given.get(x)?.errors.length === 0, - units: given.get(x)?.drawing.units ?? null, - })); + return lists; } function insertSummaries( diff --git a/cli/test/render.test.ts b/cli/test/render.test.ts index 9c9dbc5..ed14f1d 100644 --- a/cli/test/render.test.ts +++ b/cli/test/render.test.ts @@ -303,9 +303,33 @@ test("the state lists each xref, and the pictures draw the ones the file gives a const { state } = render(plan); assert.equal(state.drawing?.counts.xrefs, 3); assert.deepEqual(state.drawing?.xrefs, [ - { name: "BASE", path: "../civil/base.dwg", inserts: 2, shown: true, units: "ft" }, - { name: "SURVEY", path: "survey.dwg", inserts: 1, shown: false, units: null }, - { name: "SPARE", path: "spare.dwg", inserts: 0, shown: false, units: null }, + { + name: "BASE", + path: "../civil/base.dwg", + attach: false, + inserts: 2, + shown: true, + units: "ft", + xrefs: [], + }, + { + name: "SURVEY", + path: "survey.dwg", + attach: false, + inserts: 1, + shown: false, + units: null, + xrefs: [], + }, + { + name: "SPARE", + path: "spare.dwg", + attach: false, + inserts: 0, + shown: false, + units: null, + xrefs: [], + }, ]); assert.deepEqual( state.drawing?.inserts.map((i) => [i.block, i.xref]), @@ -389,6 +413,123 @@ test("the state lists each xref, and the pictures draw the ones the file gives a file("export const xrefs = { BASE: 5 };"); assert.match(render(plan).state.error!.message, /The export `xrefs` must be an object/); + file("export const xrefs = { BASE: { drawing: 5 } };"); + assert.match(render(plan).state.error!.message, /Its "BASE" is not a Drawing$/); +}); + +test("the pictures draw an attachment inside a drawing the file gives with its xrefs, and no overlay there", () => { + const dir = realpathSync(tempDir()); + const drawing = (layer: string, entities: unknown[], xrefs?: unknown[]) => ({ + format: 0, + units: "ft", + dxf: "R2018", + layers: [ + { name: "0", color: 7 }, + { name: layer, color: 1 }, + ], + entities, + ...(xrefs ? { xrefs } : {}), + }); + const line = (layer: string) => ({ kind: "line", layer, from: [0, 0], to: [1, 0] }); + const insert = (block: string, x: number) => ({ kind: "insert", layer: "0", block, at: [x, 0] }); + const detail = drawing("D", [line("D")]); + const survey = drawing("S", [line("S")]); + const model = drawing( + "M", + [line("M"), insert("DETAIL", 10), insert("SURVEY", 20)], + [ + { name: "DETAIL", path: "detail.dwg", attach: true }, + { name: "SURVEY", path: "survey.dwg" }, + ], + ); + const sheet = drawing("X", [insert("MODEL", 100)], [{ name: "MODEL", path: "model.dwg" }]); + const plan = join(dir, "plan.ts"); + const file = (detailGiven: unknown): void => + writeFileSync( + plan, + `export const xrefs = { MODEL: { drawing: ${JSON.stringify(model)}, xrefs: { DETAIL: ${JSON.stringify(detailGiven)}, SURVEY: ${JSON.stringify(survey)} } } };\nexport default ${JSON.stringify(sheet)};\n`, + ); + file(detail); + const { state, status } = render(plan, "--out", dir); + assert.equal(status, 0); + const svg = readFileSync(state.outputs.svg!, "utf8"); + assert.match(svg, /]*data-layer="DETAIL\|D"\/>/); + assert.doesNotMatch(svg, /SURVEY/); + const summary = (name: string, path: string, attach: boolean, shown: boolean) => ({ + name, + path, + attach, + inserts: 1, + shown, + units: shown ? "ft" : null, + xrefs: [], + }); + assert.deepEqual(state.drawing?.xrefs, [ + { + ...summary("MODEL", "model.dwg", false, true), + xrefs: [ + summary("DETAIL", "detail.dwg", true, true), + summary("SURVEY", "survey.dwg", false, false), + ], + }, + ]); + assert.deepEqual( + state.diagnostics.map((d) => [d.rule, d.severity, d.xref, d.message]), + [ + [ + "xref", + "warning", + "MODEL", + 'Xref "MODEL" > "SURVEY": "SURVEY" is an overlay of the drawing given for "MODEL", and the leading CAD app draws no overlay of a referenced drawing, so the drawing given for it is not drawn', + ], + ], + ); + // An attachment the model places only on a sheet of its own is placed nowhere drawn: CAD draws + // a referenced drawing's model space alone. + const sheetOnly = { + ...model, + entities: [line("M"), insert("SURVEY", 20)], + layouts: [{ name: "M-1", paper: "ANSI B", viewports: [], entities: [insert("DETAIL", 1)] }], + }; + writeFileSync( + plan, + `export const xrefs = { MODEL: { drawing: ${JSON.stringify(sheetOnly)}, xrefs: { DETAIL: ${JSON.stringify(detail)} } } };\nexport default ${JSON.stringify(sheet)};\n`, + ); + const onSheet = render(plan, "--out", dir); + assert.deepEqual( + onSheet.state.drawing?.xrefs[0]?.xrefs.map((x) => [x.name, x.inserts, x.shown]), + [ + ["DETAIL", 0, true], + ["SURVEY", 1, false], + ], + ); + assert.doesNotMatch(readFileSync(onSheet.state.outputs.svg!, "utf8"), /DETAIL\|/); + // The export's first name for an xref is the one drawn and checked, and an xref may be named + // `__proto__`. + writeFileSync( + plan, + `export const xrefs = { MODEL: { drawing: ${JSON.stringify(model)}, xrefs: { DETAIL: ${JSON.stringify(detail)}, SURVEY: ${JSON.stringify(survey)} } }, model: ${JSON.stringify(model)}, ["__proto__"]: ${JSON.stringify(detail)} };\nexport default ${JSON.stringify({ ...sheet, entities: [...sheet.entities, insert("__proto__", 200)], xrefs: [...sheet.xrefs!, { name: "__proto__", path: "proto.dwg" }] })};\n`, + ); + const aliased = render(plan, "--out", dir); + const aliasedSvg = readFileSync(aliased.state.outputs.svg!, "utf8"); + assert.match(aliasedSvg, /data-layer="DETAIL\|D"/); + assert.match(aliasedSvg, /data-layer="__proto__\|D"/); + assert.deepEqual( + aliased.state.diagnostics.map((d) => d.message.slice(0, 26)), + ['Xref "MODEL" > "SURVEY": "'], + ); + // A drawing given inside another is checked too, and one with an error is not drawn. + file(drawing("D", [{ kind: "circle", layer: "D", center: [0, 0], radius: -5 }])); + const broken = render(plan, "--out", dir); + assert.equal(broken.status, 2); + assert.equal(broken.state.drawing?.xrefs[0]?.xrefs[0]?.shown, false); + const error = broken.state.diagnostics.find((d) => d.severity === "error"); + assert.match( + error?.message ?? "", + /^Xref "MODEL" > "DETAIL": the drawing given for it has an error, so it is not drawn\./, + ); + assert.equal(error?.xref, "MODEL"); + assert.doesNotMatch(readFileSync(broken.state.outputs.svg!, "utf8"), /DETAIL\|/); }); test("a drawing file Node reads as CommonJS says how to make it a module", () => { @@ -767,7 +908,15 @@ test("a drawing with a layout gets a picture of its sheet, and the state says wh { name: "TITLE BLOCK", entities: 0, attributes: ["SHEET", "DATE"], inserts: 1 }, ]); assert.deepEqual(state.drawing?.xrefs, [ - { name: "BORDER", path: "border.dwg", inserts: 1, shown: false, units: null }, + { + name: "BORDER", + path: "border.dwg", + attach: false, + inserts: 1, + shown: false, + units: null, + xrefs: [], + }, ]); // Model space has no text. The sheet has text in both fonts, and the PNG sets an SHX font // in the renderer's own face. @@ -1213,7 +1362,15 @@ ${exported}\n`, }; const preview = sheet(""); assert.deepEqual(preview.xrefs, [ - { name: "BORDER", path: "border.dwg", inserts: 1, shown: true, units: "in" }, + { + name: "BORDER", + path: "border.dwg", + attach: false, + inserts: 1, + shown: true, + units: "in", + xrefs: [], + }, ]); assert.ok(preview.layers.has("BORDER|PREVIEW")); // The file's own drawing for the xref, by any case of its name, is drawn in its place. diff --git a/docs/command.md b/docs/command.md index f3eba4d..879dac0 100644 --- a/docs/command.md +++ b/docs/command.md @@ -157,18 +157,29 @@ dimension in model space: its `entity` index, `id`, `layer`, `kind`, which is `l `aligned`, `style`, `measurement`, the length it measures in drawing units, and `text`, the string the leading CAD app draws for it. The last two are `null` for a dimension whose style the drawing does not define. A layout's `dimensions` lists those on its sheet in the same way. -`drawing.xrefs` gives each xref's `name`, its `path`, how many `inserts` place it, in model -space, in blocks and on layouts, `shown` and `units`. The command opens no DWG file. It draws an xref when +`drawing.xrefs` gives each xref's `name`, its `path`, whether it is an `attach`ment or an +overlay, how many `inserts` place it, in model space, in blocks and on layouts, `shown`, `units` +and `xrefs`. The command opens no DWG file. It draws an xref when the drawing file has a named export `xrefs`, an object that gives a `Drawing` under the xref's name, such as `export const xrefs = { BASE: base }`. `shown` says that the pictures drew that -drawing. The command cannot tell whether it is what the file at `path` holds, so `shown` is +drawing. Given as `{ drawing, xrefs }`, such as +`export const xrefs = { MODEL: { drawing: model, xrefs: { SURVEY: survey } } }`, a drawing's own +attachments are drawn too, from the drawings its `xrefs` gives, and so on down, and its +overlays are not, as CAD loads them. An xref's `xrefs` then lists the xrefs of the drawing drawn +for it, each in the same way, and is empty when it is not shown. There `inserts` counts only +what the drawing's model space reaches, directly or through its blocks, since CAD draws nothing +else of a referenced drawing. `lint` warns, with the `xref` +under which it is, of a drawing given that is not drawn: an overlay inside a referenced +drawing, a circular reference, which CAD breaks, or a chain more than `XREF_DEPTH`, 16, +drawings down. The command cannot tell whether it is what the file at `path` holds, so `shown` is about the pictures and not about what CAD will load. When `xrefs` gives no drawing for an xref that is the border of a title block of the file's `standard`, and the command checked the standard and found no error, the pictures draw the title block's `preview` in its place, and `shown` is true. `units` is the units of the drawing drawn, or `null` when there is none: where they differ from the drawing's own, each insert needs the -scale between the two. The command runs `lint` on each drawing it is given. One with an error -is not drawn, its `shown` is false, and each error is in `diagnostics` with the `xref` it -belongs to, counted in `counts.errors`. An xref that is not shown is left out of the pictures +scale between the two. The command runs `lint` on each drawing it is given that it draws, at +any depth. One with an error is not drawn, its `shown` is false, and each error is in `diagnostics` with the +`xref` of the drawing it is under and the chain of xrefs in its message, counted in +`counts.errors`. An xref that is not shown is left out of the pictures and of `drawing.extents`. `drawing.layouts` gives each layout: its `name`, its `paper`, its `paperUnits`, `width` and `height`, its `plotStyle`, how many `entities` are on its sheet, and each viewport, with its `id`, its `layer`, whether its `border` plots, its `rectangle` on the sheet, its `ratio`, the diff --git a/docs/plotting.md b/docs/plotting.md index 5c8f12d..9caeba3 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -17,8 +17,9 @@ writeFileSync("A-101.pdf", toPDF(drawing, { layouts: ["A-101"], xrefs, deflate } - `layouts` names the layouts to plot, in the order of the pages. Without it, every layout is plotted in the drawing's order, which is the order of its tabs. -- `xrefs` gives the drawing each xref stands for, by the xref's name, as `toSVG` takes them. An - xref with no drawing given plots nothing. +- `xrefs` gives the drawing each xref stands for, by the xref's name, as `toSVG` takes them: a + `Drawing`, or `{ drawing, xrefs }` with the drawings its own xrefs stand for, so that it plots + its attachments. An xref with no drawing given plots nothing. - `deflate` compresses each page: a function that gives the zlib form of its bytes, such as Node's `zlib.deflateSync`. The library imports nothing, so without it the pages are written as they are, and the file is several times larger. It is called as the PDF is written, so it @@ -51,8 +52,9 @@ preview shows it: `monochrome.ctb`, and as wide as its lineweight on the paper, with round ends and joins. `DWF Virtual Pens.ctb` plots every line 0.254 mm wide. - A layer that is off, frozen or set not to plot is left out, and so is everything an insert or - an xref places on such a layer. An xref of a drawing an xref places is not drawn: a drawing's - overlays are its own. A viewport leaves out the layers frozen in it alone, and turns its view + an xref places on such a layer. A drawing an xref places plots its attachments, from the + drawings given with it, and not its overlays, as [Nested xrefs](xrefs.md#nested-xrefs) says: + a drawing's overlays are its own. A viewport leaves out the layers frozen in it alone, and turns its view by its twist, as [Frozen layers and a twist](layouts.md#frozen-layers-and-a-twist) says. - A curve strays from its arc by at most 1/1000 inch on the paper. - A dash pattern is sized on the paper and fitted to each line, side of a polyline, arc and diff --git a/docs/xrefs.md b/docs/xrefs.md index 9e161f5..590a1aa 100644 --- a/docs/xrefs.md +++ b/docs/xrefs.md @@ -38,9 +38,18 @@ toSVG(sheet, { xrefs: { BASE: base } }); // draws the base under the notes - An xref has no entities, no base point and no attribute definitions of its own. Its file has them. -tsdraft writes every xref as an overlay. The leading CAD app loads an overlay for the drawing that -references it and not for a third drawing that references that one, so two drawings can -overlay each other. +An xref is an overlay unless you attach it: + +```ts +d.xref("SURVEY", "survey.dwg"); // an overlay +d.xref("BASE", "base.dwg", { attach: true }); // an attachment +``` + +The leading CAD app loads an overlay for the drawing that references it and not for a third +drawing that references that one, so two drawings can overlay each other. It loads an +attachment for every drawing above it too: a sheet that references a model draws the base the +model attaches, and not the survey the model overlays. Attach what every sheet of a model must +show, and overlay what only the model needs. The leading CAD app draws the model space of the file and nothing of its layouts. @@ -159,10 +168,11 @@ An insert with an id has the handle `idHandle(id)`. A drawing that has an xref h ## Cycles -Two drawings that reference each other cannot be seen from one of them, so `lint` has no rule -for it. With overlays, which is all tsdraft writes, the leading CAD app loads the other drawing and -not that drawing's own overlays, and reports nothing. A drafter who changes an overlay to an -attachment in CAD can make a cycle, which that app breaks and reports as a circular reference. +Two drawings that reference each other cannot be seen from one of them, so `lint` of a drawing +alone has no rule for it. With overlays the leading CAD app loads the other drawing and not +that drawing's own overlays, and reports nothing. Two drawings that attach each other make a +circular reference, which that app breaks where it would load a drawing a second time, and +reports. `lint` with the drawings given, below, reports it too. ## The preview @@ -179,8 +189,36 @@ toSVG(sheet, { xrefs: { BASE: base } }); - The extents take in the box of what each insert draws, as they do for a block. - An xref with no drawing given draws nothing: its group is empty, and the extents leave it out. -- The xrefs of the drawing you gave are not drawn, as the leading CAD app loads no overlay of an - overlay. +- The xrefs of a drawing you gave alone are not drawn. + +### Nested xrefs + +Give a drawing as `{ drawing, xrefs }` to draw what it attaches, with the drawings its own +xrefs stand for, and so on down: + +```ts +toSVG(sheet, { + xrefs: { MODEL: { drawing: model, xrefs: { BASE: base, SURVEY: survey } } }, +}); +``` + +- An attachment of the model draws its drawing inside the model's group, where the model's + insert puts it. An element on one of its layers has `data-layer="BASE|C-BLDG"`, by the + attachment's own name. +- An overlay of the model draws nothing, though a drawing is given for it, as the leading CAD app + loads no overlay of a referenced drawing. +- A drawing that the chain above already draws, your own included, is a circular reference. It + is not drawn again there, as the leading CAD app breaks the circle there. +- A chain is drawn `XREF_DEPTH`, 16, drawings down, and no further. +- Past 4,096 names given inside referenced drawings, none of them is drawn: only the drawings + given for your drawing's own xrefs are. +- `toPDF` takes the same `xrefs`. `inspectText` takes them too, and checks the texts of the + drawings given for your drawing's own xrefs, not of what those attach. +- `drawnXrefs(sheet, xrefs)` gives what the picture draws of what you gave, in the same form. + +`lint(sheet, { xrefs })` warns of each drawing given that is not drawn for one of these reasons, +with the chain of names, such as `Xref "MODEL" > "SURVEY"`, and the first name in `xref`. It does +not check the drawings given: lint each on its own. `findXref(drawing, name)` returns the xref an insert of a name places. @@ -193,8 +231,11 @@ export const xrefs = { BASE: base }; export default d.build(); ``` +Give a drawing as `{ drawing, xrefs }` there too, to draw what it attaches. + The pictures then draw the base, and `drawing.xrefs` in the JSON says so with `shown: true`, -beside the `units` of the drawing you gave. `shown` is about the pictures: the command does -not read DWG files, so it cannot tell whether the drawing you exported is what the file at the -path holds. It runs `lint` on each drawing you give, and one with an error is reported and not -drawn. See [The tsdraft command](command.md). +beside the `units` of the drawing you gave, and its own xrefs in `xrefs`. `shown` is about the +pictures: the command does not read DWG files, so it cannot tell whether the drawing you +exported is what the file at the path holds. It runs `lint` on each drawing you give that it +draws, at any depth, and one with an error is reported and not drawn. See +[The tsdraft command](command.md). diff --git a/src/blocks.ts b/src/blocks.ts index b03752c..7d7c1bf 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -14,7 +14,14 @@ import type { import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; import { written } from "./format.ts"; -import { attributeTagProblem, blockNameProblem, idKey, idProblem } from "./rules.ts"; +import { + attributeTagProblem, + blockNameProblem, + idKey, + idProblem, + XREF_DEPTH, + XREF_LOOKS, +} from "./rules.ts"; import { filled } from "./shape.ts"; /** A map of the plane: `x' = a x + c y + e` and `y' = b x + d y + f`. */ @@ -317,12 +324,33 @@ export function attributeText(insert: Insert, definition: AttributeDefinition): return text as unknown as Text; } +/** + * The drawing an xref stands for, with the drawings its own xrefs stand for, by their names in + * it. Only its attachments are drawn: the leading CAD app loads no overlay of a referenced + * drawing. + */ +export interface XrefDrawing { + readonly drawing: Drawing; + readonly xrefs?: XrefDrawings; +} + +/** + * The drawing each xref stands for, by the xref's name: a `Drawing`, which draws none of its + * own xrefs, or an `XrefDrawing`, which gives the drawings its attachments stand for. + */ +export type XrefDrawings = Readonly>; + +/** The most problems `referencedTree` names: past them it counts them. */ +const XREF_PROBLEMS = 64; + /** A drawing that an xref stands for, under the xref's name in the drawing that references it. */ export interface Referenced { readonly name: string; readonly drawing: Drawing; /** The drawing's blocks, as `blocksByKey` gives them. */ readonly blocks: ReadonlyMap; + /** The drawings its attachments stand for, by `layerKey` of each xref's name. */ + readonly xrefs: ReadonlyMap; } /** A layer by its name: one of the drawing's own, or one of a drawing it references. */ @@ -332,25 +360,222 @@ export interface LayerRef { readonly of?: Referenced; } +/** + * Why a drawing given for an xref is not drawn: it stands for an overlay of a referenced + * drawing, for a drawing the chain above it already draws, past `XREF_DEPTH` drawings down, or + * it is neither a `Drawing` nor an `XrefDrawing`; or, with no chain, the names given inside + * referenced drawings passed `XREF_LOOKS`, so no drawing below the drawing's own xrefs is drawn. + */ +export interface XrefProblem { + readonly kind: "overlay" | "cycle" | "deep" | "many" | "shape"; + /** The names of the xrefs from one of the drawing's own down to the one not drawn. */ + readonly chain: readonly string[]; +} + +const NO_XREFS: ReadonlyMap = new Map(); +const NO_VALUES: ReadonlyMap = new Map(); +const NO_BLOCKS: ReadonlyMap = new Map(); + +/** + * The longest name of a block, and so of an xref. A longer name names no xref the walk can find, + * and is never a key of its maps, since V8 hashes a long string by its length alone. + */ +const LONGEST_NAME = 255; + +/** True for a value with what every drawing has: a list of layers and of entities, and units. */ +function drawingLike(value: unknown): value is Drawing { + if (typeof value !== "object" || value === null) return false; + const { layers, entities, units } = value as Partial; + return Array.isArray(layers) && Array.isArray(entities) && typeof units === "string"; +} + +/** + * What a picture of `drawing` draws of the drawings given in `xrefs`: each drawing given for + * one of its xrefs, and below it each drawing given for an attachment, as `toSVG` follows them, + * by the xref's name. A drawing that draws none of its own xrefs is given alone. Giving the + * result, or the result with drawings left out, draws the same, less what was left out. + */ +export function drawnXrefs(drawing: Drawing, xrefs: XrefDrawings | undefined): XrefDrawings { + const out = (tree: ReadonlyMap): Record => + Object.fromEntries( + [...tree.values()].map((r) => [ + r.name, + r.xrefs.size > 0 ? { drawing: r.drawing, xrefs: out(r.xrefs) } : r.drawing, + ]), + ); + return out(referencedTree(drawing, xrefs, () => NO_BLOCKS).xrefs); +} + /** * The drawings to draw for the xrefs of `drawing`, by `layerKey` of each xref's name, from * drawings given by name. A name that matches no xref of the drawing is left out. */ export function referencedByKey( drawing: Pick, - given: Readonly> | undefined, + given: XrefDrawings | undefined, ): Map { - const out = new Map(); - if (given === undefined) return out; - const byKey = new Map(Object.keys(given).map((name) => [layerKey(name), given[name]!])); - for (const xref of filled(drawing.xrefs)) { - const key = layerKey(xref.name); - const found = byKey.get(key); - if (found !== undefined && !out.has(key)) { - out.set(key, { name: xref.name, drawing: found, blocks: blocksByKey(found.blocks) }); + return referencedTree(drawing, given).xrefs; +} + +/** + * The drawings to draw for the xrefs of `drawing`, as `referencedByKey` gives them, and why + * any drawing given is not drawn. Inside a referenced drawing it follows an attachment and + * never an overlay, as the leading CAD app loads one. A drawing already on the chain above, + * `drawing` itself included, is a circular reference, which that app breaks, and is not drawn + * again. It follows a chain `XREF_DEPTH` drawings down. Past `XREF_LOOKS` names looked for + * inside referenced drawings it follows none: so a picture given a part of what was given cuts + * nothing that the whole did not. It reads each object given, each list of xrefs and each + * referenced drawing's blocks once. + * + * @param blocksOf - The blocks of a referenced drawing, `blocksByKey` unless they are not wanted. + */ +export function referencedTree( + drawing: Pick, + given: unknown, + blocksOf: (drawing: Drawing) => ReadonlyMap = (d) => blocksByKey(d.blocks), +): { + readonly xrefs: Map; + /** The first `XREF_PROBLEMS` problems. */ + readonly problems: XrefProblem[]; + /** How many more there were. */ + readonly unreported: number; + /** How many of those were values that are no drawing. */ + readonly unreportedShapes: number; +} { + const top = new Map(); + const problems: XrefProblem[] = []; + let unreported = 0; + /** How many of those past the first `XREF_PROBLEMS` are of the drawing's own xrefs. */ + let outside = 0; + /** How many of those are values that are no drawing, of any xref and of the drawing's own. */ + let shapes = 0; + let outsideShapes = 0; + const note = (kind: XrefProblem["kind"], chain: readonly string[]): void => { + if (problems.length < XREF_PROBLEMS) problems.push({ kind, chain }); + else { + unreported++; + if (kind === "shape") shapes++; + if (chain.length === 1) outside++; + if (chain.length === 1 && kind === "shape") outsideShapes++; } + }; + if (given === undefined) return { xrefs: top, problems, unreported, unreportedShapes: 0 }; + /** The values of an object given, by the key of each name, the last of a key kept. */ + const values = new WeakMap>(); + const valuesOf = (from: unknown): ReadonlyMap => { + if (typeof from !== "object" || from === null) return NO_VALUES; + let found = values.get(from); + if (!found) { + const read = new Map(); + for (const name of Object.keys(from)) { + if (name.length > LONGEST_NAME) continue; + read.set(layerKey(name), [name, (from as Record)[name]]); + } + values.set(from, (found = read)); + } + return found; + }; + /** + * The xrefs of a drawing, by key, the first of a key kept, as `findXref` finds them, read once + * for each list, which copies of a drawing may share. + */ + const xrefLists = new WeakMap>(); + const xrefsOf = (of: Pick): ReadonlyMap => { + const list: unknown = of.xrefs; + if (typeof list !== "object" || list === null) return new Map(); + let found = xrefLists.get(list); + if (!found) { + const read = new Map(); + for (const xref of filled(list)) { + const name: unknown = (xref as Xref | null)?.name; + if (typeof name !== "string" || name.length > LONGEST_NAME) continue; + const key = layerKey(name); + if (!read.has(key)) read.set(key, xref as Xref); + } + xrefLists.set(list, (found = read)); + } + return found; + }; + const blocks = new WeakMap>(); + /** A drawing given, and the drawings its xrefs stand for, still to look through. */ + interface Open { + readonly drawing: Pick; + readonly given: unknown; + readonly into: Map; + readonly chain: readonly string[]; + /** The drawings above it, from `drawing` itself down. */ + readonly above: readonly object[]; } - return out; + const queue: Open[] = [{ drawing, given, into: top, chain: [], above: [drawing] }]; + let looks = 0; + for (let at = 0; at < queue.length; at++) { + const open = queue[at]!; + const inside = open.chain.length > 0; + const given = valuesOf(open.given); + if (given.size === 0) continue; + const listed = xrefsOf(open.drawing); + for (const [key, [, value]] of given) { + // The drawing's own xrefs are read once. What a referenced drawing is given may be shared + // by many, so each name looked for there counts, and past the limit none is drawn. + if (inside && ++looks > XREF_LOOKS) { + for (const [name, referenced] of top) top.set(name, { ...referenced, xrefs: NO_XREFS }); + const outer = problems.filter((problem) => problem.chain.length === 1); + return { + xrefs: top, + problems: [...outer, { kind: "many", chain: [] }], + unreported: outside, + unreportedShapes: outsideShapes, + }; + } + const xref = listed.get(key); + if (xref === undefined || value === undefined) continue; + const chain = [...open.chain, xref.name]; + // An xref of the drawing itself is drawn whatever it is, and one inside another only + // when it is attached. + if (inside && xref.attach !== true) { + note("overlay", chain); + continue; + } + const nested = typeof value === "object" && value !== null && "drawing" in value; + const found: unknown = nested ? (value as XrefDrawing).drawing : value; + const inner: unknown = nested ? (value as XrefDrawing).xrefs : undefined; + if ( + !drawingLike(found) || + (inner !== undefined && (typeof inner !== "object" || inner === null)) + ) { + note("shape", chain); + continue; + } + if (open.above.includes(found)) { + note("cycle", chain); + continue; + } + if (chain.length > XREF_DEPTH) { + note("deep", chain); + continue; + } + const referenced = found as Drawing; + let held = blocks.get(referenced); + if (!held) blocks.set(referenced, (held = blocksOf(referenced))); + const into = inner === undefined ? undefined : new Map(); + open.into.set(key, { + name: xref.name, + drawing: referenced, + blocks: held, + xrefs: into ?? NO_XREFS, + }); + if (into) { + queue.push({ + drawing: referenced, + given: inner, + into, + chain, + above: [...open.above, found], + }); + } + } + } + return { xrefs: top, problems, unreported, unreportedShapes: shapes }; } /** Where one entity is drawn. */ @@ -403,9 +628,10 @@ function holds(list: readonly unknown[], index: number): boolean { * * An insert of an xref draws the model space of the drawing given for it, as the leading CAD app * draws a loaded xref: an entity on layer `"0"` there draws as the insert's layer does, as in a - * block, and any other on its own layer of the referenced drawing. The xrefs of a referenced - * drawing are not drawn, as that app loads no overlay of an overlay. An xref with no drawing given - * draws nothing. + * block, and any other on its own layer of the referenced drawing. Inside a referenced drawing an + * insert of one of its attachments draws the drawing `referencedTree` gives for it, the same way, + * and one of its overlays draws nothing, as that app loads no overlay of a referenced drawing. An + * xref with no drawing given draws nothing. * * @param isFrozen - True for a layer that hides everything an insert on it draws: a frozen * layer, and in a plot a layer that does not plot. @@ -446,7 +672,7 @@ export function eachDrawn( if (isFrozen(layer)) return true; const name = key(insert.block); const block = within.get(name); - const referenced = block || from ? undefined : xrefs?.get(name); + const referenced = block ? undefined : (from ? from.xrefs : xrefs)?.get(name); const held = block ?? referenced; if (!held || open.has(held)) return true; if (!spend(1)) return false; diff --git a/src/drawing.ts b/src/drawing.ts index 1d72b4a..86ccb40 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -671,6 +671,11 @@ export interface Xref { * folders, such as `"base.dwg"` or `"..\\survey\\base.dwg"`. */ readonly path: string; + /** + * True for an attachment: a drawing that references this one draws the file too. An overlay, + * the default, is drawn only by the drawing that references it. + */ + readonly attach?: boolean; } /** @@ -2305,15 +2310,18 @@ export class DrawingBuilder< * xref has. `insert(name, at)` then places it, as it places a block, and the leading CAD app * loads the file and draws it there each time it opens this drawing. `path` leads from the folder * of this drawing's file to the DWG file, such as `"base.dwg"` or `"../survey/base.dwg"`. + * The xref is an overlay unless `attach` is true: a drawing that references this one draws an + * attachment too, and never an overlay. */ xref( name: V extends "R12" ? R12Xrefs : BlockName, path: V extends "R12" ? R12Xrefs : XrefPath

, + options: { readonly attach?: boolean } = {}, ): this { // The parameter type is the error message when a literal is wrong, so read it as a string. const requested = name as string; try { - this.#defineXref(requested, path); + this.#defineXref(requested, path, false, options?.attach); } catch (thrown) { throw located(thrown, DrawingBuilder.prototype.xref, { xref: requested }); } @@ -2324,12 +2332,15 @@ export class DrawingBuilder< * Checks an xref and stores it. With `shared`, an xref the drawing has of the same name and * path is the one it keeps, as a title block's border on each layout is. */ - #defineXref(requested: string, path: unknown, shared = false): void { + #defineXref(requested: string, path: unknown, shared = false, attach?: unknown): void { const fail = (rule: LintRule, problem: string): never => refuse(rule, `Xref ${JSON.stringify(requested)}: ${problem}`); if (this.dxf === "R12") fail("xref", R12_ONLY.xrefs); const nameProblem = blockNameProblem(requested); if (nameProblem) fail("xref", nameProblem); + if (attach !== undefined && typeof attach !== "boolean") { + fail("xref", "attach must be true or false"); + } if (shared && this.#xrefs.get(layerKey(requested))?.path === path) return; const first = this.#blocksAudited.get(layerAuditKey(requested)); if (first !== undefined) { @@ -2346,7 +2357,11 @@ export class DrawingBuilder< for (const handle of [handles.record, handles.begin, handles.end]) { this.#claim(handle, what, undefined, []); } - this.#xrefs.set(layerKey(requested), { name: requested, path: path as string }); + this.#xrefs.set(layerKey(requested), { + name: requested, + path: path as string, + ...(attach === true ? { attach: true } : {}), + }); this.#blocksAudited.set(layerAuditKey(requested), { name: requested, xref: true }); } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 6c0ec9d..7d1112a 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -550,6 +550,7 @@ export function toDXFR2018( writeBlock(g, handles.begin, handles.end, xref.name, handles.record, { paper: false, xrefPath: xref.path, + attach: xref.attach === true, }); } for (const { arrowhead, block } of arrowheads) { @@ -849,6 +850,8 @@ function writeBlock( readonly hasAttributes?: boolean; /** The path of the file an xref's block stands for. */ readonly xrefPath?: string; + /** True for an xref that is attached, and not an overlay. */ + readonly attach?: boolean; /** True for a block of no name of its own, such as a dimension's picture. */ readonly anonymous?: boolean; readonly contents?: () => void; @@ -864,7 +867,8 @@ function writeBlock( g(2, name); // 1: the block is anonymous. 2: it has attribute definitions. 4 and 8: it is an xref, and an // overlay. - g(70, block.anonymous ? 1 : block.xrefPath !== undefined ? 12 : block.hasAttributes ? 2 : 0); + const xref = block.attach === true ? 4 : 12; + g(70, block.anonymous ? 1 : block.xrefPath !== undefined ? xref : block.hasAttributes ? 2 : 0); point(g, 10, ...(block.base ?? [0, 0])); g(3, name); // The leading CAD app decodes a block's path once, where it decodes a text twice. diff --git a/src/extents.ts b/src/extents.ts index f268e07..74ca0e1 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -200,21 +200,17 @@ export function boxer( readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; readonly leaderStyles: ReadonlyMap; - /** Counts the drawings, from 0 for the drawing itself. */ - readonly index: number; } const namesOf = ( text: readonly TextStyle[] | undefined, dimensions: readonly DimensionStyle[] | undefined, leaders: readonly LeaderStyle[] | undefined, - index: number, ): Names => ({ textStyles: new Map(filled(text).map((t) => [layerKey(t.name), t])), dimensionStyles: new Map(filled(dimensions).map((style) => [layerKey(style.name), style])), leaderStyles: new Map(filled(leaders).map((style) => [layerKey(style.name), style])), - index, }); - const own = namesOf(textStyles, dimensionStyles, leaderStyles, 0); + const own = namesOf(textStyles, dimensionStyles, leaderStyles); // The names of each referenced drawing, worked out when one of its entities is first met. const referenced = new Map(); const byDrawing = new Map(); @@ -225,7 +221,7 @@ export function boxer( found = byDrawing.get(from.drawing); if (!found) { const { textStyles, dimensionStyles, leaderStyles } = from.drawing; - found = namesOf(textStyles, dimensionStyles, leaderStyles, byDrawing.size + 1); + found = namesOf(textStyles, dimensionStyles, leaderStyles); byDrawing.set(from.drawing, found); } referenced.set(from, found); @@ -428,7 +424,22 @@ export function boxer( return true; }; - /** Each block in each drawing, by the drawing and whether its layer `0` is hidden. */ + /** + * The places a block is held in, from 1: each referenced drawing with the drawings given for + * its attachments, which two places that give one drawing may give apart. The drawing itself + * is 0. + */ + const places = new Map>(); + let counted = 0; + const placeOf = (inside: Referenced | undefined): number => { + if (inside === undefined) return 0; + let byXrefs = places.get(inside.drawing); + if (!byXrefs) places.set(inside.drawing, (byXrefs = new Map())); + let place = byXrefs.get(inside.xrefs); + if (place === undefined) byXrefs.set(inside.xrefs, (place = ++counted)); + return place; + }; + /** Each block in each place, by the place and whether its layer `0` is hidden. */ const helds = new Map(); const heldOf = ( held: Block | Referenced, @@ -437,7 +448,7 @@ export function boxer( inner: ReadonlyMap, hidden: boolean, ): Held => { - const slot = names(inside).index * 2 + (hidden ? 1 : 0); + const slot = placeOf(inside) * 2 + (hidden ? 1 : 0); let all = helds.get(held); if (!all) helds.set(held, (all = [])); return (all[slot] ??= { @@ -469,7 +480,7 @@ export function boxer( if (!zero && isFrozen(layer)) return undefined; const name = key(insert.block); const block = within.inner.get(name); - const xref = block || inside ? undefined : xrefs?.get(name); + const xref = block ? undefined : (inside ? inside.xrefs : xrefs)?.get(name); const held = block ?? xref; if (!held) return undefined; const hidden = zero ? within.hidden : isHidden(layer); @@ -510,21 +521,25 @@ export function boxer( } return (slots[slot] = box); }; - /** The inserts of a list, found once, and the block or xref that first read them. */ - const insertLists = new WeakMap(); - /** Reads the inserts a block holds, once, and pays for a list read for another block. */ + /** The inserts of a list, found once, and the block or xref and the place that first read them. */ + const insertLists = new WeakMap< + object, + { inserts: readonly Insert[]; by: Block | Referenced; place: number } + >(); + /** Reads the inserts a block holds, once, and pays for a list read for another block or place. */ const fill = (held: Held): void => { if (held.filled) return; held.filled = true; const list = listOf(held); + const place = placeOf(held.inside); let found = insertLists.get(list); if (!found) { const inserts = filled(list).filter((item): item is Insert => item.kind === "insert"); - insertLists.set(list, (found = { inserts, by: held.held })); + insertLists.set(list, (found = { inserts, by: held.held, place })); } const { inserts } = found; held.inserts = inserts.length; - if (found.by !== held.held && inserts.length > 0) { + if ((found.by !== held.held || found.place !== place) && inserts.length > 0) { if (!spend(1 + Math.floor(inserts.length / 8))) return; } const children: Child[] = []; diff --git a/src/index.ts b/src/index.ts index 4251296..12eafcf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,10 +3,13 @@ export { attributeHandle, attributesEndHandle, blockHandle, + drawnXrefs, findBlock, findXref, placeAttribute, type PlacedAttribute, + type XrefDrawing, + type XrefDrawings, } from "./blocks.ts"; export { ARROWHEADS, @@ -189,6 +192,7 @@ export type { WidthFactor, XrefPath, } from "./rules.ts"; +export { XREF_DEPTH } from "./rules.ts"; export { BUILT_IN_STANDARD, defineStandard, type BuiltInStandard } from "./standard/define.ts"; export type { Box, diff --git a/src/inspect.ts b/src/inspect.ts index f1688ae..5db48c3 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -9,6 +9,7 @@ import { type LayerRef, type Matrix, type Referenced, + type XrefDrawings, } from "./blocks.ts"; import { callOf, type CallSite } from "./callsite.ts"; import { dimensionPicture } from "./dimensions.ts"; @@ -72,8 +73,11 @@ export interface TextWarning extends Partial { export interface InspectOptions { /** Counts the layers whose `plot` is false too, as `toSVG` draws them with the same option. */ readonly drawNoPlot?: boolean; - /** The drawing each xref stands for, by the xref's name, as `toSVG` takes them. */ - readonly xrefs?: Readonly>; + /** + * The drawing each xref stands for, by the xref's name, as `toSVG` takes them. The texts of the + * drawings given for the drawing's own xrefs are checked, and not those of their attachments. + */ + readonly xrefs?: XrefDrawings; } /** How far a text may reach into another, or past an outline, as a share of its height. */ @@ -675,7 +679,8 @@ function looked( } return out; }; - // An xref's model space, read once for each drawing given, and walked without xrefs of its own. + // An xref's model space, read once for each drawing given, and walked without xrefs of its own: + // the checks read the drawings given for the drawing's own xrefs, and none they attach. const done = new Map(); const outXrefs = new Map(); for (const [key, xref] of xrefs) { @@ -685,6 +690,7 @@ function looked( name: xref.name, drawing: { ...xref.drawing, entities }, blocks: xref.blocks, + xrefs: new Map(), }; const inner = settle(xref.blocks, of, () => false); const space = read(xref.drawing.entities, of); diff --git a/src/lint.ts b/src/lint.ts index 4dc9733..c1920e8 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -5,6 +5,8 @@ import { blockHandles, lookupCost, placeAttribute, + referencedTree, + type XrefDrawings, } from "./blocks.ts"; import { arrowheadInfo, @@ -145,6 +147,8 @@ import { viewportProblem, XREF_ATTRIBUTES, XREF_REFUSED_FIELDS, + XREFS_GIVEN, + xrefChainProblem, XREF_UNPLACED, xrefFieldProblem, xrefPathProblem, @@ -282,7 +286,13 @@ export interface Diagnostic { * What `lint` checks a drawing against: its DXF version, and the standard it is drawn to, with * the drawing's discipline. */ -export type LintOptions = +export type LintOptions = { + /** + * The drawings the xrefs stand for, as `toSVG` takes them. `lint` then says why any drawing + * given there is not drawn. It does not check those drawings: lint each on its own. + */ + readonly xrefs?: XrefDrawings; +} & ( | { /** The DXF version to check against. Defaults to the drawing's own. */ readonly version?: DxfVersion; @@ -302,7 +312,8 @@ export type LintOptions = * fields by discipline. */ readonly discipline?: string; - }; + } +); /** * The most work the checks do again for what a drawing repeats, beside `REPEATS` for each @@ -1854,9 +1865,52 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const given: unknown = options?.standard; if (given !== undefined) lintStandard(drawing, given, options?.discipline, version, out); + const referenced: unknown = options?.xrefs; + if (referenced !== undefined) lintReferenced(drawing, referenced, out); return out; } +/** The blocks `lintReferenced` reads of a drawing given: none. */ +const NO_BLOCKS: ReadonlyMap = new Map(); + +/** + * Why a drawing given in `xrefs` is not drawn, as `referencedTree` finds it: a warning of the + * xref of the drawing it is under, or an error for a value that is no drawing. + */ +function lintReferenced(drawing: Drawing, xrefs: unknown, out: Diagnostic[]): void { + if (typeof xrefs !== "object" || xrefs === null || Array.isArray(xrefs)) { + out.push({ rule: "xref", severity: "error", message: XREFS_GIVEN }); + return; + } + const { problems, unreported, unreportedShapes } = referencedTree( + drawing, + xrefs, + () => NO_BLOCKS, + ); + for (const { kind, chain } of problems) { + out.push({ + rule: "xref", + severity: kind === "shape" ? "error" : "warning", + message: xrefChainProblem(kind, chain), + ...(chain[0] === undefined ? {} : { xref: chain[0] }), + }); + } + if (unreportedShapes > 0) { + out.push({ + rule: "xref", + severity: "error", + message: `${unreportedShapes} more values given in xrefs are neither a Drawing nor { drawing, xrefs }, so nothing is drawn for them`, + }); + } + if (unreported > unreportedShapes) { + out.push({ + rule: "xref", + severity: "warning", + message: `${unreported - unreportedShapes} more drawings given in xrefs are not drawn, for the reasons above`, + }); + } +} + /** * An error that refuses a drawing because of what `lint` found in it. `toDXF` * throws it when a drawing has lint errors for the version being written, `fromJSON` diff --git a/src/pdf.ts b/src/pdf.ts index 3ec1a4a..3a58c80 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -1,6 +1,7 @@ // A drawing's layouts as a PDF: a page for each sheet, made from the picture `toSVG` draws of // it. `toSVG` holds every rule of what a sheet plots, so this file decides nothing about the // drawing: it turns the elements of that picture into the operators of a page. +import type { XrefDrawings } from "./blocks.ts"; import type { Drawing } from "./drawing.ts"; import { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; import { FONTS, fontInfo, type Font } from "./fonts.ts"; @@ -14,10 +15,11 @@ export interface PdfOptions { /** The layouts to plot, in this order. Defaults to every layout, in the drawing's order. */ readonly layouts?: readonly string[]; /** - * The drawing each xref stands for, by the xref's name, as `toSVG` takes them. An xref with - * no drawing given plots nothing. + * The drawing each xref stands for, by the xref's name, as `toSVG` takes them, with the + * drawings its attachments stand for when given as `{ drawing, xrefs }`. An xref with no + * drawing given plots nothing. */ - readonly xrefs?: Readonly>; + readonly xrefs?: XrefDrawings; /** * Compresses each page's content: a function that gives the zlib form of its bytes, such as * Node's `zlib.deflateSync`. Without it the content is written as it is. @@ -46,8 +48,8 @@ export interface PdfSheet { readonly drawing: Drawing; /** The name of the layout of `drawing` that is the sheet. */ readonly layout: string; - /** The drawing each xref of `drawing` stands for, by name. */ - readonly xrefs?: Readonly>; + /** The drawing each xref of `drawing` stands for, by name, as `toSVG` takes them. */ + readonly xrefs?: XrefDrawings; } /** diff --git a/src/rules.ts b/src/rules.ts index 8fa285c..7a6412f 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -3,6 +3,7 @@ // runtime check, for values the compiler can't see. The messages are shared. // // That app discards the whole drawing over most names that break the name rules. +import type { XrefProblem } from "./blocks.ts"; import type { DxfVersion, Point, Units } from "./drawing.ts"; import type { PaperUnit } from "./paper.ts"; import { paperInfo, PLOT_STYLE_TABLES, type Paper, type PlotStyleTable } from "./papers.ts"; @@ -1363,6 +1364,48 @@ export function xrefFieldProblem(field: (typeof XREF_REFUSED_FIELDS)[number]): s export const XREF_ATTRIBUTES = "An insert of an xref cannot set attributes. An insert gives a value to an attribute its block defines, and an xref defines none in this drawing"; +/** + * The most drawings a chain of references is drawn through in a picture: the drawing given for + * an xref, the drawing given for one of its attachments, and so on down. + */ +export const XREF_DEPTH = 16; + +/** The most names the drawings given for xrefs are looked through for, in one picture. */ +export const XREF_LOOKS = 4096; + +/** What is wrong with `xrefs` given to `lint` that is no object. */ +export const XREFS_GIVEN = + "xrefs must be an object that gives, for an xref's name, a Drawing or { drawing, xrefs }"; + +/** The names of a chain of xrefs, each cut to the 255 characters a block's name may have. */ +function chainOf(chain: readonly string[]): string { + return chain + .map((name) => JSON.stringify(name.length > 255 ? `${name.slice(0, 255)}…` : name)) + .join(" > "); +} + +/** + * Why the drawing given in `xrefs` for the last xref of a chain is not drawn, the chain running + * from an xref of the drawing down through the attachments of the drawings given. + */ +export function xrefChainProblem(kind: XrefProblem["kind"], chain: readonly string[]): string { + const at = `Xref ${chainOf(chain)}`; + const last = chainOf(chain.slice(-1)); + const above = chainOf(chain.slice(-2, -1)); + switch (kind) { + case "overlay": + return `${at}: ${last} is an overlay of the drawing given for ${above}, and the leading CAD app draws no overlay of a referenced drawing, so the drawing given for it is not drawn`; + case "cycle": + return `${at}: a circular reference. The drawing given for ${last} is drawn above it on this chain already, and the leading CAD app breaks the circle there, so it is not drawn again`; + case "deep": + return `${at}: a chain of references is drawn ${XREF_DEPTH} drawings down and no further, so the drawing given for ${last} is not drawn`; + case "many": + return `The drawings given in xrefs name more than ${XREF_LOOKS} xrefs inside referenced drawings, past which tsdraft draws none of them: only the drawings given for this drawing's own xrefs are drawn`; + case "shape": + return `${at}: the value given for ${last} is neither a Drawing nor { drawing, xrefs }, so nothing is drawn for it`; + } +} + /** The warning for an xref that no insert places. */ export const XREF_UNPLACED = "No insert places this xref. The leading CAD app purges an xref that nothing references when it opens the drawing"; diff --git a/src/shape.ts b/src/shape.ts index fd099a5..7d8e3be 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -515,7 +515,7 @@ function shapes(all: boolean, typed = all): Shapes { } }; - const xrefFields = fields({ name: string, path: string }, {}); + const xrefFields = fields({ name: string, path: string }, { attach: boolean }); /** * An xref, which is told why it cannot have a field of a block. `lint` has a rule for each of @@ -533,7 +533,7 @@ function shapes(all: boolean, typed = all): Shapes { } : fields( { name: ruled(string), path: ruled(string) }, - { entities: LEFT, base: LEFT, attributes: LEFT }, + { attach: boolean, entities: LEFT, base: LEFT, attributes: LEFT }, ); const layer = record( diff --git a/src/svg.ts b/src/svg.ts index aec8787..c4cd706 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -6,6 +6,7 @@ import { type LayerRef, type Matrix, type Referenced, + type XrefDrawings, } from "./blocks.ts"; import { dimensionPicture, type Dimension } from "./dimensions.ts"; import { @@ -203,9 +204,11 @@ export interface SvgOptions { readonly drawNoPlot?: boolean; /** * The drawing each xref stands for, by the xref's name. An insert of an xref draws the model - * space of the drawing given here, and nothing when none is given. + * space of the drawing given here, and nothing when none is given. Given as + * `{ drawing, xrefs }`, a drawing draws its attachments too, from the drawings its own `xrefs` + * gives, and so on down. */ - readonly xrefs?: Readonly>; + readonly xrefs?: XrefDrawings; /** * The name of a layout to draw in place of model space: the sheet as it plots. `margin` then * defaults to 0, and `strokeWidth` is not used, because a sheet's lines are as wide as their @@ -272,7 +275,12 @@ interface Sides { * draws a loaded xref: an entity on layer `0` there draws as the insert's layer does, and any other * as its own layer of the referenced drawing does, in that layer's color, linetype, lineweight * and state, with `data-layer` naming it as that app does, `XREF|LAYER`. Dashes are scaled by - * this drawing's linetype scale. The group is empty for an xref with no drawing given. + * this drawing's linetype scale. The group is empty for an xref with no drawing given. A drawing + * given as `{ drawing, xrefs }` draws each of its attachments the same way, inside the group, + * with a layer of the attached drawing named by the attachment's name, and none of its + * overlays, as that app loads no overlay of a referenced drawing. A circular reference is + * broken where it would draw a drawing the chain above already draws, as that app breaks one, + * and a chain is followed 16 drawings down; `lint` with the same `xrefs` reports both. * * With `options.layout`, the picture is that layout as the leading CAD app plots it, in paper * units: a white sheet the size of its paper, each viewport as a group with its index in diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 3cbffa8..3ecef53 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2068,3 +2068,119 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint } } }); + +test("a chain of references ends however the drawings given share, circle or nest", () => { + const random = seeded(23); + const pick = (items: readonly T[]): T => items[Math.floor(random() * items.length)]!; + /** A drawing that attaches, or now and then overlays, each name, placed once each. */ + const link = (names: readonly string[], own: readonly Entity[]): Drawing => ({ + format: 0, + units: "ft", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [ + ...own, + ...names.map((name, i): Entity => ({ kind: "insert", layer: "0", block: name, at: [i, 0] })), + ], + xrefs: names.map((name) => ({ name, path: `${name}.dwg`, attach: random() < 0.9 })), + }); + for (let n = 0; n < 12; n++) { + const names = Array.from({ length: pick([1, 2, 8, 64]) }, (_, i) => `X${i}`); + const depth = pick([3, 17, 40, 2000]); + const own = random() < 0.3 ? Array.from({ length: 20_000 }, () => line) : [line, text("A")]; + // Each level gives one value for every name, shared, which a walk of every path would follow + // names ** depth times. + let below: unknown = link([], own); + const levels: Record[] = []; + for (let i = 0; i < depth; i++) { + const given: Record = Object.fromEntries(names.map((name) => [name, below])); + levels.push(given); + below = { drawing: link(names, own), xrefs: given }; + } + // The values circle back to the top. + if (random() < 0.5) levels[0]![names[0]!] = below; + // A value that is no drawing, or whose xrefs are none. + if (random() < 0.4) { + levels[depth - 1]![names[0]!] = pick([ + 5, + null, + [], + { drawing: 5 }, + { drawing: link([], own), xrefs: "X" }, + ]); + } + const host = link(names, []); + const options = { xrefs: Object.fromEntries(names.map((name) => [name, below])) as never }; + const fns: [string, () => unknown][] = [ + ["lint", () => lintWithin(host, options, 20_000)], + ["inspectText", () => inspectWithin(host, options, 200_000)], + [ + "extents", + () => + boxer( + [], + [], + undefined, + undefined, + referencedByKey(host, options.xrefs), + [], + [], + 20_000, + )(host.entities), + ], + ["toSVG", () => svgWithin(host, options, 20_000)], + ]; + for (const [name, fn] of fns) { + const result = settled(2000, fn); + assert.ok( + !(result instanceof Error) || result instanceof RangeError, + `case ${n}, ${name}: ${String(result)}`, + ); + if (name === "lint") + assert.ok(Array.isArray(result), `case ${n}: lint threw ${String(result)}`); + } + } + // Long names that differ only at their ends, given and declared, which no map of lint's + // reading of what is given is keyed by. + const tail = (i: number) => `${"L".repeat(20_000)}${i}`; + const longs = Array.from({ length: 2000 }, (_, i) => tail(i)); + const holder = link(longs, [line]); + const given = Object.fromEntries(longs.map((name) => [name, holder])); + const deepXrefs = { X: { drawing: holder, xrefs: given } } as never; + assert.ok(Array.isArray(within(1000, () => lint(link(["X"], []), { xrefs: deepXrefs })))); + // One model at many places, each giving its attachment, whose block places it 1,000 times: the + // block's inserts read again at each place are paid for. + const many = Array.from({ length: 1000 }, (_, i): Entity => ({ + kind: "insert", + layer: "0", + block: "IN", + at: [i, 0], + })); + const placing: Drawing = { + ...link(["IN"], []), + entities: [{ kind: "insert", layer: "0", block: "HOLD", at: [0, 0] }], + blocks: [{ name: "HOLD", entities: many }], + }; + const places = Array.from({ length: 48 }, (_, i) => `P${i}`); + const placed = Object.fromEntries( + places.map((name) => [name, { drawing: placing, xrefs: { IN: link([], [line]) } }]), + ) as never; + const paid = settled(1000, () => svgWithin(link(places, []), { xrefs: placed }, 5000)); + assert.ok(paid instanceof RangeError && /extents/.test(paid.message), String(paid)); + // Copies of one drawing with many xrefs, one list shared, under many names: the list is + // read once, and not at all where nothing is given inside the drawing. + const declared = link( + Array.from({ length: 4096 }, (_, i) => `D${i}`), + [line], + ); + const hosts = Array.from({ length: 256 }, (_, i) => `H${i}`); + const host = link(hosts, []); + for (const inner of [{}, { D0: link([], [line]) }]) { + const xrefs = Object.fromEntries( + hosts.map((name) => [name, { drawing: { ...declared }, xrefs: inner }]), + ) as never; + assert.ok(Array.isArray(within(1000, () => lint(host, { xrefs })))); + const drawn = settled(1000, () => svgWithin(host, { xrefs }, 20_000)); + assert.ok(typeof drawn === "string" || drawn instanceof RangeError, String(drawn)); + } +}); diff --git a/test/shape.test.ts b/test/shape.test.ts index 5c3d10e..ab80919 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -235,7 +235,7 @@ const full: Required & { ], }, ], - xrefs: [{ name: "BASE", path: "base.dwg" }], + xrefs: [{ name: "BASE", path: "base.dwg", attach: true }], entities: [...Object.values(kinds), { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }], layouts: [ { diff --git a/test/xrefs.test.ts b/test/xrefs.test.ts index 5d0aac6..207dd0d 100644 --- a/test/xrefs.test.ts +++ b/test/xrefs.test.ts @@ -3,10 +3,12 @@ import { test } from "node:test"; import { blockHandle, createDrawing, + drawnXrefs, DrawingError, findXref, fromJSON, idHandle, + inspectText, lint, toDXF, toJSON, @@ -198,6 +200,9 @@ test("R2018 DXF holds an xref as a block with a path, and its inserts", () => { const [block] = of("BLOCK"); // 12 is an xref that is an overlay, and a path is escaped for one pass of the leading CAD app's reader. assert.ok(block?.includes("70=12") && block.includes(`330=${record}`)); + // 4 alone is an attachment. + const attached = createDrawing().xref("A", "a.dwg", { attach: true }).insert("A", [0, 0]); + assert.match(toDXF(attached.build()), /\r\n2\r\nA\r\n70\r\n4\r\n/); assert.equal(block?.at(-1), "1=..\\base\\base.dwg"); const inserts = of("INSERT"); assert.equal(inserts.length, 2); @@ -216,13 +221,15 @@ test("a drawing with xrefs goes to JSON and back, and the parser says why an xre assert.deepEqual(findXref(drawing, "base"), { name: "BASE", path: "..\\base\\base.dwg" }); const broken = JSON.parse(toJSON(drawing)) as { xrefs: Record[] }; broken.xrefs[0]!.entities = []; - broken.xrefs[0]!.attach = true; + broken.xrefs[0]!.overlay = true; + broken.xrefs[0]!.attach = "yes"; assert.throws( () => fromJSON(broken), (thrown: unknown) => thrown instanceof DrawingError && /xrefs\[0\]: An xref cannot have entities of its own/.test(thrown.message) && - /xrefs\[0\]: unknown field "attach"/.test(thrown.message), + /xrefs\[0\]: unknown field "overlay"/.test(thrown.message) && + /xrefs\[0\]\.attach must be true or false/.test(thrown.message), ); }); @@ -283,3 +290,152 @@ test("SVG draws the drawing given for an xref where each insert puts it, as the const loop = createDrawing().xref("BASE", "host.dwg").insert("BASE", [0, 0]).line([0, 0], [1, 1]); assert.equal(toSVG(drawing, { xrefs: { BASE: loop.build() } }).match(/ { + const detail = createDrawing({ units: "ft" }); + detail.layer("D", { color: 3 }, () => detail.circle([0, 0], 1)); + const base = createDrawing({ units: "ft" }).xref("DETAIL", "detail.dwg", { attach: true }); + base.layer("B", { color: 2 }, () => base.line([0, 0], [5, 0]).insert("DETAIL", [5, 0])); + const survey = createDrawing({ units: "ft" }); + survey.layer("S", { color: 4 }, () => survey.line([0, 0], [0, 5])); + const model = createDrawing({ units: "ft" }); + model.xref("BASE", "base.dwg", { attach: true }).xref("SURVEY", "survey.dwg"); + model.layer("M", { color: 1 }, () => + model.rect([0, 0], 2, 2).insert("BASE", [10, 0]).insert("SURVEY", [0, 10]), + ); + const sheet = createDrawing({ units: "ft" }).xref("MODEL", "model.dwg"); + sheet.insert("MODEL", [100, 0]); + const drawn = sheet.build(); + const xrefs = { + MODEL: { + drawing: model.build(), + xrefs: { + BASE: { drawing: base.build(), xrefs: { DETAIL: detail.build() } }, + SURVEY: survey.build(), + }, + }, + }; + const svg = toSVG(drawn, { xrefs }); + // A layer of an attached drawing is named by the attachment's name, wherever it is attached. + assert.match(svg, /]*data-layer="BASE\|B"\/>/); + assert.match(svg, /]*data-layer="DETAIL\|D"\/>/); + assert.match(svg, /data-layer="MODEL\|M"/); + // The model's overlay is not drawn, though a drawing is given for it, and lint says why. + assert.doesNotMatch(svg, /SURVEY/); + assert.deepEqual( + lint(drawn, { xrefs }).map((d) => `${d.severity} ${d.rule} ${d.xref}: ${d.message}`), + [ + 'warning xref MODEL: Xref "MODEL" > "SURVEY": "SURVEY" is an overlay of the drawing given for "MODEL", and the leading CAD app draws no overlay of a referenced drawing, so the drawing given for it is not drawn', + ], + ); + // The model given alone draws none of its own xrefs. + assert.doesNotMatch(toSVG(drawn, { xrefs: { MODEL: xrefs.MODEL.drawing } }), /BASE|DETAIL/); + + // Two drawings that attach each other: the circle is broken where the model would be drawn + // inside itself, and the base inside the model is drawn once. + const back = createDrawing({ units: "ft" }).xref("MODEL", "model.dwg", { attach: true }); + back.layer("B", {}, () => back.line([0, 0], [1, 0]).insert("MODEL", [0, 0])); + const ring: { drawing: Drawing; xrefs: Record } = { + drawing: xrefs.MODEL.drawing, + xrefs: {}, + }; + ring.xrefs["BASE"] = { drawing: back.build(), xrefs: { MODEL: ring } }; + const circled = toSVG(drawn, { xrefs: { MODEL: ring as never } }); + assert.equal(circled.match(/data-layer="MODEL\|M"/g)?.length, 1); + assert.equal(circled.match(/data-layer="BASE\|B"/g)?.length, 1); + assert.match( + lint(drawn, { xrefs: { MODEL: ring as never } })[0]?.message ?? "", + /^Xref "MODEL" > "BASE" > "MODEL": a circular reference/, + ); + // The sheet given for its own xref is a circle too. + assert.doesNotMatch(toSVG(drawn, { xrefs: { MODEL: drawn } }), /data-layer="MODEL\|/); + + // A chain is followed 16 drawings down, and no further. + let deepest: { drawing: Drawing } | Drawing = createDrawing().line([0, 0], [1, 0]).build(); + for (let i = 0; i < 20; i++) { + const link = createDrawing().xref("NEXT", "next.dwg", { attach: true }); + link.line([0, 0], [1, 0]).insert("NEXT", [1, 0]); + deepest = { drawing: link.build(), xrefs: { NEXT: deepest } } as never; + } + const top = createDrawing().xref("NEXT", "next.dwg").insert("NEXT", [0, 0]).build(); + assert.equal(toSVG(top, { xrefs: { NEXT: deepest as never } }).match(/ `N${i}`); + for (const name of names) wide.xref(name, `${name}.dwg`, { attach: true }).insert(name, [0, 0]); + const many = { + MODEL: { + drawing: wide.build(), + xrefs: Object.fromEntries(names.map((name) => [name, detail.build()])), + }, + }; + assert.doesNotMatch(toSVG(drawn, { xrefs: many }), /\|D"/); + assert.deepEqual( + lint(drawn, { xrefs: many }).map((d) => [d.severity, d.xref, d.message.slice(0, 50)]), + [["warning", undefined, "The drawings given in xrefs name more than 4096 xr"]], + ); + + // What a picture draws of what is given, which draws the same when given again. + const kept = drawnXrefs(drawn, xrefs); + assert.deepEqual(Object.keys(kept), ["MODEL"]); + assert.deepEqual(Object.keys((kept["MODEL"] as { xrefs: object }).xrefs), ["BASE"]); + assert.equal(toSVG(drawn, { xrefs: kept }), svg); + // A value that is no drawing is an error, and draws nothing. + const odd = { MODEL: { drawing: xrefs.MODEL.drawing, xrefs: { BASE: { blocks: [{}] } } } }; + const [shape] = lint(drawn, { xrefs: odd as never }); + assert.deepEqual([shape?.severity, shape?.xref], ["error", "MODEL"]); + assert.match( + shape?.message ?? "", + /^Xref "MODEL" > "BASE": the value given for "BASE" is neither/, + ); + assert.doesNotMatch(toSVG(drawn, { xrefs: odd as never }), /BASE\|/); +}); + +test("inspectText walks no insert of an attachment given no drawing", () => { + // A model whose blocks place an attachment 4^11 times, given alone: nothing draws there, and + // the two labels of the sheet that overlap are still found. + const model = createDrawing({ units: "ft" }).xref("DEEP", "deep.dwg", { attach: true }); + model.block("B0", {}, () => model.insert("DEEP", [0, 0])); + for (let i = 1; i <= 11; i++) { + model.block(`B${i}`, {}, () => { + for (let j = 0; j < 4; j++) model.insert(`B${i - 1}`, [j, 0]); + }); + } + model.insert("B11", [0, 0]); + const sheet = createDrawing({ units: "ft" }).xref("MODEL", "model.dwg").insert("MODEL", [0, 0]); + sheet.text([0, 0], "LABEL ONE", { height: 1 }).text([0.2, 0], "LABEL TWO", { height: 1 }); + const warnings = inspectText(sheet.build(), { xrefs: { MODEL: model.build() } }); + assert.deepEqual( + warnings.map((w) => w.rule), + ["text-overlaps-text"], + ); +}); + +test("one drawing given at two places draws what each place gives for its attachments", () => { + const model = createDrawing({ units: "ft" }).xref("DETAIL", "detail.dwg", { attach: true }); + model.block("HOLDER", {}, () => model.insert("DETAIL", [0, 0])); + model.insert("HOLDER", [0, 0]); + const at = (x: number) => { + const d = createDrawing({ units: "ft" }); + d.layer("D", { color: 3 }, () => d.line([x, 0], [x + 1, 0])); + return d.build(); + }; + const sheet = createDrawing({ units: "ft" }).xref("A", "a.dwg").xref("B", "b.dwg"); + sheet.insert("A", [0, 0]).insert("B", [0, 0]); + const shared = model.build(); + const xrefs = { + A: { drawing: shared, xrefs: { DETAIL: at(0) } }, + B: { drawing: shared, xrefs: { DETAIL: at(1000) } }, + }; + const svg = toSVG(sheet.build(), { xrefs, margin: 0 }); + assert.match(svg, /viewBox="0 0 1001 0"/); + assert.match(svg, / Date: Thu, 19 Nov 2026 00:41:40 -0500 Subject: [PATCH 02/35] Polyline arcs and widths: bulges, rounded corners, revision clouds, donuts and wide sides Polyline arcs and widths, in R2018 drawings. A `Polyline` holds `bulges`, one for each side, where 0 is straight and 1 is a half circle. It holds `width`, one width for every side, or `widths`, the width at each side's start and end. `d.polyline(points, closed, options)` takes all three, and `radius`, which rounds each corner with an arc tangent to both sides, as a bar's hook is bent. `d.rect` takes `radius` too. - `d.cloud(outline, { arc })` draws a revision cloud along an outline: one closed polyline of arcs that each turn 110 degrees and bulge out of it. A cloud drawn around a note crosses none of it. - `d.donut(center, outside, { inside })` draws a filled ring, or a dot. - `bulgeThrough(from, through, to)` gives the bulge of the arc through a point, and `polylineBox` gives the box a polyline covers. `toDXF` writes them. `readDXF` reads them from a lightweight polyline and from a 2D one. `lint` refuses any of these: - a list of bulges or widths without one for each side; - a bulge or a width that is not a number; - a negative width; - `width` and `widths` together; - either in an R12 drawing. `toSVG`, `toPDF` and `tsdraft render` draw them as the leading CAD app plots them: - a side of width 0 is drawn with its pen; - a wide side is filled with no pen; - two straight sides meet in a miter up to a turn of 151 degrees; - a straight side meets an arc along the line from the arc's center; - two arcs each end square; - each dash of a wide side is filled. `checkIntent` leaves a footprint or a property line with an arc unchecked, and says so. The example sheet has a revision cloud around its driveway, and its north arrow's head is one polyline that widens from its tip. `docs/polylines.md` describes them. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 21 + GUIDE.md | 18 +- README.md | 21 +- cli/test/warm.test.ts | 4 +- docs/assets/site-plan-dark.svg | 7 +- docs/assets/site-plan-light.svg | 7 +- docs/plotting.md | 2 + docs/polylines.md | 157 ++++++++ docs/reading.md | 8 +- docs/rules.md | 5 + docs/standard.md | 2 +- examples/README.md | 15 +- examples/site-plan.ts | 59 ++- scripts/readme-drawing.ts | 1 + src/drawing.ts | 296 +++++++++++++- src/dxf-r2018.ts | 17 +- src/extents.ts | 48 ++- src/index.ts | 7 + src/intent.ts | 10 + src/lint.ts | 39 +- src/polylines.ts | 664 ++++++++++++++++++++++++++++++++ src/read/check.ts | 3 + src/read/dxf.ts | 33 +- src/read/entities.ts | 65 +++- src/read/model.ts | 14 +- src/rules.ts | 79 ++++ src/shape.ts | 9 +- src/svg.ts | 297 +++++++++++++- test/bounded.test.ts | 92 ++++- test/polylines.test.ts | 653 +++++++++++++++++++++++++++++++ test/read-agreement.ts | 18 + test/read-fuzz.ts | 4 + test/read.test.ts | 8 +- test/rules.test.ts | 29 ++ test/shape.test.ts | 46 ++- test/standard-lint.test.ts | 7 +- 36 files changed, 2660 insertions(+), 105 deletions(-) create mode 100644 docs/polylines.md create mode 100644 src/polylines.ts create mode 100644 test/polylines.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b2cad18..34a89ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,27 @@ `tsdraft dev` take the same in the export `xrefs`, lint each drawing given that they draw, at any depth, and `drawing.xrefs` gives each xref's `attach` and, for one shown, the `xrefs` of the drawing drawn for it. [docs/xrefs.md](docs/xrefs.md) describes them. +- Polyline arcs and widths, in R2018 drawings. A `Polyline` holds `bulges`, one for each side, + where 0 is straight and 1 a half circle, and `width`, one width for every side, or `widths`, + the width at each side's start and end. `d.polyline(points, closed, options)` takes all three, + and `radius`, which rounds each corner with an arc tangent to both sides, as a bar's hook is + bent; `d.rect` takes `radius` too. `d.cloud(outline, { arc })` draws a revision cloud along an + outline, one closed polyline of arcs that each turn 110 degrees and bulge out of it, so a cloud + drawn around a note crosses none of it; an outline with a notch narrower than an arc bulges is + refused. `d.donut(center, outside, { inside })` draws a filled + ring, or a dot. `bulgeThrough(from, through, to)` gives the bulge of the arc through a point, + and `polylineBox` the box a polyline covers. `toDXF` writes them, `readDXF` reads them from a + lightweight polyline and from a 2D one, and `lint` refuses a list of bulges or widths that does + not have one for each side, a bulge or a width that is not a number, a negative width, `width` + and `widths` together, and either in an R12 drawing. `toSVG`, `toPDF` and `tsdraft render` draw + a side of width 0 with its pen and fill a wide one with no pen, as the leading CAD app plots + them: two straight sides meet in a miter up to a turn of 151 degrees, a straight side meets an + arc along the line from the arc's center, two arcs each end square, and each dash of a wide + side is filled. `checkIntent` leaves a footprint or a property line with an arc unchecked, and + says so. [docs/polylines.md](docs/polylines.md) describes them. +- The example sheet has a revision cloud around the driveway, with a delta, on the layer + `C-ANNO-REVS` of its standard, and its north arrow's head is one polyline that widens from its + tip, which CAD programs fill. - The README lists a viewport's own frozen layers and its twist with what tsdraft draws, and no longer with what it does not have yet. - The README and the package's description name what tsdraft does now: plotting to PDF, diff --git a/GUIDE.md b/GUIDE.md index bd7fc74..9799a5a 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -59,7 +59,10 @@ export default d.build(); Coordinates are in drawing units with Y pointing up. Angles are in degrees, counterclockwise from +X. A layer's color is a number from 1 to 255 in the color index CAD programs share, and a lineweight is in millimetres. Entities drawn inside a `layer()` callback go on that layer. The -builder draws `line`, `polyline`, `rect`, `circle`, `arc`, `text` and dimensions. +builder draws `line`, `polyline`, `rect`, `circle`, `arc`, `text` and dimensions. A polyline +takes `bulges` to make a side an arc, `width` or `widths` to draw its sides wide, and `radius` +to round its corners; `cloud` draws a revision cloud around an outline, which crosses nothing +inside it, and `donut` a filled ring or dot. [docs/polylines.md](docs/polylines.md) has them. Give an entity an `id` when you will want to find it again: 1 to 64 letters, digits, `.`, `-` and `_`, each used once in a drawing. A diagnostic about the entity carries the id. @@ -276,18 +279,17 @@ the built-in standard and the rest. [`examples/site-plan.ts`](https://github.com/Surfside-Software/tsdraft/blob/main/examples/site-plan.ts) in the tsdraft repository is a whole sheet: a permit-style site plan at 1" = 10' with property -lines, setbacks, a building, dimensions, leaders and labels in model space, and on a landscape +lines, setbacks, a building, dimensions, leaders, labels and a revision cloud in model space, +and on a landscape ARCH D layout, 36 by 24 inches, its border, a title block whose fields are attributes, notes, a legend, the view's title and a graphic scale. Start a new drawing from it. It is not in the npm package. Copy it and -[`examples/lib/drafting.ts`](https://github.com/Surfside-Software/tsdraft/blob/main/examples/lib/drafting.ts), -keeping `drafting.ts` in a `lib` folder beside it. Change two import strings to `"tsdraft"`: -`"../src/index.ts"` in `site-plan.ts`, and `"../../src/index.ts"` in `lib/drafting.ts`. +change its import string `"../src/index.ts"` to `"tsdraft"`. Its parameters come first and every position is worked out from them. Its columns and line breaks are laid out with `measureText`. Its symbols are blocks. -It is drawn to a standard of its own, which extends `BUILT_IN_STANDARD` with the layer -`V-TREE`, as the section above shows, and a leader style. A text names a `role` of the standard, +It is drawn to a standard of its own, which extends `BUILT_IN_STANDARD` with the layers +`V-TREE` and `C-ANNO-REVS`, as the section above shows, and a leader style. A text names a `role` of the standard, which gives its text style and the height it plots at. The plan is a view at one of the standard's scales, `const plan = d.view("plan", { scale: "1in-10ft" })`, and what model space draws to be read in it names the view: `d.text(at, "LOT 27", { role: "label", view: plan })`, @@ -592,7 +594,7 @@ writeFileSync("plan.dxf", toDXF(drawing)); `measureText`. A text takes a text style with a font, and `align` and `valign` to justify it to its point, as the example sheet does. -- Ellipses, splines, and curved segments in a polyline. +- Ellipses and splines. - A color on a single entity. Color comes from the layer. - DWG files. tsdraft writes DXF. - An existing drawing as a background or a base to edit. `readDXF` reads a DXF's tables, blocks, diff --git a/README.md b/README.md index 8005105..ff7c8c2 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,18 @@ The path leads from the folder of the drawing's file. `toSVG` draws the referenc when it is given one, as `toSVG(drawing, { xrefs: { BASE: base } })`. [Xrefs](docs/xrefs.md) has the rest. +A polyline's sides can be arcs and can be drawn wide, and the builder makes a few shapes of +them, each one polyline in the file: + +```ts +d.polyline(hook, false, { radius: 1.5, width: 0.625 }); // a bar's hook with its bend +d.cloud(outline, { arc: 3.75 }); // a revision cloud that bulges out of its outline +d.donut([10, 10], 0.5); // a filled dot +``` + +`bulges` makes any side an arc, and `widths` gives each side a width at each end. +[Polylines](docs/polylines.md) has the rest. + A dimension measures between two points and writes what it measures. In the file it is a dimension, which a CAD program measures again when its points move, and a dimension style says how it is drawn: @@ -211,15 +223,15 @@ tsdraft is early, and its API still changes. Until 1.0 any release, a patch included, can break code written for the one before. [CHANGELOG.md](CHANGELOG.md) starts each breaking change with `Breaking:`. -It draws layers, lines, polylines, rectangles, circles, arcs and single-line text, with +It draws layers, lines, polylines with arcs and widths, rectangles, revision clouds, donuts, +circles, arcs and single-line text, with linetypes and lineweights, text styles and justification, blocks with attributes and inserts of them, references to DWG files as xrefs, linear and aligned dimensions in decimal units or feet and inches, leaders, layouts with a page setup and viewports, which can freeze their own layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have paragraph text, arcs or widths in a polyline, ellipses, splines or -points, hatches, solid fills or masks, images, tables, color or transparency set on one +It does not yet have paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit @@ -270,6 +282,7 @@ the drawing's version, and `toDXF(drawing, { version })` writes another one. | Format code | AC1032 | AC1009 | | Drawing units | Stored in `$INSUNITS`. | Not stored. Set them in CAD with `UNITS`. | | Polylines | `LWPOLYLINE` | `POLYLINE` with `VERTEX` records | +| Polyline arcs and widths | Yes | No | | Text | UTF-8 | ASCII, with `\U+XXXX` escapes for other characters | | Layer names | Up to 255 characters, except those in [the rules](docs/rules.md#errors) | Up to 31 letters, digits, `$`, `-` and `_` | | Linetypes, lineweights | Yes | No: only `Continuous`, and no lineweights | @@ -317,6 +330,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version characters it refuses. - [Blocks](docs/blocks.md) covers blocks, inserts and attributes: layers in a block, names, handles and what the preview draws. +- [Polylines](docs/polylines.md) covers arcs by their bulge, rounded corners, revision clouds, + widths and donuts, how a wide polyline plots, and what `lint` refuses of them. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. - [Xrefs](docs/xrefs.md) covers references to DWG files: the path, units, a diff --git a/cli/test/warm.test.ts b/cli/test/warm.test.ts index ad5ec00..a9ddc5a 100644 --- a/cli/test/warm.test.ts +++ b/cli/test/warm.test.ts @@ -140,8 +140,8 @@ test("a build after another reads the drawing's files alone, and answers as the assert.equal(cold!.ok, true); assert.equal(cold!.modules.ahead, 0); assert.ok(cold!.modules.read > 2, "the first build reads the library"); - // The sheet and its helpers: the library is neither read nor run again. - assert.equal(warm!.modules.read, 2); + // The sheet alone: the library is neither read nor run again. + assert.equal(warm!.modules.read, 1); assert.ok(warm!.modules.ahead > 0); assert.deepEqual(answer(warm!), answer(cold!)); }); diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index 696753e..f1316dd 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -152,6 +152,9 @@ EXISTING OAK TO REMAIN + + + 1 @@ -233,13 +236,13 @@ N - + N - + diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index f6b68c8..db02147 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -152,6 +152,9 @@ EXISTING OAK TO REMAIN + + + 1 @@ -233,13 +236,13 @@ N - + N - + diff --git a/docs/plotting.md b/docs/plotting.md index 9caeba3..39870c7 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -61,6 +61,8 @@ preview shows it: circle, as [Linetypes on a sheet](layouts.md#linetypes-on-a-sheet) says. - A line of lineweight 0 plots as the thinnest line the printer draws, as a viewport's border does. +- A wide side of a polyline is filled, at its width whatever its pen, with its joins and its + dashes as [How it plots](polylines.md#how-it-plots) says. - Each layer is a layer of the PDF too, by the name the picture gives it, `XREF|LAYER` for a layer of an xref, so a PDF viewer lists the layers and can hide one. - Each page has a bookmark and a page label with its layout's name. diff --git a/docs/polylines.md b/docs/polylines.md new file mode 100644 index 0000000..f410c05 --- /dev/null +++ b/docs/polylines.md @@ -0,0 +1,157 @@ +# Polylines + +A polyline is one entity of sides, from each point to the next and, when it is closed, from the +last back to the first. A side is straight or an arc, and may be drawn wide. In the file it is an +`LWPOLYLINE`, which a CAD user selects, moves and edits as one. + +Arcs and widths are R2018 only. The builder and `lint` refuse them in an R12 drawing. + +## Arcs + +A side is an arc by its bulge: the tangent of a quarter of the angle the arc turns through, 0 for +a straight side, 1 for a half circle, and greater than 0 when the arc turns counterclockwise, +which bulges it to the right of the way the side runs. `bulges` holds one for each side: + +```ts +// A straight side, then a half circle that bulges below its chord. +d.polyline( + [ + [0, 0], + [10, 0], + [20, 0], + ], + false, + { bulges: [0, 1] }, +); +``` + +`bulgeThrough(from, through, to)` gives the bulge of the arc from `from` to `to` that passes +through `through`: + +```ts +const bulge = bulgeThrough([0, 0], [5, 2], [10, 0]); +d.polyline( + [ + [0, 0], + [10, 0], + ], + false, + { bulges: [bulge] }, +); +``` + +`radius` rounds each corner with an arc of that radius, tangent to both sides, as a bar's hook is +bent. The polyline then holds the arcs' ends in place of its corners, and an open one keeps its +two ends. `rect` takes `radius` for a rectangle with rounded corners. A radius whose arcs need +more of a side than the side has is refused. + +```ts +// A bar's hook: a leg, the bend, and the tail, as one polyline as wide as the bar. +d.polyline( + [ + [0, 0], + [0, 12], + [4, 12], + ], + false, + { radius: 1.5, width: 0.625 }, +); +d.rect([0, 0], 24, 12, { radius: 2 }); +``` + +## Revision clouds + +`cloud(outline, { arc })` draws a revision cloud along a closed outline: the corners of a +rectangle, or an outline drawn around what changed. It is one closed polyline of arcs from point +to point along each side, as many on a side as its length over `arc`, rounded and at least one. +Each arc turns through 110 degrees, as the arcs of the leading CAD app's own clouds do, and +bulges out of the outline. An arc of less than half a circle stays beside its own stretch of the +side, so the cloud never enters the outline at a corner: drawn around a note, the dimensions and +a window it marks, it crosses none of them. `arc` is a length in drawing units; in model space +under a standard, `view.paper(3 / 8)` gives arcs about 3/8 in long on the paper. + +```ts +d.cloud( + [ + [40, -15], + [85, -15], + [85, 28], + [40, 28], + ], + { arc: plan.paper(3 / 8) }, +); +``` + +No arc may cross the outline. In a notch narrower than an arc bulges, an arc on one wall would +reach the far one, and the cloud is refused: give a shorter arc. In a notch a little wider, the +arcs on its two walls may overlap each other while neither crosses the outline. A cloud has at most 10,000 +arcs. Its outline needs three points or more and an area. + +## Widths + +`width` draws every side that wide, in drawing units, and `widths` gives each side its own width +at its start and at its end: one pair for each side. A polyline has one or the other. + +```ts +// A duct heavier than any pen. +d.polyline( + [ + [0, 0], + [30, 0], + [30, 20], + ], + false, + { width: 2 }, +); +// An arrowhead: one side that widens from nothing at its tip. +d.polyline( + [ + [0, 0], + [0, -1], + ], + false, + { widths: [[0, 0.3]] }, +); +``` + +`donut(center, outside, { inside })` draws a filled ring `outside` across with a hole `inside` +across: a closed polyline of two half circles, as wide as the ring. With no `inside` it is a +filled dot, such as a bar cut in a section. + +## How it plots + +The leading CAD app fills a side that has a width at either end, at that width whatever its pen, +and draws a side of width 0 with its pen. `toSVG`, `toPDF` and `tsdraft render` draw them the same +way: + +- A wide side ends square. The width changes along a side from its start width to its end width, + along an arc as well. +- Where two wide sides meet, two straight ones meet in a miter, with the edges of each carried to + where they cross, unless the turn is more than 151.04 degrees, the miter's corner then lying + more than twice the width from the point; both then end square. A straight side and an arc meet + along the line from the arc's center through the point, unless the tangent of the turn is more + than 4. Two arcs each end square, on the line from their center. +- A dashed wide side is cut into its dashes as a line is, each dash filled and square at both + ends, with no joins. The dashes of a wide arc are fitted along its outer edge, at the larger of + its widths. +- An insert or a viewport scales a width with the rest of what it draws. + +`polylineBox(e)` is the box a polyline covers: its points, the arcs of its sides and its wide sides +with their joins. The extents and the view a file opens on take it. + +## Checks + +`lint` refuses a list of bulges or widths that is not a list, or holds what is not a number or a +pair of numbers, as `format`, as it refuses any field of the wrong type. It refuses, as +`geometry`: + +- A list of bulges or widths that does not have one for each side: a closed polyline has a side + for each point, and an open one a side fewer. +- A bulge or a width that is not a finite number, or is 1e100 or more. +- A width less than 0. The leading CAD app reads a negative width of every side as 0, and keeps a + negative width of one side with no `AUDIT` error. +- A width and widths for each side together. +- Either in an R12 drawing. + +`checkIntent` takes only outlines of straight sides, and leaves a property line or a footprint +with an arc unchecked, with an `intent-unchecked` warning. diff --git a/docs/reading.md b/docs/reading.md index 50b9ab3..cb7c078 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -55,7 +55,7 @@ states and keeps each object's handle, and it keeps going past what it does not style with whether it is annotative, and a dimension style with the units it writes lengths in. Two entries of one name are both kept, in the order of the file. - `blocks`: each with its base point, its attribute definitions and its entities, below. What - else a block draws is counted under `other` by kind, such as `HATCH` or `LWPOLYLINE with arcs`, + else a block draws is counted under `other` by kind, such as `HATCH` or `LWPOLYLINE in 3D`, and so is what stands in another plane than the block's. The blocks keep `BLOCK_ITEMS`, 400,000 items in all, counted as below, and count what comes past that under `past the limit`. The pictures the leading CAD app makes for dimensions, the blocks named `*D` and a number, are @@ -91,8 +91,10 @@ The texts of a block's definition are kept, since a title block's labels belong A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers write: -- `line`, `circle` and `arc`, and `polyline` for a polyline of straight segments, open or - closed. A polyline with an arc or a width is counted under `other`. +- `line`, `circle` and `arc`, and `polyline` for a lightweight polyline or a 2D one, open or + closed, with `bulges`, one for each side, when a side is an arc, and `width`, one width for + every side, or `widths`, each side's width at its start and its end, when a side is wide, as + a `Polyline` holds them. A 2D polyline's vertex with no width of its own has the polyline's. - `text`: a text of one line, with its `value`. - `insert`: its block, by name and by the handle of its record in `blockHandle`, its point, scale and rotation, `tags`, and with `geometry` its `attributes`: each a text with its `tag` diff --git a/docs/rules.md b/docs/rules.md index dd71cf6..af4fe52 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -31,6 +31,11 @@ it would take `1e+100` for `1e+10` and report nothing. characters U+E800 to U+E8FF, which that app replaces. - Coordinates, sizes and text rotations are under 1e100 in size, because the leading CAD app reads only two exponent digits from DXF. +- A polyline has a bulge for each side and a pair of widths for each side when it has them: + a closed polyline has a side for each point, an open one a side fewer. A width is 0 or more, + since the leading CAD app reads a negative width of every side as 0 and keeps a negative width + of one side with no `AUDIT` error, and a polyline has one width for every side or one for each, + not both. [Polylines](polylines.md#checks) has the rest. - Arc angles are stored from 0 up to 360, so -90 becomes 270. An arc cannot come within 0.000001 degrees of a full turn, because its two angles would be written the same and the leading CAD app holds such an arc as having no length. Draw a diff --git a/docs/standard.md b/docs/standard.md index 097a23d..675c0ab 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -40,7 +40,7 @@ The child's entries are added to its parent's, an entry of the same name replace whole, and `null` removes one. Export the standard beside the drawing, so that [the command](#the-command) holds the drawing to it. [`examples/site-plan.ts`](../examples/site-plan.ts) is a whole sheet drawn this way, to a -standard that adds the layer `V-TREE` to the built-in one. +standard that adds the layers `V-TREE` and `C-ANNO-REVS` to the built-in one. ## `defineStandard` diff --git a/examples/README.md b/examples/README.md index 1fb95cd..d4f6940 100644 --- a/examples/README.md +++ b/examples/README.md @@ -37,7 +37,7 @@ so a CAD program opens them as plain geometry. - A landscape sheet, 3 wide to 2 tall, inside a border. At the left, a permit-style site plan at 1 inch to 10 feet: a lot with its bearings, setback lines, a building footprint with dimension strings, a driveway, a sidewalk, trees and the street, with a north arrow, the view title and a graphic scale under it. To its lower right, a key plan at 1 inch to 40 feet: the lot, its setbacks, the building and the trees, turned 30 degrees, with its own turned north arrow and title. At the right, a column of site data, general notes, a legend and abbreviations, and in the lower right corner a title block with the project, the sheet title, the date, the scale and the sheet number C-101 + A landscape sheet, 3 wide to 2 tall, inside a border. At the left, a permit-style site plan at 1 inch to 10 feet: a lot with its bearings, setback lines, a building footprint with dimension strings, a driveway, a sidewalk, trees and the street, a revision cloud around the driveway, with a north arrow, the view title and a graphic scale under it. To its lower right, a key plan at 1 inch to 40 feet: the lot, its setbacks, the building and the trees, turned 30 degrees, with its own turned north arrow and title. At the right, a column of site data, general notes, a legend and abbreviations, and in the lower right corner a title block with the project, the sheet title, the date, the scale and the sheet number C-101 The example sheet: a permit-style site plan on an ARCH D sheet, 36 by 24 inches, @@ -52,7 +52,9 @@ at 1" = 10'. It is the file to copy to start a drawing. `plan`, which sizes it by how large it plots at the view's scale. The dimensions are dimension objects in the standard's dimension style at that scale, so CAD measures them, and the leaders are leader objects in its - leader style, one with two shafts. + leader style, one with two shafts. A revision cloud wraps the driveway and + its label, one polyline of arcs that bulge out of its outline so that it + crosses neither, with a delta that holds the revision's number. - **The layout `C-101`** holds the sheet, in inches of paper: the border, the title block, a column of site data, general notes, a legend and abbreviations, and under each view its north arrow and its title, and under @@ -61,8 +63,8 @@ at 1" = 10'. It is the file to copy to start a drawing. One viewport shows the view on the layout at its scale. A second shows the view `key-plan` of the same model space, at 1" = 40' and turned 30 degrees with `twist`, and freezes the layers that are sized for the plan or run to its -edges with `frozenLayers`: the dimensions, the text, the property corners, the -adjoining lot lines, the pavement and the centerline. So the key plan shows the +edges with `frozenLayers`: the dimensions, the text, the revision, the property +corners, the adjoining lot lines, the pavement and the centerline. So the key plan shows the lot, its setbacks, the building and the trees, and the plan's viewport still shows everything. The key plan's north arrow is turned as far as its view. Both viewports are on a layer that does not plot, so their borders stay off the @@ -101,12 +103,13 @@ their own, `VIEW_TITLE` and `VIEW_SCALE`, so no tag names two fields. own border. The trees, the property corners, the north arrow and the view title are blocks -too. The tree and the property corner are in the plan and in the legend, so +too. The north arrow's head is one polyline that widens from nothing at its tip, +which CAD programs fill. The tree and the property corner are in the plan and in the legend, so each is inserted in model space and on the layout: the tree at each tree's radius in the plan and at 3/16 inch in the legend. The sheet is drawn to a standard of its own, `standard`, which extends -`BUILT_IN_STANDARD` with the layer `V-TREE`. Each layer is named, and its color, +`BUILT_IN_STANDARD` with the layers `V-TREE` and `C-ANNO-REVS`. Each layer is named, and its color, linetype, pen and plot flag are the standard's. The standard's linetype scale is a length of paper, 1/2. Each text names a role of the standard, which gives its text style and the height it plots at; the title block's texts are in a diff --git a/examples/site-plan.ts b/examples/site-plan.ts index ef4aba5..b32eac2 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -1,6 +1,6 @@ // A permit-style site plan: a lot from its plat dimensions, with setbacks, a building footprint, -// the street, labels, dimensions, leaders, site data and notes, on a sheet with a border and a -// title block. Copy this file to start a drawing. +// the street, labels, dimensions, leaders, a revision cloud, site data and notes, on a sheet with +// a border and a title block. Copy this file to start a drawing. // // The drawing has two spaces, as a drafter keeps them: // @@ -41,7 +41,7 @@ // - What belongs to the site is drawn in model space, in feet. What belongs to the paper is // drawn inside `d.layout(...)`, in inches, at the size it plots. // - The drawing is drawn to a standard, `standard`, which extends the built-in one with the -// layer `V-TREE`. A layer is named, and its color, linetype, pen and plot flag are the +// layers `V-TREE` and `C-ANNO-REVS`. A layer is named, and its color, linetype, pen and plot flag are the // standard's. Its entities draw ByLayer, and one that plots heavier than its layer names a // pen of the standard. // - The plan is the view `plan`, at a scale of the standard, which the viewport shows. An @@ -58,6 +58,9 @@ // - A symbol is a block, drawn once and inserted where it is needed. The tree and the property // corner are in the plan and in the legend, so each is inserted in model space and on the // layout. A block's entities are on layer 0, so each insert draws on its own layer. +// - A revision is a cloud around what it changed, one polyline of arcs that bulge out of its +// outline, with a delta that holds its number. A polyline can also be drawn wide: the north +// arrow's head is one side that widens from nothing at its tip, which CAD programs fill. // - The key plan is a second view of the same model space, at a smaller scale and turned, in a // viewport of its own. That viewport freezes the layers of the plan's annotation, which is // sized for the plan's scale, and of the lines that run to the plan's edges, so it shows the @@ -84,11 +87,10 @@ import { type Intent, type Point, } from "../src/index.ts"; -import { arrowhead } from "./lib/drafting.ts"; /** - * The standard the sheet is drawn to: the built-in one, with a layer for the trees and a leader - * style for the notes. Its layers give the plan its colors, linetypes and pens, its linetype + * The standard the sheet is drawn to: the built-in one, with layers for the trees and the + * revision and a leader style for the notes. Its layers give the plan its colors, linetypes and pens, its linetype * scale sizes the dashes, and its leader style gives every leader its arrowhead, its landing and * the role of its note. */ @@ -96,7 +98,10 @@ export const standard = defineStandard({ id: "site-plan-example", version: "1", extends: BUILT_IN_STANDARD, - layers: { "V-TREE": { color: 3, pen: "fine", discipline: "V" } }, + layers: { + "V-TREE": { color: 3, pen: "fine", discipline: "V" }, + "C-ANNO-REVS": { color: 1, pen: "medium", discipline: "C" }, + }, leaderStyles: { notes: { role: "note", arrowSize: 1 / 8, landing: 1 / 8, gap: 1 / 16 } }, defaultLeaderStyle: "notes", }); @@ -272,7 +277,16 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee d.text([0, arrowRadius + gap], "N", { role: "heading", align: "center" }); d.circle([0, 0], arrowRadius); d.line([0, -arrowRadius], [0, arrowRadius * 0.4]); - arrowhead(d, [0, arrowRadius], [0, 0], arrowRadius * 0.9); + // The arrowhead is one polyline from the tip, where it has no width, to its base. + const head = arrowRadius * 0.9; + d.polyline( + [ + [0, arrowRadius], + [0, arrowRadius - head], + ], + false, + { widths: [[0, head / 3]] }, + ); }); // The view title: the title over a line and the scale under it. Its base point is the left // end of the line. The line has one fixed length, long enough for the sheet's view title, @@ -514,6 +528,34 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee }); }); + // A revision: a cloud around the driveway, which it changed, and a delta with its number beside + // the cloud. Each arc of the cloud is about 3/8 in on paper, and every arc bulges out + // of the outline, so the cloud crosses none of what it wraps. + d.layer("C-ANNO-REVS", () => { + const margin = plan.paper(1 / 8); + const left = driveX - driveway.flare - margin; + const right = driveX + driveway.width + driveway.flare + margin; + const bottom = pavement.near - margin; + const top = bounds.front - plan.paper(1 / 4); + const outline: Point[] = [ + [left, bottom], + [right, bottom], + [right, top], + [left, top], + ]; + d.cloud(outline, { arc: plan.paper(3 / 8) }); + // The delta: a triangle 3/8 in on a side, pointing up, with the number at its middle. + const side = plan.paper(3 / 8); + const middle: Point = [right + side, (bottom + top) / 2]; + const reach = side / Math.sqrt(3); + const corners = [90, 210, 330].map((angle): Point => { + const a = (angle * Math.PI) / 180; + return [middle[0] + reach * Math.cos(a), middle[1] + reach * Math.sin(a)]; + }); + d.polyline(corners, true); + d.text(middle, "1", { role: "label", view: plan, align: "center", valign: "middle" }); + }); + /** The point of a tree's canopy that faces `toward`, where a leader points at the tree. */ function canopyEdge(tree: (typeof trees)[number], toward: Point): Point { const [dx, dy] = [toward[0] - tree.at[0], toward[1] - tree.at[1]]; @@ -554,6 +596,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee frozenLayers: [ "C-ANNO-DIMS", "C-ANNO-TEXT", + "C-ANNO-REVS", "C-PROP-MONU", "C-PROP-ADJC", "C-PAVE", diff --git a/scripts/readme-drawing.ts b/scripts/readme-drawing.ts index 7fd05bf..1b72241 100644 --- a/scripts/readme-drawing.ts +++ b/scripts/readme-drawing.ts @@ -86,6 +86,7 @@ const pictures: Picture[] = [ "C-ROAD-CNTR": "muted", "V-TREE": "muted", "C-ANNO-DIMS": "accent", + "C-ANNO-REVS": "accent", "C-ANNO-TEXT": "line", "C-ANNO-SYMB": "line", "C-ANNO-TITL": "line", diff --git a/src/drawing.ts b/src/drawing.ts index 86ccb40..5c3102a 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -47,6 +47,7 @@ import { type PlotStyleTable, } from "./papers.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; +import { arcsAlong, cloud, donut, MAX_CLOUD_ARCS, rounded } from "./polylines.ts"; import { canonical } from "./json.ts"; import { DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; import { @@ -62,6 +63,7 @@ import { dimensionStyleTwinProblem, dimensionAngleProblem, dimensionTextProblem, + donutHoleProblem, duplicateAttributeProblem, duplicateIdProblem, handleProblem, @@ -94,6 +96,7 @@ import { layoutTwinProblem, paperProblem, plotStyleProblem, + polylineSidesProblems, R12_ONLY, scaleProblem, sheetNumberProblem, @@ -138,7 +141,10 @@ import { type LeaderTargetsOf, type LeaderText, type NewLeaderStyleName, + type DonutHole, + type PolylineWidth, type R12Leaders, + type R12Polylines, type LineweightMm, type LineweightOf, type LinetypeName, @@ -340,10 +346,25 @@ export interface Line extends EntityBase { readonly to: Point; } +/** + * A polyline: sides from each point to the next and, when it is closed, from the last back to + * the first. A side is straight, or an arc by its bulge, and may be drawn wide: CAD programs fill + * a side that has a width, and draw one of width 0 with its pen. + */ export interface Polyline extends EntityBase { readonly kind: "polyline"; readonly points: readonly Point[]; readonly closed: boolean; + /** + * The bulge of each side, one for each: 0 for a straight side, and for an arc the tangent of a + * quarter of the angle it turns through, greater than 0 when it turns counterclockwise. 1 is a + * half circle. Defaults to every side straight. R2018 only. + */ + readonly bulges?: readonly number[]; + /** The width of every side, in drawing units, 0 or more. R2018 only. */ + readonly width?: number; + /** The width of each side at its start and at its end, one pair for each side. R2018 only. */ + readonly widths?: readonly (readonly [start: number, end: number])[]; } export interface Circle extends EntityBase { @@ -969,6 +990,111 @@ export interface EntityOptions< readonly pen?: Z extends Standard ? PenOfStandard : PenWithoutStandard; } +/** + * How wide a polyline is drawn: the width of every side, in drawing units, 0 or more. CAD + * programs fill a side that has a width, at that width whatever its pen, and draw one of width 0 + * with its pen. R2018 only. + */ +interface Widened { + readonly width?: V extends "R12" ? R12Polylines : PolylineWidth; +} + +/** + * The options of `polyline()`: the bulge and the width of its sides, or a radius that rounds its + * corners, and the options of every entity. + * + * @typeParam N - The width as written. + * @typeParam R - The radius as written. + */ +export interface PolylineOptions< + V extends DxfVersion = "R2018", + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, + N extends number = number, + R extends number = number, +> + extends EntityOptions, Widened { + /** + * The bulge of each side, one for each: 0 for a straight side, and for an arc the tangent of a + * quarter of the angle it turns through, greater than 0 when it turns counterclockwise. + * `bulgeThrough` gives the bulge of the arc through a third point. R2018 only. + */ + readonly bulges?: V extends "R12" ? R12Polylines : readonly number[]; + /** The width of each side at its start and at its end, one pair for each side. R2018 only. */ + readonly widths?: V extends "R12" ? R12Polylines : readonly (readonly [number, number])[]; + /** + * Rounds every corner with an arc of this radius, tangent to both sides, as a bar's bend or a + * duct's turn is drawn. The polyline then holds the arcs' ends in place of its corners. With + * `width` only, not `bulges` or `widths`. R2018 only. + */ + readonly radius?: V extends "R12" ? R12Polylines : Positive; +} + +/** + * The options of `rect()`: a radius that rounds its corners, and the options of every entity. + * + * @typeParam R - The radius as written. + */ +export interface RectOptions< + V extends DxfVersion = "R2018", + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, + R extends number = number, +> extends EntityOptions { + /** Rounds each corner with a quarter circle of this radius, at most half the shorter side. R2018 only. */ + readonly radius?: V extends "R12" ? R12Polylines : Positive; +} + +/** + * The options of `cloud()`: the length of its arcs, its width, and the options of every entity. + * + * @typeParam A - The length of an arc as written. + * @typeParam N - The width as written. + */ +export interface CloudOptions< + A extends number = number, + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, + N extends number = number, +> + extends EntityOptions<"R2018", T, W, L, I, Z, P>, Widened<"R2018", N> { + /** + * About how far apart the ends of each arc are, in drawing units: each side of the outline + * holds the whole number of arcs nearest its length over this, and at least one. + */ + readonly arc: Positive; +} + +/** + * The options of `donut()`: the diameter of its hole, and the options of every entity. + * + * @typeParam H - The diameter of the hole as written. + */ +export interface DonutOptions< + H extends number = number, + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, +> extends EntityOptions<"R2018", T, W, L, I, Z, P> { + /** The diameter of its hole, less than the outside diameter. Defaults to 0: a filled dot. */ + readonly inside?: DonutHole; +} + /** A text style to define: a `TextStyle`, checked. */ export interface TextStyleDefinition< N extends string = string, @@ -2088,24 +2214,34 @@ export class DrawingBuilder< })); } + /** + * A polyline through `points`, and back to the first when `closed`. `bulges` makes a side an + * arc, `width` or `widths` draws the sides wide, and `radius` rounds every corner with an arc, + * as a bar's hook is bent: `d.polyline(hook, false, { radius: bend, width: bar })`. + */ polyline< T extends string = string, W extends number = number, const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, + N extends number = number, + R extends number = number, >( points: readonly Point[], closed = false, - options: EntityOptions = {}, + options: PolylineOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.polyline, options, () => { if (points.length < 2) refuse("geometry", "A polyline needs at least 2 points"); - return { kind: "polyline", layer: this.#current, points: points.map(pt), closed }; + return this.#polyline(points.map(pt), closed, options); }); } - /** Closed rectangle from its lower-left corner. */ + /** + * A closed rectangle from its lower-left corner, `width` along X and `height` along Y. `radius` + * rounds its corners. + */ rect< W extends number, H extends number, @@ -2114,11 +2250,12 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, + R extends number = number, >( corner: Point, width: Positive, height: Positive, - options: EntityOptions = {}, + options: RectOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.rect, options, () => { const [x, y] = pt(corner); @@ -2133,10 +2270,154 @@ export class DrawingBuilder< [x + w, y + h], [x, y + h], ]; - return { kind: "polyline", layer: this.#current, points: corners.map(pt), closed: true }; + const { radius } = options as { readonly radius?: unknown }; + return this.#polyline(corners.map(pt), true, radius === undefined ? {} : { radius }); + }); + } + + /** + * A revision cloud along a closed outline: the corners of a rectangle, or an outline drawn + * around what changed. It is one closed polyline of arcs from point to point along each side, + * each bulging out of the outline, so the cloud crosses nothing inside it. `arc` is about how + * far apart each arc's ends are, and `width` draws it wide. An arc that would reach across the + * outline, in a notch narrower than it bulges, is refused. R2018 only. + */ + cloud< + A extends number, + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + N extends number = number, + >( + outline: readonly Point[], + options: V extends "R12" ? R12Polylines : CloudOptions, + ): this { + const o = options as unknown as CloudOptions; + return this.#add(DrawingBuilder.prototype.cloud, o, () => { + if (this.dxf === "R12") refuse("geometry", R12_ONLY.polylines); + if (outline.length < 3) refuse("geometry", "A cloud's outline needs at least 3 points"); + const corners = outline.map(pt); + const arc = positive(o.arc, "arc"); + const count = arcsAlong(corners, arc); + if (count > MAX_CLOUD_ARCS) { + refuse( + "geometry", + `arc: the cloud would have ${count} arcs, and has at most ${MAX_CLOUD_ARCS}. Give a longer arc`, + ); + } + const made = cloud(corners, arc); + if (typeof made === "string") refuse("geometry", capitalized(made)); + return this.#polyline(made.points, true, { + bulges: made.bulges, + ...(o.width === undefined ? {} : { width: o.width }), + }); }); } + /** + * A donut: a filled ring `outside` across about `center`, with a hole `inside` across, which + * defaults to 0 for a filled dot, such as a bar cut in a section. It is one closed polyline of + * two half circles, as wide as the ring. R2018 only. + */ + donut< + D extends number, + H extends number = number, + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + >( + center: Point, + outside: V extends "R12" ? R12Polylines : Positive, + options?: V extends "R12" ? R12Polylines : DonutOptions, + ): this { + const o = (options ?? {}) as unknown as DonutOptions; + return this.#add(DrawingBuilder.prototype.donut, o, () => { + if (this.dxf === "R12") refuse("geometry", R12_ONLY.polylines); + const [x, y] = pt(center); + const across = positive(outside, "outside"); + const inside: unknown = o.inside ?? 0; + const problem = donutHoleProblem(inside); + if (problem) refuse("geometry", `inside: ${problem}`); + if (!((inside as number) < across)) { + refuse("geometry", "inside: A donut's hole must be less across than the donut"); + } + const made = donut([x, y], across, inside as number); + // Its middle, between its two points, and its ring are written within 1% of what they are. + const middle = (across + (inside as number)) / 2; + const chord = written(made.points[1]![0]) - written(made.points[0]![0]); + const off = (wrote: number, is: number): boolean => !(Math.abs(wrote - is) <= is / 100); + if (off(chord, middle) || off(written(made.width), made.width)) { + refuse( + "geometry", + "outside: The donut is too small for the 6 decimals tsdraft writes: its ring or its middle would be written more than 1% off. Give a larger donut, or a hole further from its size", + ); + } + return this.#polyline(made.points.map(pt), true, { + bulges: made.bulges, + width: made.width, + }); + }); + } + + /** + * A polyline of the current layer through `points`, with what `given` says of its sides, once + * the sides are checked. A radius rounds the corners first. + */ + #polyline( + points: readonly Point[], + closed: boolean, + given: { + readonly bulges?: unknown; + readonly width?: unknown; + readonly widths?: unknown; + readonly radius?: unknown; + }, + ): Polyline { + const { width, widths, radius } = given; + let { bulges } = given; + if ( + this.dxf === "R12" && + (bulges !== undefined || width !== undefined || widths !== undefined || radius !== undefined) + ) { + refuse("geometry", R12_ONLY.polylines); + } + let shape = points; + if (radius !== undefined) { + if (bulges !== undefined || widths !== undefined) { + refuse( + "geometry", + "radius: A polyline whose corners a radius rounds takes no bulges or widths of its own, since its sides are made anew. Give it width alone", + ); + } + const made = rounded(points, closed, positive(radius, "radius")); + if (typeof made === "string") refuse("geometry", `radius: ${capitalized(made)}`); + shape = made.points.map(pt); + if (made.bulges.some((bulge) => bulge !== 0)) bulges = made.bulges; + } + const sides = closed ? shape.length : shape.length - 1; + const [problem] = polylineSidesProblems(sides, bulges, width, widths); + if (problem) refuse("geometry", capitalized(problem)); + return { + kind: "polyline", + layer: this.#current, + points: shape, + closed, + ...(bulges === undefined ? {} : { bulges: [...(bulges as readonly number[])] }), + ...(width === undefined ? {} : { width: width as number }), + ...(widths === undefined + ? {} + : { + widths: (widths as readonly (readonly [number, number])[]).map( + ([start, end]) => [start, end] as const, + ), + }), + }; + } + circle< R extends number, T extends string = string, @@ -4386,6 +4667,11 @@ function positive(value: unknown, label: string): number { return value; } +/** A problem as a sentence of its own. */ +function capitalized(problem: string): string { + return problem.charAt(0).toUpperCase() + problem.slice(1); +} + function lostSide(size: string, axis: string, at: number): string { return `${size}: This value is too small at ${axis} = ${at}. Both sides of the rectangle are written as ${axis} = ${fmt(at)}, because tsdraft writes 6 decimals`; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 7d1112a..2a9c90f 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -985,16 +985,25 @@ function writeEntity( point(g, 10, ...e.from); point(g, 11, ...e.to); return; - case "polyline": + case "polyline": { begin("LWPOLYLINE", "AcDbPolyline"); g(90, e.points.length); g(70, e.closed ? 1 : 0); - g(43, 0); // constant width - for (const [x, y] of e.points) { + // A width for each side is written at each point, and a constant width once. + if (e.widths === undefined) g(43, e.width ?? 0); + e.points.forEach(([x, y], i) => { g(10, x); g(20, y); - } + const pair = e.widths?.[i]; + if (e.widths) { + g(40, pair?.[0] ?? 0); + g(41, pair?.[1] ?? 0); + } + const bulge = e.bulges?.[i] ?? 0; + if (written(bulge) !== 0) g(42, bulge); + }); return; + } case "circle": begin("CIRCLE", "AcDbCircle"); point(g, 10, ...e.center); diff --git a/src/extents.ts b/src/extents.ts index 74ca0e1..fadb720 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -19,10 +19,12 @@ import type { Leader, LeaderStyle, Point, + Polyline, Text, TextStyle, } from "./drawing.ts"; import { layerKey, layerKeys } from "./layers.ts"; +import { hasArcsOrWidths, mayCurve, polylineBox, PolylineMemo } from "./polylines.ts"; import { leaderPicture, leaderRepeats } from "./leaders.ts"; import { inStyle, measurer } from "./measure.ts"; import { filled } from "./shape.ts"; @@ -58,7 +60,8 @@ const SHARED = 64; const LONG = 256; /** - * Approximate extents. Arcs use their full circle. A text counts for the box `measureText` + * Approximate extents. Arcs use their full circle, and a polyline counts for its points, the + * arcs of its sides and its wide sides with their joins. A text counts for the box `measureText` * gives it, its capitals as long as the text plots, justified, turned and leaned as it is, * and for what its font draws below the baseline. An insert counts for the box of what its block * draws, in the block's coordinates, where the insert puts the box's corners, so a turned insert @@ -260,7 +263,7 @@ export function boxer( add(...e.to); break; case "polyline": { - const box = pointsBox(e.points); + const box = curvedBox(e) ?? pointsBox(e.points); if (box[0] === Infinity) break; add(box[0], box[1]); add(box[2], box[3]); @@ -309,6 +312,47 @@ export function boxer( if (long) pointBoxes.set(points, box); return box; }; + /** + * The box of a polyline with an arc or a width, or undefined for one with neither, worked out + * once for every polyline that holds the same lists: its points, its arcs and its filled sides. + * A long list read again for another polyline is paid for, as `lint` pays for it. + */ + const curvedBoxes = new PolylineMemo(); + const curvedLists = new WeakSet(); + const curvedBox = (e: Polyline): Bounds | undefined => { + if (!mayCurve(e)) return undefined; + const known = curvedBoxes.get(e); + if (known !== undefined) return known ?? undefined; + /** + * Pays for reading long lists again, a unit for each `per` items, and says whether there was + * room to. + */ + const paid = (lists: readonly unknown[], per: number): boolean => { + let cost = 0; + for (const list of lists) { + if (!Array.isArray(list) || list.length < SHARED) continue; + if (curvedLists.has(list)) cost += Math.floor(list.length / per); + else curvedLists.add(list); + } + return cost === 0 || spend(cost); + }; + // Telling whether it has an arc or a width reads its bulges and widths. Boxing it reads its + // points and works out each side's arc, filled shape and join, which costs more for each. + if (!paid([e.bulges, e.widths], 8)) return empty(); + if (!hasArcsOrWidths(e)) { + curvedBoxes.set(e, null); + return undefined; + } + if (!paid([e.points], 2)) return empty(); + const box = empty(); + const found = polylineBox(e); + if (found) { + include(box, found[0], found[1]); + include(box, found[2], found[3]); + } + curvedBoxes.set(e, box); + return box; + }; /** What a dimension draws: its lines, its arrowheads, and its text as any text is boxed. */ const dimension = (e: Dimension, from: Names, add: Add): void => { const style = from.dimensionStyles.get(key(e.style)); diff --git a/src/index.ts b/src/index.ts index 12eafcf..4d733e8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -48,8 +48,10 @@ export { type Block, type BlockOptions, type Circle, + type CloudOptions, type DimensionStyle, type DimensionStyleDefinition, + type DonutOptions, type Drawing, type DrawingOptions, type DxfVersion, @@ -77,6 +79,8 @@ export { type Lineweight, type Point, type Polyline, + type PolylineOptions, + type RectOptions, type Sheet, type StandardAlignedDimensionOptions, type StandardLeaderOptions, @@ -98,6 +102,7 @@ export { type Zone, } from "./drawing.ts"; export { toDXF, type DxfOptions } from "./dxf.ts"; +export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; export { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; export { FONTS, type Font, type FontInfo } from "./fonts.ts"; export { idHandle } from "./handles.ts"; @@ -157,6 +162,7 @@ export type { DimensionAffix, DimensionPrefix, DimensionScale, + DonutHole, DimensionStyleName, DimensionText, EntityId, @@ -184,6 +190,7 @@ export type { PaperLength, PaperOf, Pattern, + PolylineWidth, Positive, Precision, Ratio, diff --git a/src/intent.ts b/src/intent.ts index d472d47..db8e1da 100644 --- a/src/intent.ts +++ b/src/intent.ts @@ -452,6 +452,16 @@ function outlineOf( return { why: ", which has a point that is not two numbers" }; } } + // An arc's side is no straight line between its points, which the checks measure. + const bulges: unknown = entity.bulges; + if (Array.isArray(bulges)) { + if (!spend(READ_COST * bulges.length)) return "short"; + if (bulges.some((bulge) => bulge !== 0)) { + return { + why: ", which has a side that is an arc. checkIntent takes an outline of straight sides", + }; + } + } const same = (p: Point, q: Point): boolean => p[0] === q[0] && p[1] === q[1]; const corners: Point[] = []; for (let i = 0; i < points.length; i++) { diff --git a/src/lint.ts b/src/lint.ts index c1920e8..8498963 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -123,6 +123,7 @@ import { linetypeScaleProblem, R12_ONLY, magnitudeProblem, + polylineSidesProblems, paperProblem, placedAttributeProblem, plotStyleProblem, @@ -1417,16 +1418,15 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // there may be unreported, and toDXF refuses the drawing. if (stopped !== undefined) return; const here = () => `${entity.kind} #${index} of ${space}`; - // A long list of points that many polylines share is read again for each, and paid for. - const points: unknown = - isObject(entity) && entity.kind === "polyline" ? entity.points : undefined; - if ( - Array.isArray(points) && - points.length >= FREE && - again(points) && - !spend(Math.floor(points.length / 8), here) - ) { - return; + // A long list of points, bulges or widths that many polylines share is read again for + // each, and paid for. + if (isObject(entity) && entity.kind === "polyline") { + let cost = 0; + for (const list of [entity.points, entity.bulges, entity.widths]) { + if (Array.isArray(list) && list.length >= FREE && again(list)) + cost += Math.floor(list.length / 8); + } + if (cost > 0 && !spend(cost, here)) return; } // What the extents would do again is paid for there, so a drawing that can cost them // anything is boxed below. @@ -1465,6 +1465,13 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (layer) add("undefined-layer", "error", layer); const problems = geometryProblems(entity); for (const problem of problems) add("geometry", "error", problem); + if ( + r12 && + entity.kind === "polyline" && + (entity.bulges !== undefined || entity.width !== undefined || entity.widths !== undefined) + ) { + add("geometry", "error", R12_ONLY.polylines); + } if (entity.kind === "insert") { if (r12) { add("block", "error", R12_ONLY.blocks); @@ -2037,12 +2044,16 @@ function asText(definition: AttributeDefinition): Text { } /** - * True for an entity whose box can cost anything: an insert, a dimension, a leader, and a text - * too long for a table of strings to keep. + * True for an entity whose box can cost anything: an insert, a dimension, a leader, a text too + * long for a table of strings to keep, and a polyline that may have an arc or a width, whose box + * pays for a long list read again. */ function costsBoxes(e: Readonly>): boolean { const kind = e.kind; if (kind === "text") return typeof e.value === "string" && e.value.length > KEYED; + if (kind === "polyline") { + return Array.isArray(e.bulges) || Array.isArray(e.widths) || typeof e.width === "number"; + } return ( kind === "insert" || kind === "leader" || @@ -2082,6 +2093,10 @@ function geometryProblems(e: Entity): string[] { break; } } + if (e.points.length >= 2) { + const sides = e.closed ? e.points.length : e.points.length - 1; + out.push(...polylineSidesProblems(sides, e.bulges, e.width, e.widths)); + } break; case "circle": finite("its center", ...e.center); diff --git a/src/polylines.ts b/src/polylines.ts new file mode 100644 index 0000000..14851f3 --- /dev/null +++ b/src/polylines.ts @@ -0,0 +1,664 @@ +// What a polyline draws: each side, straight or an arc by its bulge, and how wide it is at each +// end, from the numbers as they are written. The writers, `toSVG`, the extents and the builder's +// shapes all read it. And the shapes the builder makes of polylines: a corner rounded by a +// radius, a revision cloud along an outline, a donut, and the bulge of an arc through a point. +import type { Point, Polyline } from "./drawing.ts"; +import { written } from "./format.ts"; +import { filled } from "./shape.ts"; + +/** A side of a polyline, from one of its points to the next. */ +export interface PolylineSide { + readonly from: Point; + readonly to: Point; + /** Its bulge as written: 0 for a straight side. */ + readonly bulge: number; + /** Its width at `from` and at `to`, as written. */ + readonly startWidth: number; + readonly endWidth: number; +} + +/** The arc of a side with a bulge, about its center. */ +export interface SideArc { + readonly center: Point; + readonly radius: number; + /** The angle of the side's `from` about the center, in radians counterclockwise from +X. */ + readonly start: number; + /** The angle it turns through, in radians, counterclockwise when greater than 0. */ + readonly sweep: number; +} + +/** + * The sides of a polyline, from each point to the next and, when it is closed, from the last back + * to the first, with the points, the bulge and the widths each is written with. A list of bulges + * or widths that does not have one item for each side up to its first empty slot, or a value that + * is no number, counts as 0, as `lint` reports it. + */ +export function polylineSides(e: Polyline): PolylineSide[] { + const points = (filled(e.points) as readonly Point[]).map(([x, y]): Point => [ + number(x), + number(y), + ]); + const count = e.closed ? points.length : points.length - 1; + if (count < 1) return []; + // A list of points with an empty slot has its sides up to it straight and of no width, as + // `hasArcsOrWidths`, which reads no point, takes them. + const whole = Array.isArray(e.points) && e.points.length === points.length; + const each = (list: unknown): readonly unknown[] | undefined => + whole && Array.isArray(list) && list.length === count && filled(list).length === count + ? list + : undefined; + const bulges = each(e.bulges); + const widths = each(e.widths); + const constant = typeof e.width === "number" ? number(e.width) : 0; + const sides: PolylineSide[] = []; + for (let i = 0; i < count; i++) { + const pair: unknown = widths?.[i]; + const [start, end] = Array.isArray(pair) ? pair : [constant, constant]; + sides.push({ + from: points[i]!, + to: points[(i + 1) % points.length]!, + bulge: number(bulges?.[i]), + startWidth: Math.max(0, number(start)), + endWidth: Math.max(0, number(end)), + }); + } + return sides; +} + +/** A number as written, and 0 for anything else. */ +function number(value: unknown): number { + return typeof value === "number" && Number.isFinite(value) ? written(value) : 0; +} + +/** The key `PolylineMemo` keeps a field that is no list by, which its sides read as none. */ +const NO_LIST: object = Object.freeze({}); + +/** + * Values worked out for polylines, each kept for every polyline that holds the same lists of + * points, bulges and widths, the same width and the same `closed`, since a drawing made in code + * may share them among many. It lives for one call, so it holds what the drawing holds. + */ +export class PolylineMemo { + readonly #values = new Map>>>(); + + get(e: Polyline): T | undefined { + const [points, bulges, widths] = PolylineMemo.#lists(e); + return this.#values.get(points)?.get(bulges)?.get(widths)?.get(PolylineMemo.#rest(e)); + } + + set(e: Polyline, value: T): void { + const [points, bulges, widths] = PolylineMemo.#lists(e); + let byBulges = this.#values.get(points); + if (!byBulges) this.#values.set(points, (byBulges = new Map())); + let byWidths = byBulges.get(bulges); + if (!byWidths) byBulges.set(bulges, (byWidths = new Map())); + let byRest = byWidths.get(widths); + if (!byRest) byWidths.set(widths, (byRest = new Map())); + byRest.set(PolylineMemo.#rest(e), value); + } + + /** Each list as the key it is kept by: the list itself, or one key for whatever is no list. */ + static #lists(e: Polyline): [object, object, object] { + const key = (list: unknown): object => (Array.isArray(list) ? list : NO_LIST); + return [key(e.points), key(e.bulges), key(e.widths)]; + } + + /** Whether it is closed and its width as written, which is all else its sides read. */ + static #rest(e: Polyline): string { + return `${Boolean(e.closed)}/${typeof e.width === "number" ? Math.max(0, number(e.width)) : 0}`; + } +} + +/** + * True for a polyline that may have an arc or a width: one with a list of bulges or widths, or a + * width greater than 0. It reads nothing but those three fields. + */ +export function mayCurve(e: Polyline): boolean { + return ( + Array.isArray(e.bulges) || + Array.isArray(e.widths) || + (typeof e.width === "number" && number(e.width) > 0) + ); +} + +/** + * True for a polyline with a side that is an arc or has a width. It reads no point, and of the + * bulges and widths only a list with one item for each side, up to the side count, as + * `polylineSides` does: a list of another length is read as all 0. The count is taken from the + * length of the list of points, so a list with an empty slot may be taken for one with arcs, and + * then drawn straight. + */ +export function hasArcsOrWidths(e: Polyline): boolean { + const length: unknown = Array.isArray(e.points) ? e.points.length : 0; + const count = (length as number) - (e.closed ? 0 : 1); + if (!(count >= 1)) return false; + if (typeof e.width === "number" && number(e.width) > 0) return true; + const { bulges, widths } = e; + // Each list is read up to its first empty slot. + if (Array.isArray(bulges) && bulges.length === count) { + for (let i = 0; i < count && i in bulges; i++) if (number(bulges[i]) !== 0) return true; + } + if (Array.isArray(widths) && widths.length === count) { + for (let i = 0; i < count && i in widths; i++) { + const pair: unknown = widths[i]; + if (Array.isArray(pair) && (number(pair[0]) > 0 || number(pair[1]) > 0)) return true; + } + } + return false; +} + +/** + * The arc of a side from `from` to `to` with a bulge, or undefined for a straight side and for + * one whose ends are one point, which draws nothing. + */ +export function sideArc(from: Point, to: Point, bulge: number): SideArc | undefined { + if (bulge === 0) return undefined; + const [dx, dy] = [to[0] - from[0], to[1] - from[1]]; + const chord = Math.hypot(dx, dy); + if (!(chord > 0)) return undefined; + // The center is off the middle of the chord, square to it: to its left for a bulge from 0 to 1. + const off = (1 / bulge - bulge) / 4; + const center: Point = [(from[0] + to[0]) / 2 - dy * off, (from[1] + to[1]) / 2 + dx * off]; + const size = Math.abs(bulge); + return { + center, + radius: (chord / 4) * (size + 1 / size), + start: Math.atan2(from[1] - center[1], from[0] - center[0]), + sweep: 4 * Math.atan(bulge), + }; +} + +/** The point of an arc at `t` of the way along it, from 0 at its start to 1 at its end. */ +export function arcPoint(arc: SideArc, t: number, radius = arc.radius): Point { + const angle = arc.start + arc.sweep * t; + return [arc.center[0] + radius * Math.cos(angle), arc.center[1] + radius * Math.sin(angle)]; +} + +/** A box: least X, least Y, greatest X, greatest Y. */ +export type PolylineBox = [number, number, number, number]; + +/** + * Widens `box` to hold an arc of `radius` about the arc's center: its ends and each direction + * along an axis that lies inside its sweep. + */ +export function includeArc(box: PolylineBox, arc: SideArc, radius = arc.radius): void { + const include = ([x, y]: Point): void => { + if (x < box[0]) box[0] = x; + if (y < box[1]) box[1] = y; + if (x > box[2]) box[2] = x; + if (y > box[3]) box[3] = y; + }; + include(arcPoint(arc, 0, radius)); + include(arcPoint(arc, 1, radius)); + const [from, to] = + arc.sweep > 0 ? [arc.start, arc.start + arc.sweep] : [arc.start + arc.sweep, arc.start]; + const quarter = Math.PI / 2; + for (let k = Math.ceil(from / quarter); k * quarter < to; k++) { + const angle = k * quarter; + include([arc.center[0] + radius * Math.cos(angle), arc.center[1] + radius * Math.sin(angle)]); + } +} + +/** True for a side that is drawn filled: one with a width at either end. */ +export function isWide(side: PolylineSide): boolean { + return side.startWidth > 0 || side.endWidth > 0; +} + +/** The length of a side along its arc or its chord. */ +export function sideLength( + side: PolylineSide, + arc = sideArc(side.from, side.to, side.bulge), +): number { + return arc + ? arc.radius * Math.abs(arc.sweep) + : Math.hypot(side.to[0] - side.from[0], side.to[1] - side.from[1]); +} + +/** + * The filled shape of a wide side: its corners at its start and its end, to the left and the + * right of the way it runs, and its arc. The corners of an arc are on the lines from its center + * through its ends; those of a straight side are square to it, or where a join puts them. + */ +export interface Band { + readonly side: PolylineSide; + readonly arc: SideArc | undefined; + startLeft: Point; + startRight: Point; + endLeft: Point; + endRight: Point; + /** Its corners ending square, whose lines are its edges, which each join reads. */ + readonly square: readonly [startLeft: Point, startRight: Point, endLeft: Point, endRight: Point]; +} + +/** + * How far a join may reach, in half widths. Two straight sides meet in a miter when its corner is + * no farther than this from the point where they meet: a turn of at most 2 acos(1/4), 151.04 + * degrees. A straight side meets an arc along the line from the arc's center through the point + * when its edges reach that line no farther than this from where they end square: a turn whose + * tangent is at most 4, so up to 75.96 degrees and from 104.04. Past either, both sides end + * square, as the leading CAD app plots them. + */ +const JOIN_REACH = 4; + +/** + * The filled shape of each side of a polyline drawn solid, or undefined for a side of width 0 or + * of no length, which a pen draws or nothing does. Where two wide sides meet, two straight ones + * join in a miter, a straight one and an arc along the arc's line through the point, and two arcs + * each end square; a join whose corner would reach past `JOIN_REACH` half widths is not made. + */ +export function polylineBands( + sides: readonly PolylineSide[], + closed: boolean, +): (Band | undefined)[] { + const bands = sides.map((side): Band | undefined => { + if (!isWide(side)) return undefined; + const arc = sideArc(side.from, side.to, side.bulge); + if (!(sideLength(side, arc) > 0)) return undefined; + const [h0, h1] = [side.startWidth / 2, side.endWidth / 2]; + let square: Band["square"]; + if (arc) { + // The left of an arc that turns counterclockwise is toward its center. + const inward = arc.sweep > 0 ? 1 : -1; + square = [ + arcPoint(arc, 0, arc.radius - inward * h0), + arcPoint(arc, 0, arc.radius + inward * h0), + arcPoint(arc, 1, arc.radius - inward * h1), + arcPoint(arc, 1, arc.radius + inward * h1), + ]; + } else { + const [dx, dy] = [side.to[0] - side.from[0], side.to[1] - side.from[1]]; + const length = Math.hypot(dx, dy); + const [nx, ny] = [-dy / length, dx / length]; + square = [ + [side.from[0] + nx * h0, side.from[1] + ny * h0], + [side.from[0] - nx * h0, side.from[1] - ny * h0], + [side.to[0] + nx * h1, side.to[1] + ny * h1], + [side.to[0] - nx * h1, side.to[1] - ny * h1], + ]; + } + const [startLeft, startRight, endLeft, endRight] = square; + return { side, arc, startLeft, startRight, endLeft, endRight, square }; + }); + const joins = closed ? bands.length : bands.length - 1; + for (let i = 0; i < joins; i++) { + const [a, b] = [bands[i], bands[(i + 1) % bands.length]]; + if (a && b && a !== b) join(a, b); + } + return bands; +} + +/** The direction a band runs at its start or its end, as a unit vector. */ +function heading(band: Band, end: boolean): Point { + const { arc, side } = band; + if (!arc) { + const [dx, dy] = [side.to[0] - side.from[0], side.to[1] - side.from[1]]; + const length = Math.hypot(dx, dy); + return [dx / length, dy / length]; + } + const angle = arc.start + (end ? arc.sweep : 0); + const turn = arc.sweep > 0 ? 1 : -1; + return [-Math.sin(angle) * turn, Math.cos(angle) * turn]; +} + +/** + * Joins band `a` to band `b`, which starts where `a` ends. Each join reads the edges of the sides + * as they end square, so a join at one end of a short side leaves the other end's as it is. + */ +function join(a: Band, b: Band): void { + if (a.arc && b.arc) return; + const [u, v] = [heading(a, true), heading(b, false)]; + const cos = u[0] * v[0] + u[1] * v[1]; + const at = a.side.to; + const [aStartLeft, aStartRight, aEndLeft, aEndRight] = a.square; + const [bStartLeft, bStartRight, bEndLeft, bEndRight] = b.square; + if (!a.arc && !b.arc) { + // The miter's corner is 1 / cos(turn / 2) half widths from the point. + if ((1 + cos) / 2 < 1 / JOIN_REACH ** 2) return; + const left = meet(aStartLeft, aEndLeft, bStartLeft, bEndLeft); + const right = meet(aStartRight, aEndRight, bStartRight, bEndRight); + if (!left || !right) return; + a.endLeft = b.startLeft = left; + a.endRight = b.startRight = right; + return; + } + // A straight side meets an arc on the arc's line through the point, tan(turn) half widths along + // its edges from where they end square. + const sin = u[0] * v[1] - u[1] * v[0]; + if (Math.abs(sin) > JOIN_REACH * Math.abs(cos)) return; + const arc = (a.arc ?? b.arc)!; + if (b.arc) { + const left = meet(aStartLeft, aEndLeft, arc.center, at); + const right = meet(aStartRight, aEndRight, arc.center, at); + if (left && right) [a.endLeft, a.endRight] = [left, right]; + } else { + const left = meet(bStartLeft, bEndLeft, arc.center, at); + const right = meet(bStartRight, bEndRight, arc.center, at); + if (left && right) [b.startLeft, b.startRight] = [left, right]; + } +} + +/** Where the line through `a0` and `a1` meets the line through `b0` and `b1`, or undefined for parallel lines. */ +function meet(a0: Point, a1: Point, b0: Point, b1: Point): Point | undefined { + const [dx, dy] = [a1[0] - a0[0], a1[1] - a0[1]]; + const [ex, ey] = [b1[0] - b0[0], b1[1] - b0[1]]; + const cross = dx * ey - dy * ex; + const scale = Math.hypot(dx, dy) * Math.hypot(ex, ey); + if (!(Math.abs(cross) > scale * 1e-9)) return undefined; + const t = ((b0[0] - a0[0]) * ey - (b0[1] - a0[1]) * ex) / cross; + return [a0[0] + dx * t, a0[1] + dy * t]; +} + +/** + * The box of what a polyline draws: its points, the arcs of its sides, and each wide side's + * filled shape with its joins. Undefined for one with no point. + */ +export function polylineBox(e: Polyline): PolylineBox | undefined { + const box: PolylineBox = [Infinity, Infinity, -Infinity, -Infinity]; + const include = ([x, y]: Point): void => { + if (x < box[0]) box[0] = x; + if (y < box[1]) box[1] = y; + if (x > box[2]) box[2] = x; + if (y > box[3]) box[3] = y; + }; + for (const p of filled(e.points) as readonly Point[]) include(p); + const sides = polylineSides(e); + for (const side of sides) { + const arc = sideArc(side.from, side.to, side.bulge); + if (arc) includeArc(box, arc); + } + for (const band of polylineBands(sides, e.closed)) { + if (!band) continue; + // A dash ends square where the side drawn solid is joined. + for (const p of [band.startLeft, band.startRight, band.endLeft, band.endRight, ...band.square]) + include(p); + if (band.arc) { + const most = Math.max(band.side.startWidth, band.side.endWidth) / 2; + includeArc(box, band.arc, band.arc.radius + most); + includeArc(box, band.arc, band.arc.radius - most); + } + } + return box[0] === Infinity ? undefined : box; +} + +/** + * The bulge of the arc from `from` to `to` through `through`, for a side of a polyline. It is 0 + * when the three points are on one line. + * + * @throws RangeError when two of the points are one point, so that no arc passes through them. + */ +export function bulgeThrough(from: Point, through: Point, to: Point): number { + const same = (a: Point, b: Point): boolean => a[0] === b[0] && a[1] === b[1]; + if (same(from, through) || same(through, to) || same(from, to)) { + throw new RangeError("An arc through three points needs three different points"); + } + // The arc turns through twice the angle between the chord and the way to `through`, as an + // angle at the circle's edge is half the one at its center: the bulge is the tangent of half + // the angle at `through` between the two chords, measured the other way round. + const [ax, ay] = [from[0] - through[0], from[1] - through[1]]; + const [bx, by] = [to[0] - through[0], to[1] - through[1]]; + const cross = ax * by - ay * bx; + const dot = ax * bx + ay * by; + if (cross === 0) { + if (dot < 0) return 0; + throw new RangeError( + "No arc passes through three points on one line, the middle one not between the others", + ); + } + const angle = Math.atan2(cross, dot); + return Math.tan((Math.PI - Math.abs(angle)) / 2) * (angle < 0 ? 1 : -1); +} + +/** Points and the bulge of each side between them, which a polyline holds. */ +export interface Bulged { + readonly points: Point[]; + readonly bulges: number[]; +} + +/** + * Rounds each corner of a polyline with an arc of `radius` tangent to both its sides. An open + * polyline keeps its two ends. A corner whose sides are on one line, as written, is no corner. + * Returns what is wrong in place of the points when a corner cannot be rounded: the polyline + * turns back on itself there, or the arcs at the two ends of a side need more of it than it has. + */ +export function rounded( + points: readonly Point[], + closed: boolean, + radius: number, +): Bulged | string { + const n = points.length; + /** What the corner at each point becomes: the ends of its arc and its bulge, or none. */ + const corners: ({ in: Point; out: Point; bulge: number; reach: number } | undefined)[] = []; + for (let i = 0; i < n; i++) { + if (!closed && (i === 0 || i === n - 1)) { + corners.push(undefined); + continue; + } + const [a, p, b] = [points[(i - 1 + n) % n]!, points[i]!, points[(i + 1) % n]!]; + const [ux, uy] = [p[0] - a[0], p[1] - a[1]]; + const [vx, vy] = [b[0] - p[0], b[1] - p[1]]; + const [lu, lv] = [Math.hypot(ux, uy), Math.hypot(vx, vy)]; + if (!(lu > 0 && lv > 0)) return `the corner at point ${i} has a side of no length`; + const turn = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy); + const reach = radius * Math.tan(Math.abs(turn) / 2); + // A corner the arc would leave where it is, once written, needs no arc. + const cut: Point = [p[0] - (ux / lu) * reach, p[1] - (uy / lu) * reach]; + if (written(cut[0]) === written(p[0]) && written(cut[1]) === written(p[1])) { + corners.push(undefined); + continue; + } + if (Math.abs(turn) > Math.PI * (1 - 1e-9)) { + return `the polyline turns back on itself at point ${i}, where no arc can round it`; + } + corners.push({ + in: cut, + out: [p[0] + (vx / lv) * reach, p[1] + (vy / lv) * reach], + bulge: Math.tan(turn / 4), + reach, + }); + } + // The two arcs at a side's ends must fit in it as written: the end of the first may meet the + // start of the second at one written point, and must not pass it. Two ends that meet exactly + // may be written a unit or two of the last decimal past each other, and are then made one + // point, which moves an arc's end about as far as writing it does. + const sides = closed ? n : n - 1; + const unit = 2.5e-6; + for (let i = 0; i < sides; i++) { + const [a, b] = [points[i]!, points[(i + 1) % n]!]; + const next = corners[(i + 1) % n]; + const from = corners[i]?.out ?? a; + const to = next?.in ?? b; + const along = + (written(to[0]) - written(from[0])) * (b[0] - a[0]) + + (written(to[1]) - written(from[1])) * (b[1] - a[1]); + const close = + Math.abs(written(to[0]) - written(from[0])) <= unit && + Math.abs(written(to[1]) - written(from[1])) <= unit; + if (along < 0 && close) { + if (next) next.in = from; + else if (corners[i]) corners[i]!.out = to; + continue; + } + // Arcs that need more of the side than it has end past each other, so this is where both + // refusals are made. + if (along < 0) { + const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + const need = (corners[i]?.reach ?? 0) + (corners[(i + 1) % n]?.reach ?? 0); + const between = `the arcs at points ${i} and ${(i + 1) % n}`; + return written(need) > written(length) + ? `${between} need ${written(need)} of the side between them, which is ${written(length)} long: give a smaller radius` + : `${between} end past each other once their ends are written to 6 decimals: give a radius a little smaller`; + } + } + const out: Point[] = []; + const bulges: number[] = []; + /** Adds a point, with the bulge of the side that starts there, unless it is the last one again. */ + const add = (p: Point, bulge: number): void => { + const last = out.at(-1); + if (last && written(last[0]) === written(p[0]) && written(last[1]) === written(p[1])) { + bulges[bulges.length - 1] = bulge; + return; + } + out.push(p); + bulges.push(bulge); + }; + for (let i = 0; i < n; i++) { + const corner = corners[i]; + if (corner) { + add(corner.in, corner.bulge); + add(corner.out, 0); + } else add(points[i]!, 0); + } + if (closed && out.length > 1) { + // The last point may be the first again, where a side between two arcs had no length left. + const [first, last] = [out[0]!, out.at(-1)!]; + if (written(first[0]) === written(last[0]) && written(first[1]) === written(last[1])) { + out.pop(); + bulges.pop(); + } + } + if (!closed) bulges.pop(); + return { points: out, bulges }; +} + +/** + * The bulge of each arc of a revision cloud: each turns through 110 degrees, as the arcs of the + * leading CAD app's own clouds do. + */ +export const CLOUD_BULGE = Math.tan((110 / 4) * (Math.PI / 180)); + +/** The most arcs a cloud has, so that a short arc along a long outline cannot fill memory. */ +export const MAX_CLOUD_ARCS = 10_000; + +/** + * How many arcs `cloud` puts along an outline, worked out before any is made, from its first + * point as `cloud` works. + */ +export function arcsAlong(given: readonly Point[], arc: number): number { + const [ox, oy] = given[0] ?? [0, 0]; + const outline = given.map(([x, y]): Point => [x - ox, y - oy]); + let count = 0; + for (let i = 0; i < outline.length; i++) { + const [a, b] = [outline[i]!, outline[(i + 1) % outline.length]!]; + const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (written(length) !== 0) count += Math.max(1, Math.round(length / arc)); + } + return count; +} + +/** + * A revision cloud along a closed outline: arcs from point to point along each side, as many on a + * side as the length over `arc` gives, rounded and at least one, each bulging out of the outline. + * An arc turns through less than half a circle, so it stays beside its own stretch of the side, + * and no arc may cross the outline, so the cloud never enters it: drawn around what it marks, it + * crosses none of it. Returns what is wrong in place of the points for an outline with no area, + * and for one with a notch an arc would reach across. + */ +export function cloud(given: readonly Point[], arc: number): Bulged | string { + // Worked out from the first point, so that a cloud at a survey's coordinates is as exact as one + // at the origin. + const [ox, oy] = given[0] ?? [0, 0]; + const outline = given.map(([x, y]): Point => [x - ox, y - oy]); + const made = cloudAt(outline, arc, [ox, oy]); + if (typeof made === "string") return made; + return { points: made.points.map(([x, y]): Point => [x + ox, y + oy]), bulges: made.bulges }; +} + +/** `cloud` along an outline near the origin, which messages name from `origin`. */ +function cloudAt(outline: readonly Point[], arc: number, origin: Point): Bulged | string { + const named = ([x, y]: Point): string => `(${written(x + origin[0])}, ${written(y + origin[1])})`; + let area = 0; + for (let i = 0; i < outline.length; i++) { + const [a, b] = [outline[i]!, outline[(i + 1) % outline.length]!]; + area += a[0] * b[1] - b[0] * a[1]; + } + if (!(Math.abs(area) > 0)) return "the outline of a cloud must enclose an area"; + // A positive bulge bulges to the right of the way it runs, which is out of an outline that + // runs counterclockwise. + const bulge = area > 0 ? CLOUD_BULGE : -CLOUD_BULGE; + const points: Point[] = []; + // The side of the outline each arc is on, by the point it starts at. + const sideOf: number[] = []; + for (let i = 0; i < outline.length; i++) { + const [a, b] = [outline[i]!, outline[(i + 1) % outline.length]!]; + const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (written(length) === 0) continue; + const count = Math.max(1, Math.round(length / arc)); + for (let k = 0; k < count; k++) { + points.push([a[0] + ((b[0] - a[0]) * k) / count, a[1] + ((b[1] - a[1]) * k) / count]); + sideOf.push(i); + } + } + // An arc bulges out of its own side, and in a notch narrower than it bulges it can reach the + // notch's far wall, which is another side. The check reads the cloud and the outline as the file + // would hold them, with their points and the bulge written. An arc is not held to its own side, + // which writing its ends may move it across by a hair. + const writ = ([x, y]: Point): Point => [ + written(x + origin[0]) - origin[0], + written(y + origin[1]) - origin[1], + ]; + const cloudPoints = points.map(writ); + const walls = outline.map(writ); + for (let k = 0; k < cloudPoints.length; k++) { + const [from, to] = [cloudPoints[k]!, cloudPoints[(k + 1) % cloudPoints.length]!]; + const curve = sideArc(from, to, written(bulge)); + if (!curve) continue; + const box: PolylineBox = [Infinity, Infinity, -Infinity, -Infinity]; + includeArc(box, curve); + for (let i = 0; i < walls.length; i++) { + if (i === sideOf[k]) continue; + const [a, b] = [walls[i]!, walls[(i + 1) % walls.length]!]; + if (Math.max(a[0], b[0]) < box[0] || Math.min(a[0], b[0]) > box[2]) continue; + if (Math.max(a[1], b[1]) < box[1] || Math.min(a[1], b[1]) > box[3]) continue; + const crossing = arcCrossing(curve, a, b); + if (crossing) { + return `the cloud's arc from ${named(from)} reaches across the outline at ${named(crossing)}, as in a notch narrower than an arc bulges: give a shorter arc`; + } + } + } + return { points, bulges: points.map(() => bulge) }; +} + +/** + * Where an arc crosses the segment from `a` to `b`, away from the arc's two ends, which lie on the + * outline; undefined where it does not. + */ +function arcCrossing(arc: SideArc, a: Point, b: Point): Point | undefined { + const [dx, dy] = [b[0] - a[0], b[1] - a[1]]; + const [fx, fy] = [a[0] - arc.center[0], a[1] - arc.center[1]]; + const qa = dx * dx + dy * dy; + if (!(qa > 0)) return undefined; + const qb = 2 * (fx * dx + fy * dy); + const qc = fx * fx + fy * fy - arc.radius * arc.radius; + const root = qb * qb - 4 * qa * qc; + if (root < 0) return undefined; + const ends = [arcPoint(arc, 0), arcPoint(arc, 1)]; + const near = 1e-9 * (arc.radius + Math.sqrt(qa)); + for (const sign of [-1, 1]) { + const t = (-qb + sign * Math.sqrt(root)) / (2 * qa); + if (t < 0 || t > 1) continue; + const p: Point = [a[0] + dx * t, a[1] + dy * t]; + if (ends.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= near)) continue; + // On the arc when its angle from the arc's start, the way the arc turns, is inside its sweep. + const angle = Math.atan2(p[1] - arc.center[1], p[0] - arc.center[0]) - arc.start; + const turn = 2 * Math.PI; + const along = arc.sweep > 0 ? ((angle % turn) + turn) % turn : ((-angle % turn) + turn) % turn; + if (along < Math.abs(arc.sweep)) return p; + } + return undefined; +} + +/** + * A donut of `outside` across about `center`, with a hole `inside` across: a closed polyline of + * two half circles, as wide as the ring, through the middle of the ring. + */ +export function donut(center: Point, outside: number, inside: number): Bulged & { width: number } { + const middle = (outside + inside) / 4; + return { + points: [ + [center[0] - middle, center[1]], + [center[0] + middle, center[1]], + ], + bulges: [1, 1], + width: (outside - inside) / 2, + }; +} diff --git a/src/read/check.ts b/src/read/check.ts index d524798..175b3bd 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -125,6 +125,9 @@ const ENTITY: Readonly> = { kind: { oneOf: ["polyline"] }, points: { list: "point" }, closed: "boolean", + "bulges?": { list: "number" }, + "width?": "number", + "widths?": { list: "point" }, }, circle: { ...BASE, kind: { oneOf: ["circle"] }, center: "point", radius: "number" }, arc: { diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 7546d50..cc883c8 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -16,6 +16,7 @@ import { nameCost, placementOf, readingOf, + sidesOf, type Later, type PendingStart, } from "./entities.ts"; @@ -412,8 +413,11 @@ interface PolylineOwner { readonly kind: "polyline"; readonly rec: Rec; points: Point[]; - arcs: boolean; - wide: boolean; + /** The bulge and the widths each vertex gives the side from it to the next. */ + bulges: number[]; + widths: [number, number][]; + /** The widths of a vertex that gives none, the polyline's own. */ + readonly widthsAt: readonly [number, number]; over: boolean; broken: boolean; readonly face: Facing; @@ -860,8 +864,9 @@ class DxfReader { kind: "polyline", rec: r, points: [], - arcs: false, - wide: (num(r, 40) ?? 0) !== 0 || (num(r, 41) ?? 0) !== 0, + bulges: [], + widths: [], + widthsAt: [num(r, 40) ?? 0, num(r, 41) ?? 0], over: false, broken: brokenNumber(r), face, @@ -1074,14 +1079,20 @@ class DxfReader { if (brokenNumber(r)) owner.broken = true; // A spline's frame point is not a point of the polyline. if ((flags & 16) === 0 && target && !owner.over) { - // A polyline that cannot fit what its target may still keep holds no more points. + // A polyline that cannot fit what its target may still keep holds no more points, nor + // the bulge and the pair of widths of each. if (owner.points.length >= this.#room(target)) { owner.over = true; owner.points = []; - } else owner.points.push(point(r, 10)); + owner.bulges = []; + owner.widths = []; + } else { + owner.points.push(point(r, 10)); + owner.bulges.push(num(r, 42) ?? 0); + // A vertex with no width of its own has the polyline's. + owner.widths.push([num(r, 40) ?? owner.widthsAt[0], num(r, 41) ?? owner.widthsAt[1]]); + } } - if ((num(r, 42) ?? 0) !== 0) owner.arcs = true; - if ((num(r, 40) ?? 0) !== 0 || (num(r, 41) ?? 0) !== 0) owner.wide = true; } #placeInsert(owner: InsertOwner): void { @@ -1123,15 +1134,15 @@ class DxfReader { // 8 is a 3D polyline, 16 a mesh and 64 a face mesh. if ((flags & (8 | 16 | 64)) !== 0 || owner.face === 0) add(target.other, "POLYLINE in 3D"); else if (owner.broken) add(this.unread.malformed, "POLYLINE with a number that is not finite"); - else if (owner.arcs) add(target.other, "POLYLINE with arcs"); - else if (owner.wide) add(target.other, "POLYLINE with widths"); else if (owner.over) add(target.other, "past the limit"); else { + const closed = (flags & 1) !== 0; this.#kept(target, { ...baseOf(r, name(r, 8) ?? "0", handleAt(r, 5)), kind: "polyline", points: owner.face === -1 ? owner.points.map((p) => placed(p, -1)) : owner.points, - closed: (flags & 1) !== 0, + closed, + ...sidesOf(owner.points.length, closed, owner.bulges, owner.widths, 0, owner.face), }); } } diff --git a/src/read/entities.ts b/src/read/entities.ts index 1a9c78b..ff75e2a 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -9,6 +9,7 @@ import type { ReadEntityBase, ReadMtext, ReadMultileader, + ReadPolyline, ReadTextPlacement, } from "./model.ts"; import { @@ -221,30 +222,66 @@ export function readingOf( function lwpolyline(r: Rec, base: ReadEntityBase, face: Facing): Reading { if (face === 0) return { other: "LWPOLYLINE in 3D" }; const points: Point[] = []; - let arcs = false; - let x: number | undefined; - let wide = (num(r, 43) ?? 0) !== 0; + // The bulge and the two widths each point gives the side from it to the next, from its group + // 10 up to the next point's, in whatever order they come. + const bulges: number[] = []; + const widths: [number, number][] = []; + let vertex: { x: number; y?: number; bulge: number; widths: [number, number] } | undefined; + const close = (): void => { + if (vertex?.y === undefined) return; + points.push(placed([vertex.x, vertex.y], face)); + bulges.push(vertex.bulge); + widths.push(vertex.widths); + }; for (let i = 0; i < r.codes.length; i++) { const code = r.codes[i]; - if (code === 10) x = Number(r.values[i]); - else if (code === 20 && x !== undefined) { - points.push(placed([x, Number(r.values[i])], face)); - x = undefined; - } else if (code === 42 && Number(r.values[i]) !== 0) arcs = true; - else if ((code === 40 || code === 41) && Number(r.values[i]) !== 0) wide = true; + const value = Number(r.values[i]); + if (code === 10) { + close(); + vertex = { x: value, bulge: 0, widths: [0, 0] }; + } else if (vertex === undefined) continue; + else if (code === 20 && vertex.y === undefined) vertex.y = value; + else if (code === 42) vertex.bulge = value; + else if (code === 40 || code === 41) vertex.widths[code - 40] = value; } - if (arcs) return { other: "LWPOLYLINE with arcs" }; - if (wide) return { other: "LWPOLYLINE with widths" }; + close(); + const closed = ((num(r, 70) ?? 0) & 1) !== 0; return { entity: { ...base, kind: "polyline", points, - closed: ((num(r, 70) ?? 0) & 1) !== 0, + closed, + ...sidesOf(points.length, closed, bulges, widths, num(r, 43) ?? 0, face), }, }; } +/** + * The bulges and the widths of a polyline's sides, from what each of its points gives the side + * from it to the next, as `ReadPolyline` holds them: each left out when every one is 0, and the + * constant width only where no point gives a width of its own. A bulge seen from below turns the + * other way. + */ +export function sidesOf( + count: number, + closed: boolean, + bulges: readonly number[], + widths: readonly (readonly [number, number])[], + constant: number, + face: Facing, +): Pick { + const sides = closed ? count : Math.max(0, count - 1); + const bent = bulges.slice(0, sides).map((bulge) => (face === -1 ? -bulge : bulge)); + const own = widths.slice(0, sides); + const wide = own.some(([start, end]) => start !== 0 || end !== 0); + return { + ...(bent.some((bulge) => bulge !== 0) ? { bulges: bent.map((bulge) => bulge + 0) } : {}), + ...(wide ? { widths: own.map(([start, end]) => [start, end] as const) } : {}), + ...(!wide && constant !== 0 ? { width: constant } : {}), + }; +} + function mtext(record: Rec, base: ReadEntityBase): Reading { const face = facing(record); if (face !== 1) return { other: face === -1 ? "MTEXT seen from below" : "MTEXT in 3D" }; @@ -417,7 +454,8 @@ export const attributeCost = (a: ReadAttribute): number => /** * What an entity costs against `BLOCK_ITEMS` or `GEOMETRY_ITEMS`: one, and one more for each of - * its points, each attribute or tag, and each 32 characters of its names and its text. + * its points, bulges and pairs of widths, each attribute or tag, and each 32 characters of its + * names and its text. */ export function costOf(e: ReadEntity): number { const own = 1 + chars(e.layer) + chars(e.linetype); @@ -428,6 +466,7 @@ export function costOf(e: ReadEntity): number { case "arc": return own + 1; case "polyline": + return own + e.points.length + (e.bulges?.length ?? 0) + (e.widths?.length ?? 0); case "solid": return own + e.points.length; case "text": diff --git a/src/read/model.ts b/src/read/model.ts index abd65ce..2195247 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -243,11 +243,23 @@ export interface ReadLine extends ReadEntityBase { readonly to: Point; } -/** A polyline of straight segments. */ +/** + * A polyline in its plane: a lightweight one, or a 2D one with its vertices. Its sides are + * straight or arcs, and may be wide, as a `Polyline`'s are. + */ export interface ReadPolyline extends ReadEntityBase { readonly kind: "polyline"; readonly points: readonly Point[]; readonly closed: boolean; + /** + * The bulge of each side, one for each, as a `Polyline` holds them, in the world's coordinates: + * greater than 0 for an arc that turns counterclockwise. Left out when every side is straight. + */ + readonly bulges?: readonly number[]; + /** The width of every side. Left out at 0, and when the file gives each side its own. */ + readonly width?: number; + /** The width at the start and the end of each side, one pair for each. Left out when none is not 0. */ + readonly widths?: readonly (readonly [start: number, end: number])[]; } export interface ReadCircle extends ReadEntityBase { diff --git a/src/rules.ts b/src/rules.ts index 7a6412f..99321e2 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -131,6 +131,11 @@ const R12_DIMENSIONS = 'tsdraft writes no dimensions to R12 drawings. Use DXF version "R2018" for a dimension'; const R12_LEADERS = 'tsdraft writes no leaders to R12 drawings. Use DXF version "R2018" for a leader'; +const R12_POLYLINES = + 'tsdraft writes no arcs or widths of a polyline to R12 drawings. Use DXF version "R2018" for a polyline with bulges or a width'; +const POLYLINE_WIDTH = + "A polyline's width cannot be less than 0. The leading CAD app reads a negative width of every side as 0, and keeps a negative width of one side with no AUDIT error"; +const DONUT_HOLE = "A donut's hole cannot be less than 0 across"; const ARROWHEAD_BLOCK = "Block names cannot be _ArchTick, _Open, _Dot or _None, in any case of their letters. The leading CAD app draws the architectural tick of a dimension and the arrowheads of a leader with the blocks of those names"; const STANDARD_DIMENSION_STYLE_DEFINED = @@ -865,6 +870,13 @@ export type R12Xrefs = typeof R12_XREFS; export type R12Layouts = typeof R12_LAYOUTS; export type R12Dimensions = typeof R12_DIMENSIONS; export type R12Leaders = typeof R12_LEADERS; +export type R12Polylines = typeof R12_POLYLINES; + +/** Resolves to `N` when it is a width a polyline can have, and to the error message otherwise. */ +export type PolylineWidth = NotNegative; + +/** Resolves to `N` when it is a donut's hole, and to the error message otherwise. */ +export type DonutHole = NotNegative; /** Returns what is wrong with a layer name for a DXF version, or undefined when it is valid. */ export function layerNameProblem(name: string, version: DxfVersion): string | undefined { @@ -1027,8 +1039,75 @@ export const R12_ONLY = { layouts: R12_LAYOUTS, dimensions: R12_DIMENSIONS, leaders: R12_LEADERS, + polylines: R12_POLYLINES, } as const; +/** What is wrong with a donut's hole, of `inside` across, or undefined. */ +export function donutHoleProblem(inside: unknown): string | undefined { + return notNegativeProblem(inside, DONUT_HOLE); +} + +/** + * What is wrong with the bulges and the widths of a polyline of `sides` sides, or undefined for + * each that is sound. It takes `unknown`s so that `lint` can report a drawing built by hand. A + * bulge and a width are judged as written: a width written as 0 is 0, and a bulge written as 0 + * is a straight side. + */ +export function polylineSidesProblems( + sides: number, + bulges: unknown, + width: unknown, + widths: unknown, +): string[] { + const out: string[] = []; + const counted = (list: readonly unknown[], what: string): boolean => { + if (list.length === sides) return true; + out.push( + `its ${what} must have one for each side, ${sides}, and it has ${list.length}. A closed polyline has a side for each point, and an open one a side fewer`, + ); + return false; + }; + if (bulges !== undefined) { + if (!Array.isArray(bulges)) out.push("its bulges must be an array of numbers"); + else if (counted(bulges, "bulges")) { + for (let i = 0; i < bulges.length; i++) { + const bulge: unknown = bulges[i]; + const problem = + typeof bulge !== "number" || !Number.isFinite(bulge) + ? "must be a finite number" + : magnitudeProblem(bulge); + if (!problem) continue; + out.push(`its bulge ${i}: ${problem}`); + break; + } + } + } + if (width !== undefined && widths !== undefined) { + out.push("it has a width and widths for each side: give one or the other"); + } + if (width !== undefined) { + const problem = notNegativeProblem(width, POLYLINE_WIDTH); + if (problem) out.push(`its width: ${problem}`); + } + if (widths !== undefined) { + if (!Array.isArray(widths)) out.push("its widths must be an array of pairs of numbers"); + else if (counted(widths, "widths")) { + for (let i = 0; i < widths.length; i++) { + const pair: unknown = widths[i]; + const problem = + !Array.isArray(pair) || pair.length !== 2 + ? "must be a pair of numbers, [start, end]" + : (notNegativeProblem(pair[0], POLYLINE_WIDTH) ?? + notNegativeProblem(pair[1], POLYLINE_WIDTH)); + if (!problem) continue; + out.push(`its widths ${i}: ${problem}`); + break; + } + } + } + return out; +} + /** How a text is justified across its line, and up and down it. The first of each is the default. */ export const TEXT_ALIGNS = ["left", "center", "right"] as const; export const TEXT_VERTICAL_ALIGNS = ["baseline", "bottom", "middle", "top"] as const; diff --git a/src/shape.ts b/src/shape.ts index 7d8e3be..919d778 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -335,11 +335,12 @@ function shapes(all: boolean, typed = all): Shapes { (value, at, problems) => { const items = value as readonly unknown[]; if (array(value, at) || items.length !== 2 || !isNumber(items[0]) || !isNumber(items[1])) { - problems.push(`${at} must be ${what}, [x, y]`); + problems.push(`${at} must be ${what}`); } }; - const point = pair("a point"); - const scale = pair("a scale along each axis"); + const point = pair("a point, [x, y]"); + const scale = pair("a scale along each axis, [x, y]"); + const sideWidths = pair("the widths at a side's start and end, [start, end]"); const oneOf = (...values: readonly string[]): Check => (value, at, problems) => { @@ -456,7 +457,7 @@ function shapes(all: boolean, typed = all): Shapes { line: fields({ kind, layer: string, from: point, to: point }, shared), polyline: fields( { kind, layer: string, points: list(point), closed: boolean }, - shared, + { ...shared, bulges: list(number), width: number, widths: list(sideWidths) }, ), circle: fields({ kind, layer: string, center: point, radius: number }, shared), arc: fields( diff --git a/src/svg.ts b/src/svg.ts index c4cd706..4b9a7fd 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -20,10 +20,25 @@ import { type LeaderStyle, type Line, type Point, + type Polyline, type Text, type TextStyle, type Viewport, } from "./drawing.ts"; +import { + arcPoint, + hasArcsOrWidths, + isWide, + mayCurve, + polylineBands, + polylineSides, + PolylineMemo, + sideArc, + sideLength, + type Band, + type PolylineSide, + type SideArc, +} from "./polylines.ts"; import { boxer, type Boxer } from "./extents.ts"; import { fontInfo, STANDARD_FONT } from "./fonts.ts"; import { fmt, written } from "./format.ts"; @@ -177,6 +192,9 @@ const MAX_WALKED = 2_000_000; */ const CHARACTERS = 250; +/** The fewest items of a list a plan reads that `toSVG` pays for when another plan reads it again. */ +const PLANNED = 64; + /** The viewports of a picture that look through model space free of `MAX_WALKED`. */ const FREE_VIEWS = 64; @@ -252,6 +270,81 @@ interface Sides { readonly longest: number; } +/** + * What a polyline with an arc or a width draws, worked out once a picture, so that a placement + * does work only for what it draws: each side that has a length, with its arc, the length a + * pattern is fitted to and, + * drawn solid, its filled shape and joins, and the longest side. + */ +interface Plan { + readonly parts: readonly { + readonly side: PolylineSide; + readonly arc: SideArc | undefined; + /** + * The length a pattern is fitted to: the side's own, or for a wide arc its length along its + * outer edge, at the larger of its widths. + */ + readonly fit: number; + readonly band: Band | undefined; + }[]; + /** The longest `fit`, which a pattern too fine for draws the whole polyline solid. */ + readonly longest: number; +} + +/** + * What a picture works out once: the sides of each list of points, and the plan of each + * polyline with an arc or a width, or `null` for one with neither. + */ +interface Known { + readonly sides: WeakMap; + readonly plans: PolylineMemo; + /** + * Pays for the lists a plan is about to read, when a list was read for another plan before, + * or refuses the picture. + */ + readonly readAgain: (lists: readonly unknown[]) => void; +} + +/** A new `Known`, for one picture, which pays for lists read again with `readAgain`. */ +function knowing(readAgain: Known["readAgain"] = () => {}): Known { + return { sides: new WeakMap(), plans: new PolylineMemo(), readAgain }; +} + +/** + * The plan of a polyline with an arc or a width, or undefined for one with neither, worked out + * once into `known` for every polyline that holds the same lists. + */ +function planOf(e: Polyline, known: Known): Plan | undefined { + if (!mayCurve(e)) return undefined; + const found = known.plans.get(e); + if (found !== undefined) return found ?? undefined; + // Telling whether it has an arc or a width reads its bulges and widths, and its plan its points. + known.readAgain([e.bulges, e.widths]); + if (!hasArcsOrWidths(e)) { + known.plans.set(e, null); + return undefined; + } + known.readAgain([e.points]); + const sides = polylineSides(e); + const bands = polylineBands(sides, e.closed); + const parts: Plan["parts"][number][] = []; + let longest = 0; + sides.forEach((side, i) => { + const arc = sideArc(side.from, side.to, side.bulge); + const length = sideLength(side, arc); + if (!(length > 0)) return; + const fit = + arc && isWide(side) + ? (arc.radius + Math.max(side.startWidth, side.endWidth) / 2) * Math.abs(arc.sweep) + : length; + if (fit > longest) longest = fit; + parts.push({ side, arc, fit, band: bands[i] }); + }); + const plan = { parts, longest }; + known.plans.set(e, plan); + return plan; +} + /** * 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 @@ -423,7 +516,19 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): }; /** The sides of each list of points a pattern cuts, read once for the picture. */ - const sides = new WeakMap(); + // A long list that one polyline's plan read and another's reads again is paid for, as `lint` + // pays for it, by the entity drawn at the time. + let drawingAt: (() => string) | undefined; + const planned = new WeakSet(); + const sides = knowing((lists) => { + let cost = 0; + for (const list of lists) { + if (!Array.isArray(list) || list.length < PLANNED) continue; + if (planned.has(list)) cost += Math.floor(list.length / 8); + else planned.add(list); + } + if (cost > 0 && !spend(cost)) refuse(drawingAt?.() ?? "a polyline"); + }); /** Each pattern scaled for each space, worked out when first drawn with. */ const scaled = new Map>(); @@ -522,6 +627,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const line = look.indent.length + 1; return shown.map(([i, e]) => { const where = () => entityAt(i, e, space); + drawingAt = where; if (e.kind !== "insert") { const element = drawn(e, marks(e, i), pen(look, styled(e), { name: e.layer }, where), look); if (!write(element.length + line)) refuse(where()); @@ -980,7 +1086,7 @@ function leaderToSvg( look: Look, matrix: Matrix | undefined, room: number, - sides: WeakMap, + sides: Known, ): string { if (picture === undefined) return ``; const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); @@ -1135,11 +1241,15 @@ function entityToSvg( style: TextStyle | undefined, matrix: Matrix | undefined, room: number, - sides = new WeakMap(), + sides: Known = knowing(), ): string { // A lineweight of 0 draws as the thinnest line, as in the leading CAD app. const s = `stroke="${pen.color}"${look.stroke(pen.lineweight)} ${mark}`; const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + const plan = e.kind === "polyline" ? planOf(e, sides) : undefined; + if (e.kind === "polyline" && plan) { + return polylineToSvg(e, plan, mark, pen, look, matrix, room, sides); + } if (e.kind !== "text" && pen.dashes) { const d = dashedPath(e, pen.dashes, matrix, room, sides); // A pattern with a dot draws it as a round cap on a path of no length. @@ -1251,7 +1361,8 @@ function dashedPath( { lengths: dashes, total }: Dashes, matrix: Matrix | undefined, room: number, - known: WeakMap, + known: Known, + wide?: { readonly fills: string[]; readonly ends: string[] }, ): string | undefined { // Dashes that add up to no length would never reach the end of a stretch. if (!(total > 0)) return undefined; @@ -1259,7 +1370,7 @@ function dashedPath( const [mx, my] = matrix ? mapPoint(matrix, [px, py]) : [px, py]; return `${fmt(mx)} ${fmt(my)}`; }; - const out: string[] = []; + let out: string[] = []; let size = 0; /** Draws a dash from `from` to `to` along a stretch, and counts its characters. */ const dash = (draw: (from: number, to: number) => string, from: number, to: number): void => { @@ -1353,6 +1464,43 @@ function dashedPath( ok = straight(e.from, e.to); break; case "polyline": { + const plan = planOf(e, known); + if (plan) { + // A side the pattern is too fine for draws the whole polyline solid. + if (plan.longest / total > MAX_DASHES) return undefined; + const strokes = out; + for (const { side, arc, fit } of plan.parts) { + if (size > room) break; + if (!isWide(side)) { + if (!arc) straight(side.from, side.to); + else { + // An arc that turns clockwise is cut from its end, which fits the same dashes. + const from = arc.sweep > 0 ? arc.start : arc.start + arc.sweep; + round(arc.center, arc.radius, degrees(from), degrees(Math.abs(arc.sweep)), true); + } + continue; + } + // Each dash of a wide side is filled, square at both ends. + out = []; + cut(fit, (from, to) => bandPiece(side, arc, from / fit, to / fit, place, matrix), true); + if (out.length > 0) wide?.fills.push(out.join(" ")); + out = strokes; + // A straight side cut into dashes ends in the thinnest line across its end, and so does + // an arc whose width changes, at the end it reaches counterclockwise. + const tapered = side.startWidth !== side.endWidth; + if ((!arc || tapered) && fit >= total * (1 - 1e-9)) { + const t = !arc || arc.sweep > 0 ? 1 : 0; + const ended = bandPiece(side, arc, t, t, place, matrix).split(" L "); + const across = arc + ? `${ended[0]!} L ${ended[ended.length / 2]!}` + : `${ended[0]!} L ${ended[2]!}`; + size += across.length + 1; + wide?.ends.push(across); + } + } + ok = true; + break; + } const { points, ends, longest } = sidesOf(e.points, known); const [first, last] = [points[0], points.at(-1)]; // The side that closes it, NaN when there is none. @@ -1381,15 +1529,146 @@ function dashedPath( ok = round(e.center, e.radius, e.startAngle, sweep(e.startAngle, e.endAngle), true); break; } - return ok && out.length > 0 ? out.join(" ") : undefined; + return ok && (out.length > 0 || (wide?.fills.length ?? 0) > 0) ? out.join(" ") : undefined; +} + +/** + * The path of the filled piece of a side from `t0` to `t1` of the way along it, square to the + * side at both ends, where `matrix` puts it: its left edge from `t0` to `t1`, then its right edge + * back. The width changes along it from the side's start width to its end width. + */ +function bandPiece( + side: PolylineSide, + arc: SideArc | undefined, + t0: number, + t1: number, + place: (x: number, y: number) => string, + matrix: Matrix | undefined, +): string { + const half = (t: number): number => (side.startWidth + (side.endWidth - side.startWidth) * t) / 2; + if (!arc) { + const [dx, dy] = [side.to[0] - side.from[0], side.to[1] - side.from[1]]; + const length = Math.hypot(dx, dy); + const [nx, ny] = [-dy / length, dx / length]; + const edge = (t: number, h: number): string => + place(side.from[0] + dx * t + nx * h, side.from[1] + dy * t + ny * h); + return `M ${edge(t0, half(t0))} L ${edge(t1, half(t1))} L ${edge(t1, -half(t1))} L ${edge(t0, -half(t0))}`; + } + // The left of an arc that turns counterclockwise is toward its center. + const inward = arc.sweep > 0 ? 1 : -1; + const point = (t: number, h: number): string => { + const [x, y] = arcPoint(arc, t, arc.radius + h); + return place(x, y); + }; + if (side.startWidth === side.endWidth) { + const h = side.startWidth / 2; + /** The edge `offset` off the middle from `from` to `to` of the way along, in arcs of at most half a turn. */ + const edge = (offset: number, from: number, to: number): string => { + const round = rounded(Math.abs(arc.radius + offset), matrix); + // sweep-flag 1 is counterclockwise in local coordinates, which a mirroring matrix turns. + const ccw = arc.sweep > 0 === to > from; + const flag = ccw ? round.sweep : 1 - round.sweep; + const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + return Math.abs(arc.sweep * (to - from)) > Math.PI + ? `${a} ${point((from + to) / 2, offset)} ${a} ${point(to, offset)}` + : `${a} ${point(to, offset)}`; + }; + const [left, right] = [-inward * h, inward * h]; + return `M ${point(t0, left)} ${edge(left, t0, t1)} L ${point(t1, right)} ${edge(right, t1, t0)}`; + } + // An edge whose width changes along the arc is drawn in chords of at most 5 degrees. + const count = Math.max(2, Math.ceil((Math.abs(arc.sweep) * (t1 - t0)) / (Math.PI / 36))); + const along = (h: (t: number) => number, from: number, to: number): string[] => + Array.from({ length: count + 1 }, (_, k) => { + const t = from + ((to - from) * k) / count; + return point(t, h(t)); + }); + const left = along((t) => -inward * half(t), t0, t1); + const right = along((t) => inward * half(t), t1, t0); + return `M ${[...left, ...right].join(" L ")}`; +} + +/** + * A polyline with an arc or a width: each wide side filled, with its joins, and each run of + * sides of width 0 as one path, straight or along its arcs. With dashes, each dash of a wide side + * is filled on its own. Several elements are a group, which `mark` is on. + */ +function polylineToSvg( + e: Polyline, + plan: Plan, + mark: string, + pen: Pen, + look: Look, + matrix: Matrix | undefined, + room: number, + known: Known, +): string { + const place = (px: number, py: number): string => { + const [mx, my] = matrix ? mapPoint(matrix, [px, py]) : [px, py]; + return `${fmt(mx)} ${fmt(my)}`; + }; + const stroked = `stroke="${pen.color}"${look.stroke(pen.lineweight)}`; + const fill = `fill="${pen.color}" stroke="none"`; + const parts: string[] = []; + const dashed = pen.dashes + ? { fills: [] as string[], ends: [] as string[], d: undefined as string | undefined } + : undefined; + if (pen.dashes && dashed) dashed.d = dashedPath(e, pen.dashes, matrix, room, known, dashed); + if (dashed && (dashed.d !== undefined || dashed.fills.length > 0)) { + const cap = pen.dashes?.dot ? ` stroke-linecap="round"` : ""; + if (dashed.d) parts.push(``); + for (const d of dashed.fills) parts.push(``); + if (dashed.ends.length > 0) { + parts.push(``); + } + } else { + let run: string[] = []; + let used = 0; + const flush = (): void => { + if (run.length > 0) parts.push(``); + run = []; + }; + for (const { side, arc, band } of plan.parts) { + if (used > room) break; + if (band) { + flush(); + const d = band.arc + ? bandPiece(side, band.arc, 0, 1, place, matrix) + : `M ${[band.startLeft, band.endLeft, band.endRight, band.startRight].map(([x, y]) => place(x, y)).join(" L ")}`; + parts.push(``); + used += d.length; + continue; + } + if (run.length === 0) run.push(`M ${place(...side.from)}`); + if (!arc) run.push(`L ${place(...side.to)}`); + else { + const round = rounded(arc.radius, matrix); + const flag = arc.sweep > 0 ? round.sweep : 1 - round.sweep; + const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + // An arc of more than half a turn is drawn as two halves, so that no arc of the path + // ends where it starts, which SVG would draw as nothing. + if (Math.abs(arc.sweep) > Math.PI) run.push(`${a} ${place(...arcPoint(arc, 0.5))}`); + run.push(`${a} ${place(...side.to)}`); + } + used += run.at(-1)!.length; + } + flush(); + } + if (parts.length === 0) return ``; + if (parts.length === 1) return parts[0]!.replace(/\/>$/, ` ${mark}/>`); + return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; +} + +function degrees(radians: number): number { + return (radians * 180) / Math.PI; } /** * The sides of a list of points that have a length, read once into `known`. A side whose length * is 0, or not a number, draws no dash. */ -function sidesOf(list: unknown, known: WeakMap): Sides { - const found = typeof list === "object" && list !== null ? known.get(list) : undefined; +function sidesOf(list: unknown, known: Known): Sides { + const found = typeof list === "object" && list !== null ? known.sides.get(list) : undefined; if (found) return found; const points = filled(list) as readonly Point[]; const ends: number[] = []; @@ -1402,7 +1681,7 @@ function sidesOf(list: unknown, known: WeakMap): Sides { if (length > longest) longest = length; } const sides = { points, ends, longest }; - if (typeof list === "object" && list !== null) known.set(list, sides); + if (typeof list === "object" && list !== null) known.sides.set(list, sides); return sides; } diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 3ecef53..b447a0e 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -9,6 +9,7 @@ import { fromJSON, inspectText, lint, + polylineBox, toDXF, toSVG, type Block, @@ -263,7 +264,20 @@ function walkedExtents( box[3] = Math.max(box[3]!, py); }; if (e.kind === "line") [e.from, e.to].forEach((p) => add(...p)); - if (e.kind === "polyline") e.points.forEach((p) => add(...p)); + if (e.kind === "polyline") { + // Its arcs and its wide sides, by the corners of their box. + const [x0, y0, x1, y1] = polylineBox(e) ?? [Infinity, Infinity, -Infinity, -Infinity]; + if (x0 !== Infinity) { + for (const [x, y] of [ + [x0, y0], + [x1, y0], + [x1, y1], + [x0, y1], + ] as const) { + add(x, y); + } + } + } if (e.kind === "circle") { for (const [i, j] of [ [-1, -1], @@ -318,6 +332,7 @@ const holds = (outer: readonly number[], inner: readonly number[]): boolean => test("a block's box holds a walk's, and is a walk's where no insert is turned", () => { const random = seeded(7); + const curving = seeded(11); const pick = (items: readonly T[]): T => items[Math.floor(random() * items.length)]!; const point = (): Point => [random() * 100 - 50, random() * 100 - 50]; const none = [Infinity, Infinity, -Infinity, -Infinity]; @@ -346,6 +361,19 @@ test("a block's box holds a walk's, and is a walk's where no insert is turned", ])(), ); } + // A polyline with arcs and a width, from a stream of its own, which leaves the drawings + // above as they were. + if (curving() < 0.3) { + const at = (): Point => [curving() * 100 - 50, curving() * 100 - 50]; + entities.push({ + kind: "polyline", + layer: "A", + points: [at(), at(), at()], + closed: false, + bulges: [curving() * 4 - 2, curving() < 0.5 ? 0 : -3], + width: curving() < 0.5 ? 0 : curving() * 5, + }); + } for (let k = 0; i > 0 && k < 1 + Math.floor(random() * 3); k++) { entities.push({ kind: "insert", @@ -1875,6 +1903,42 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint (tree.blocks[0]!.entities as unknown as Entity[]).push(pointed); (drawing.entities as Entity[]).push(pointed); } + // A polyline of many sides that are arcs and wide, dashed or solid, with lists of bulges + // and widths that many polylines share: bulges of nearly a whole turn and of none, and + // widths far wider than the polyline. + if (random() < 0.3) { + (drawing.linetypes as Data[]).push({ name: "BANDS", description: "", pattern: [0.5, -0.25] }); + const count = 20_000; + const curved = { + kind: "polyline", + layer: "0", + linetype: pick(["BANDS", "ByLayer"]), + closed: random() < 0.5, + points: Array.from({ length: count }, (_, i) => [i % 7, i % 2 === 0 ? 0 : 3]), + bulges: Array.from({ length: count }, () => pick([0, 1, -1e9, 1e-7, 0.5])), + widths: Array.from({ length: count }, () => [pick([0, 0.1, 1e6]), random()]), + }; + if (!curved.closed) { + curved.bulges.pop(); + curved.widths.pop(); + } + (tree.blocks[0]!.entities as unknown as Data[]).push(curved); + // Polylines of their own that share its lists, some closed the other way, and one whose + // bulges are a list as long as a list can be, with nothing in it. + (drawing.entities as Data[]).push( + ...Array.from({ length: 50 }, (_, i) => ({ ...curved, closed: i % 3 === 0 })), + // oxlint-disable-next-line unicorn/no-new-array + { + ...curved, + points: [ + [0, 0], + [1, 1], + ], + bulges: new Array(2 ** 32 - 1), + widths: undefined, + }, + ); + } // A large block placed once. if (random() < 0.2) { blocks.push({ @@ -2184,3 +2248,29 @@ test("a chain of references ends however the drawings given share, circle or nes assert.ok(typeof drawn === "string" || drawn instanceof RangeError, String(drawn)); } }); + +test("polylines that share a long list of points, each with lists or a width of its own, are boxed in a bounded time", () => { + const points = Array.from({ length: 1_000_000 }, (_, i): Point => [i, i % 2]); + const bulges = Array.from({ length: 999_999 }, (_, i) => (i === 7 ? 0.5 : 0)); + const own = [ + (k: number) => ({ width: -k }), + () => ({ bulges: [] }), + () => ({ widths: [[0, 0] as const] }), + (k: number) => ({ bulges, width: -k }), + (k: number) => ({ bulges, closed: k % 2 === 0 }), + ]; + for (const fields of own) { + const entities = Array.from({ length: 2000 }, (_, k): Entity => ({ + kind: "polyline", + layer: "0", + points, + closed: false, + ...fields(k), + })); + // Telling whether each has an arc reads no point, and a list read again is paid for. + const found = settled(2000, () => + extents(entities, [], [], undefined, undefined, undefined, [], [], 20_000), + ); + assert.ok(Array.isArray(found) || found instanceof RangeError, String(found)); + } +}); diff --git a/test/polylines.test.ts b/test/polylines.test.ts new file mode 100644 index 0000000..942f27f --- /dev/null +++ b/test/polylines.test.ts @@ -0,0 +1,653 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + bulgeThrough, + checkIntent, + createDrawing, + DrawingError, + lint, + polylineBox, + readDXF, + toDXF, + toPDF, + toSVG, + type Drawing, + type Point, + type Polyline, +} from "../src/index.ts"; +import { polylineBands, polylineSides, sideArc } from "../src/polylines.ts"; +import { svgWithin } from "../src/svg.ts"; + +const near = (a: number, b: number, tolerance = 1e-9): boolean => Math.abs(a - b) <= tolerance; +const nearPoint = (a: Point, b: Point, tolerance = 1e-9): boolean => + near(a[0], b[0], tolerance) && near(a[1], b[1], tolerance); + +/** The polylines a drawing holds in model space. */ +const polylines = (drawing: Drawing): Polyline[] => + drawing.entities.filter((e): e is Polyline => e.kind === "polyline"); + +test("bulgeThrough gives the arc that passes through the middle point", () => { + // A positive bulge turns counterclockwise, which bulges to the right of the way it runs. + assert.ok(near(bulgeThrough([0, 0], [1, -1], [2, 0]), 1)); + assert.ok(near(bulgeThrough([0, 0], [1, 1], [2, 0]), -1)); + assert.equal(bulgeThrough([0, 0], [1, 0], [2, 0]), 0); + const through: Point = [3, 4]; + const arc = sideArc([0, 0], [7, 1], bulgeThrough([0, 0], through, [7, 1]))!; + assert.ok(near(Math.hypot(through[0] - arc.center[0], through[1] - arc.center[1]), arc.radius)); + assert.throws(() => bulgeThrough([0, 0], [3, 0], [2, 0]), /on one line/); + assert.throws(() => bulgeThrough([0, 0], [0, 0], [2, 0]), /three different points/); +}); + +test("a radius rounds each corner with an arc tangent to both sides, and refuses one too large", () => { + const d = createDrawing(); + d.polyline( + [ + [0, 0], + [10, 0], + [10, 10], + ], + false, + { radius: 2, width: 0.5 }, + ); + d.rect([20, 0], 6, 4, { radius: 2 }); + const [hook, rect] = polylines(d.build()); + const corners: Point[] = [ + [0, 0], + [8, 0], + [10, 2], + [10, 10], + ]; + assert.ok( + hook!.points.every((p, i) => nearPoint(p, corners[i]!)), + `${hook!.points}`, + ); + assert.ok(near(hook!.bulges![1]!, Math.tan(Math.PI / 8))); + assert.deepEqual([hook!.bulges![0], hook!.bulges![2], hook!.width], [0, 0, 0.5]); + // Sides of the rectangle that the arcs use up leave no straight side between them. + assert.equal(rect!.points.length, 6); + assert.equal(rect!.bulges!.filter((bulge) => bulge !== 0).length, 4); + assert.throws( + () => + d.polyline( + [ + [0, 0], + [1, 0], + [1, 1], + ], + false, + { radius: 2 }, + ), + /need 2 of the side between them, which is 1 long/, + ); + assert.throws( + () => + d.polyline( + [ + [0, 0], + [5, 0], + [5, 5], + ], + false, + { radius: 1, bulges: [0, 0] }, + ), + /takes no bulges or widths/, + ); +}); + +test("a cloud's arcs turn 110 degrees, bulge out of its outline, and stay beside their stretch", () => { + const square: Point[] = [ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + ]; + const d = createDrawing(); + d.cloud(square, { arc: 2.4 }); + d.cloud([...square].reverse(), { arc: 2.4 }); + const [counterclockwise, clockwise] = polylines(d.build()); + assert.equal(counterclockwise!.points.length, 16); + assert.ok(counterclockwise!.bulges!.every((b) => near(b, Math.tan((27.5 * Math.PI) / 180)))); + assert.ok(clockwise!.bulges!.every((b) => near(b, -Math.tan((27.5 * Math.PI) / 180)))); + for (const cloud of [counterclockwise!, clockwise!]) { + for (const side of polylineSides(cloud)) { + const arc = sideArc(side.from, side.to, side.bulge)!; + const [x, y] = [ + arc.center[0] + arc.radius * Math.cos(arc.start + arc.sweep / 2), + arc.center[1] + arc.radius * Math.sin(arc.start + arc.sweep / 2), + ]; + assert.ok(x < 0 || x > 10 || y < 0 || y > 10, `the arc from ${side.from} bulges out`); + } + } + assert.throws(() => d.cloud(square, { arc: 0.001 }), /would have 40000 arcs/); + assert.throws( + () => + d.cloud( + [ + [0, 0], + [1, 0], + [2, 0], + ], + { arc: 1 }, + ), + /must enclose an area/, + ); +}); + +test("a donut is two half circles as wide as its ring, and a dot has no hole", () => { + const d = createDrawing(); + d.donut([5, 5], 2, { inside: 1 }); + d.donut([0, 0], 0.5); + const [ring, dot] = polylines(d.build()); + assert.deepEqual(ring, { + kind: "polyline", + layer: "0", + points: [ + [4.25, 5], + [5.75, 5], + ], + closed: true, + bulges: [1, 1], + width: 0.5, + }); + assert.deepEqual( + [dot!.points, dot!.width], + [ + [ + [-0.125, 0], + [0.125, 0], + ], + 0.25, + ], + ); + assert.throws(() => d.donut([0, 0], 1, { inside: 1 }), /less across than the donut/); +}); + +test("lint reports a malformed bulge or width, and an R12 drawing that has one", () => { + const drawing = (fields: object, dxf: "R12" | "R2018" = "R2018"): Drawing => ({ + format: 0, + units: "in", + dxf, + layers: [{ name: "0", color: 7 }], + entities: [ + { + kind: "polyline", + layer: "0", + points: [ + [0, 0], + [10, 0], + [10, 5], + ], + closed: false, + ...fields, + } as Polyline, + ], + }); + const problems = (fields: object, dxf?: "R12" | "R2018") => + lint(drawing(fields, dxf)).map((d) => `${d.rule}: ${d.message}`); + assert.deepEqual(problems({ bulges: [0.5, 0, 1] }), [ + "geometry: polyline #0: its bulges must have one for each side, 2, and it has 3. A closed polyline has a side for each point, and an open one a side fewer", + ]); + assert.match(problems({ bulges: [0, Number.NaN] })[0]!, /its bulge 1: must be a finite number/); + assert.match(problems({ bulges: [0, 1e100] })[0]!, /its bulge 1: This value must be under 1e100/); + assert.match(problems({ width: -1 })[0]!, /its width: A polyline's width cannot be less than 0/); + assert.match( + problems({ + width: 1, + widths: [ + [1, 1], + [1, 1], + ], + })[0]!, + /give one or the other/, + ); + assert.match( + problems({ + widths: [ + [1, 1], + [0, -2], + ], + })[0]!, + /its widths 1: A polyline's width/, + ); + assert.match(problems({ widths: [[1, 1]] })[0]!, /its widths must have one for each side, 2/); + assert.deepEqual(problems({ bulges: [0, 0.5], width: 0.1, widths: undefined }), []); + assert.match(problems({ bulges: [0, 0.5] }, "R12")[0]!, /no arcs or widths of a polyline to R12/); +}); + +/** A polyline along +X to `[1, 0]` and on, turned `turn` degrees there, as `turn` gives an arc. */ +function turned(turn: number, arc: boolean): Polyline { + const radians = (degrees: number) => (degrees * Math.PI) / 180; + const chord = radians(arc ? turn + 15 : turn); + return { + kind: "polyline", + layer: "0", + points: [ + [0, 0], + [1, 0], + [1 + Math.cos(chord), Math.sin(chord)], + ], + closed: false, + width: 0.1, + ...(arc ? { bulges: [0, Math.tan(radians(30) / 4)] } : {}), + }; +} + +test("wide sides join as the leading CAD app plots them: a miter to 151.04 degrees, an arc's line to 75.96", () => { + const ends = (e: Polyline): Point[] => { + const [first] = polylineBands(polylineSides(e), e.closed); + return [first!.endLeft, first!.endRight]; + }; + // Square ends are a half width from the point, square to the first side. + const square: Point[] = [ + [1, 0.05], + [1, -0.05], + ]; + // A miter at a turn of 150 degrees and of 151.0, and none at 151.1. + const miter = ends(turned(150, false)); + assert.ok( + near(Math.hypot(miter[0]![0] - 1, miter[0]![1]), 0.05 / Math.cos((75 * Math.PI) / 180), 1e-5), + ); + assert.ok(!nearPoint(ends(turned(151, false))[1]!, square[1]!)); + assert.deepEqual(ends(turned(151.1, false)), square); + // A straight side meets an arc on the arc's line through the point at 75 and 105 degrees, and + // ends square at 76 and 104. + for (const turn of [75, 105]) { + const [left] = ends(turned(turn, true)); + // The bulge is taken as written, to 6 decimals. + assert.ok(near(left![0], 1 - 0.05 * Math.tan((turn * Math.PI) / 180), 1e-5), `${turn}`); + } + for (const turn of [76, 104]) assert.deepEqual(ends(turned(turn, true)), square, `${turn}`); +}); + +test("toDXF writes each side's bulge and widths, and readDXF gives them back", async () => { + const d = createDrawing(); + d.polyline( + [ + [0, 0], + [10, 0], + [10, 5], + ], + true, + { + bulges: [0, 0.5, -1], + widths: [ + [0, 1], + [1, 1], + [0.5, 0], + ], + }, + ); + d.donut([20, 0], 2); + const drawing = d.build(); + const dxf = toDXF(drawing); + const lines = dxf.split(/\r?\n/).map((line) => line.trim()); + const pairs: string[] = []; + for (let i = 0; i + 1 < lines.length; i += 2) pairs.push(`${lines[i]} ${lines[i + 1]}`); + const start = pairs.indexOf("0 LWPOLYLINE"); + const end = pairs.indexOf("0 LWPOLYLINE", start + 1); + assert.deepEqual(pairs.slice(pairs.indexOf("90 3", start), end), [ + "90 3", + "70 1", + "10 0", + "20 0", + "40 0", + "41 1", + "10 10", + "20 0", + "40 1", + "41 1", + "42 0.5", + "10 10", + "20 5", + "40 0.5", + "41 0", + "42 -1", + ]); + const read = await readDXF(dxf, { geometry: true }); + const [wide, donut] = read.model.entities ?? []; + assert.deepEqual(wide?.kind === "polyline" && [wide.bulges, wide.widths, wide.width], [ + [0, 0.5, -1], + [ + [0, 1], + [1, 1], + [0.5, 0], + ], + undefined, + ]); + assert.deepEqual(donut?.kind === "polyline" && [donut.bulges, donut.width], [[1, 1], 1]); +}); + +test("a polyline's box holds its arcs and its widths, and the picture fills a wide side", () => { + const half: Polyline = { + kind: "polyline", + layer: "0", + points: [ + [0, 0], + [2, 0], + ], + closed: false, + bulges: [1], + }; + const boxed = (e: Polyline, box: readonly number[]): boolean => + polylineBox(e)!.every((value, i) => near(value, box[i]!, 1e-12)); + assert.ok(boxed(half, [0, -1, 2, 0])); + assert.ok(boxed({ ...half, width: 0.5 }, [-0.25, -1.25, 2.25, 0])); + const d = createDrawing(); + d.polyline(half.points, false, { bulges: [1] }); + d.polyline( + [ + [0, 2], + [4, 2], + ], + false, + { width: 0.5 }, + ); + d.layout("SHEET", { paper: "ANSI B" }, () => d.donut([2, 2], 1)); + const drawing = d.build(); + const svg = toSVG(drawing); + assert.match(svg, / 0); +}); + +test("checkIntent does not take a footprint with an arc for its outline", () => { + const d = createDrawing(); + d.rect([0, 0], 100, 100, { id: "lot" }); + d.rect([30, 30], 40, 40, { id: "house", radius: 5 }); + const [warning] = checkIntent(d.build(), { + setbacks: [{ property: "lot", footprints: ["house"], distance: 10 }], + }); + assert.equal(warning?.rule, "intent-unchecked"); + assert.match(warning?.message ?? "", /a side that is an arc/); +}); + +test("each join reads the sides' own edges, so a short jog keeps both miters", () => { + const jog: Polyline = { + kind: "polyline", + layer: "0", + points: [ + [0, 0], + [10, 0], + [10, 1], + [20, 1], + ], + closed: false, + width: 2, + }; + const [, middle, last] = polylineBands(polylineSides(jog), false); + assert.deepEqual( + [middle!.startLeft, middle!.endLeft, last!.startLeft], + [ + [9, 1], + [9, 2], + [9, 2], + ], + ); +}); + +test("a radius that fits as written is taken, and a cloud that would cross its outline is not", () => { + const d = createDrawing(); + d.rect([0, 0], 0.9999999, 2, { radius: 0.5 }); + const notched: Point[] = [ + [0, 0], + [12, 0], + [12, 10], + [7, 10], + [7, 2], + [5, 2], + [5, 10], + [0, 10], + ]; + assert.throws(() => d.cloud(notched, { arc: 8 }), /reaches across the outline/); + d.cloud(notched, { arc: 1 }); +}); + +test("a dashed wide arc too long for its pattern draws the whole polyline solid", () => { + const d = createDrawing(); + d.linetype({ name: "FINE", description: "", pattern: [0.05, -0.05] }); + d.polyline( + [ + [0, 0], + [636, 0], + [650, 0], + ], + false, + { bulges: [1, 0], width: 2, linetype: "FINE" }, + ); + const svg = toSVG(d.build()); + // Two filled sides and no dash: the arc's outer edge holds more than 10,000 patterns. + assert.equal(svg.match(/fill="currentColor" stroke="none"/g)?.length, 2); +}); + +test("readDXF takes a point's bulge and widths in any order up to the next point", async () => { + const dxf = [ + "0", + "SECTION", + "2", + "ENTITIES", + "0", + "LWPOLYLINE", + "8", + "0", + "90", + "2", + "70", + "0", + "10", + "0", + "42", + "1", + "40", + "2", + "41", + "3", + "20", + "0", + "10", + "10", + "20", + "0", + "0", + "ENDSEC", + "0", + "EOF", + "", + ].join("\n"); + const [read] = (await readDXF(dxf, { geometry: true })).model.entities ?? []; + assert.deepEqual(read?.kind === "polyline" && [read.bulges, read.widths], [[1], [[2, 3]]]); +}); + +test("the box holds where a dash ends square, and an arc is worked out from its points as written", () => { + const joined: Polyline = { + kind: "polyline", + layer: "0", + points: [ + [0, 0], + [4, 0], + [0, -4], + ], + closed: false, + widths: [ + [0.5, 0.5], + [1, 1], + ], + }; + assert.ok(polylineBox(joined)![3] >= 0.5 * Math.SQRT1_2 - 1e-12); + // The second point is written as 0.000001, which makes the arc nearly a whole circle, 0.5 + // across. + const tiny: Polyline = { + kind: "polyline", + layer: "0", + points: [ + [0, 0], + [0.0000006, 0], + ], + closed: false, + bulges: [1e6], + }; + assert.ok(near(polylineBox(tiny)![1], -0.5, 1e-6)); +}); + +test("a cloud far from the origin is as a cloud at it, and arcs that meet keep one point as written", () => { + const d = createDrawing(); + const square = (at: number): Point[] => [ + [at, at], + [at + 1.1, at], + [at + 1.1, at + 1.1], + [at, at + 1.1], + ]; + d.cloud(square(0), { arc: 0.22 }); + d.cloud(square(10_000_000), { arc: 0.22 }); + const [near0, far] = polylines(d.build()); + assert.deepEqual(far!.bulges, near0!.bulges); + d.cloud( + [ + [0, 0], + [10, 1], + [10, 8], + [0, 8], + ], + { arc: 3 }, + ); + // A turned lot, at the origin and at a survey's coordinates, with several arcs on each side, + // whose points between its corners are written off its slanted sides. + for (const [x, y] of [ + [0, 0], + [512345.67, 2876543.21], + ]) { + const lot: Point[] = [ + [0, 0], + [37.3, 11.2], + [30.1, 40.7], + [-5.4, 28.9], + ]; + d.cloud( + lot.map(([px, py]): Point => [px + x!, py + y!]), + { arc: 3 }, + ); + } + // Arcs that meet exactly, or end a unit of the last decimal past each other as written, keep one + // point where they meet, wherever the slot is: no side runs back. + d.rect([0.0000004, 0], 1, 2, { radius: 0.5000002 }); + d.rect([897104.048729, 623613.643646], 16.362579, 2.210141, { radius: 2.210141 / 2 }); + for (const slot of polylines(d.build()).slice(-2)) { + assert.equal(slot.bulges!.filter((bulge) => bulge !== 0).length, 4); + assert.equal(slot.points.length, 6); + } + assert.throws(() => d.rect([0, 0], 1, 2, { radius: 0.6 }), /need 1.2 of the side/); + assert.throws(() => d.donut([0, 0], 1, { inside: 0.9999991 }), /too small for the 6 decimals/); + assert.throws(() => d.donut([0, 0], 0.0000024), /too small for the 6 decimals/); +}); + +test("toSVG pays for a long list that one polyline after another reads again", () => { + // One list of points that draws nothing, each side of no length, which two polylines share. + const points = Array.from({ length: 1000 }, (): Point => [1, 1]); + const wide = (width: number): Polyline => ({ + kind: "polyline", + layer: "0", + points, + closed: false, + width, + }); + const sheet = (entities: Polyline[]): Drawing => ({ + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [], + layouts: [{ name: "SHEET", paper: "ANSI B", viewports: [], entities }], + }); + assert.ok(svgWithin(sheet([wide(0.1)]), { layout: "SHEET" }, 20).length > 0); + assert.throws( + () => svgWithin(sheet([wide(0.1), wide(0.2)]), { layout: "SHEET" }, 20), + /stopped at entity #1 of layout "SHEET"/, + ); +}); + +test("an arc of more than half a turn is drawn in two halves, so none vanishes", () => { + const d = createDrawing(); + d.block("RING", {}, () => + d.polyline( + [ + [0, 0], + [0.000001, 0], + ], + false, + { bulges: [1e6], width: 0.1 }, + ), + ); + d.insert("RING", [0, 0], { scale: 0.1 }); + const ring = toSVG(d.build()) + .split("\n") + .find((line) => line.includes('fill="currentColor"'))!; + // Each edge of the band is two arcs. + assert.equal(ring.match(/ A /g)?.length, 4); +}); + +test("readDXF gives a 2D polyline's vertex with no widths the polyline's own", async () => { + const dxf = [ + ["0", "SECTION"], + ["2", "ENTITIES"], + ["0", "POLYLINE"], + ["8", "0"], + ["66", "1"], + ["70", "0"], + ["40", "0.5"], + ["41", "0.25"], + ["0", "VERTEX"], + ["8", "0"], + ["10", "0"], + ["20", "0"], + ["42", "1"], + ["0", "VERTEX"], + ["8", "0"], + ["10", "10"], + ["20", "0"], + ["40", "2"], + ["0", "VERTEX"], + ["8", "0"], + ["10", "20"], + ["20", "0"], + ["0", "SEQEND"], + ["0", "ENDSEC"], + ["0", "EOF"], + ] + .flat() + .join("\n"); + const [read] = (await readDXF(dxf, { geometry: true })).model.entities ?? []; + assert.deepEqual(read?.kind === "polyline" && [read.bulges, read.widths], [ + [1, 0], + [ + [0.5, 0.25], + [2, 0.25], + ], + ]); +}); + +test("lint stops where toDXF would, on polylines whose boxes pay for a list read again", () => { + const points = Array.from({ length: 11_000 }, (_, i): Point => [i, i % 2]); + const drawing: Drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: Array.from({ length: 100 }, (_, k): Polyline => ({ + kind: "polyline", + layer: "0", + points, + closed: false, + width: k + 1, + })), + }; + const capped = lint(drawing).filter((d) => d.rule === "check-capped"); + assert.equal(capped.length, 1); + assert.throws( + () => toDXF(drawing), + (thrown: unknown) => + thrown instanceof DrawingError && thrown.diagnostics.some((d) => d.rule === "check-capped"), + ); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index 3e00436..fab53d1 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -232,6 +232,24 @@ export function readProblems( ) { say(`${label}: points ${JSON.stringify(got.points).slice(0, 200)}`); } + { + // Each side's bulge and widths as written, where a list left out is all 0. + const sides = want.closed ? want.points.length : want.points.length - 1; + for (let i = 0; i < sides; i++) { + const bulge = [got.bulges?.[i] ?? 0, written(want.bulges?.[i] ?? 0)]; + const constant = [got.width ?? 0, written(want.width ?? 0)] as const; + const read = got.widths?.[i] ?? [constant[0], constant[0]]; + const drawn = want.widths?.[i] ?? [constant[1], constant[1]]; + if ( + !near(bulge[0]!, bulge[1]!) || + !near(read[0], written(drawn[0])) || + !near(read[1], written(drawn[1])) + ) { + say(`${label}: side ${i} has bulge ${bulge[0]} and widths ${read.join(", ")}`); + break; + } + } + } return; case "circle": if (!kind("circle") || got.kind !== "circle") return; diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index 2cb2a8d..5e03ec8 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -157,6 +157,8 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { 10, 11, 40, + 41, + 42, 66, 70, 71, @@ -182,6 +184,8 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { "INSERT", "ATTRIB", "SEQEND", + "POLYLINE", + "LWPOLYLINE", "VERTEX", "MTEXT", "DIMENSION", diff --git a/test/read.test.ts b/test/read.test.ts index 6bb160e..fc06c2f 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -671,7 +671,7 @@ test("readDXF decodes the DOS code pages, and keeps MTEXT heights to their scope assert.deepEqual(inlineHeights("\\H1e308x;\\H2x;\\H0.5;", 1), [1e308, 0.5]); }); -test("readDXF keeps a polyline with widths of 0, and counts one with widths", async () => { +test("readDXF reads the widths of a polyline's sides, and leaves out widths of 0", async () => { const polyline = (widths: [number, number | string][]) => [ [0, "LWPOLYLINE"] as const, [8, "0"] as const, @@ -699,8 +699,10 @@ test("readDXF keeps a polyline with widths of 0, and counts one with widths", as [0, "EOF"], ]), ); - assert.equal(read.blocks[0]?.entities.length, 1); - assert.deepEqual(plain(read.blocks[0]?.other), { "LWPOLYLINE with widths": 1 }); + const [zero, wide] = read.blocks[0]?.entities ?? []; + assert.equal(zero?.kind === "polyline" && zero.widths, undefined); + assert.deepEqual(wide?.kind === "polyline" && wide.widths, [[0, 0.5]]); + assert.deepEqual(plain(read.blocks[0]?.other), {}); }); test("checkDrawingRead takes no hole or getter for a value", async () => { diff --git a/test/rules.test.ts b/test/rules.test.ts index d0e4a84..2a7d7bf 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -18,6 +18,7 @@ import { type Drawing, type Entity, type Insert, + type Point, type Text, } from "../src/index.ts"; import sheet, { sitePlan, type Box } from "../examples/site-plan.ts"; @@ -1225,3 +1226,31 @@ test("the extents of a turned text reach its far corner", () => { assert.ok(Math.abs(top - (along + 2) / Math.SQRT2) < 1e-9); assert.ok(Math.abs(left + 2 / Math.SQRT2) < 1e-9); }); + +test("a polyline's width, radius and arcs, a cloud's arc and a donut's hole are checked twice", () => { + const d = createDrawing(); + const r12 = createDrawing({ dxf: "R12" }); + const corner: Point[] = [ + [0, 0], + [1, 0], + [1, 1], + ]; + // @ts-expect-error: a width cannot be less than 0. + assert.throws(() => d.polyline(corner, false, { width: -1 }), /width cannot be less than 0/); + // @ts-expect-error: a radius must be greater than 0. + assert.throws(() => d.polyline(corner, false, { radius: 0 }), /greater than 0/); + // @ts-expect-error: a radius must be greater than 0. + assert.throws(() => d.rect([0, 0], 2, 2, { radius: -1 }), /greater than 0/); + // @ts-expect-error: a cloud's arc must be greater than 0. + assert.throws(() => d.cloud(corner, { arc: 0 }), /greater than 0/); + // @ts-expect-error: a donut's hole cannot be less than 0 across. + assert.throws(() => d.donut([0, 0], 1, { inside: -0.5 }), /hole cannot be less than 0/); + // @ts-expect-error: R12 holds no arc of a polyline. + assert.throws(() => r12.polyline(corner, false, { bulges: [0, 1] }), /no arcs or widths/); + // @ts-expect-error: R12 holds no width. + assert.throws(() => r12.polyline(corner, false, { width: 1 }), /no arcs or widths/); + // @ts-expect-error: R12 holds no cloud, which is a polyline of arcs. + assert.throws(() => r12.cloud(corner, { arc: 1 }), /no arcs or widths/); + // @ts-expect-error: R12 holds no donut, which is a polyline of arcs. + assert.throws(() => r12.donut([0, 0], 1), /no arcs or widths/); +}); diff --git a/test/shape.test.ts b/test/shape.test.ts index ab80919..1000fe2 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -22,6 +22,7 @@ import { type Layout, type LeaderStyle, type Linetype, + type Polyline, type TextStyle, type Viewport, type Xref, @@ -31,8 +32,15 @@ import { timeLimit } from "./time-limit.ts"; const styled = { linetype: "DD", lineweight: 0.25 } as const; const justified = { style: "NOTES", align: "center", valign: "middle" } as const; -/** Each kind of entity with every field it can have: a field left out is a compile error. */ -const kinds: { readonly [K in Entity["kind"]]: Required> } = { +/** + * Each kind of entity with every field it can have: a field left out is a compile error. A + * polyline has a width or widths for each side, and `wide` has the other. + */ +const kinds: { + readonly [K in Entity["kind"]]: K extends "polyline" + ? Required> + : Required>; +} = { line: { kind: "line", layer: "WALL", from: [0, 0], to: [10, 0], id: "a", ...styled }, polyline: { kind: "polyline", @@ -43,6 +51,12 @@ const kinds: { readonly [K in Entity["kind"]]: Required> = { + kind: "polyline", + layer: "0", + points: kinds.polyline.points, + closed: false, + bulges: [0.25, 0], + width: 0.25, + id: "j", + ...styled, +}; + /** One of everything an R2018 drawing can hold, with every field of every object. */ const full: Required & { readonly linetypes: readonly [Required]; @@ -236,7 +262,11 @@ const full: Required & { }, ], xrefs: [{ name: "BASE", path: "base.dwg", attach: true }], - entities: [...Object.values(kinds), { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }], + entities: [ + ...Object.values(kinds), + { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }, + wide, + ], layouts: [ { name: "C-101", @@ -270,7 +300,15 @@ const r12: Drawing = { layers: [{ name: "0", color: 7 }], entities: [ { kind: "line", layer: "0", from: [0, 0], to: [10, 0], id: "a" }, - { ...kinds.polyline, linetype: "ByLayer", lineweight: "ByLayer" }, + { + kind: "polyline", + layer: "0", + points: kinds.polyline.points, + closed: true, + id: "b", + linetype: "ByLayer", + lineweight: "ByLayer", + }, { kind: "circle", layer: "0", center: [5, 5], radius: 2 }, { kind: "arc", layer: "0", center: [5, 5], radius: 3, startAngle: 0, endAngle: 90 }, { kind: "text", layer: "0", at: [0, 4], height: 1, rotation: 0, value: "T-0" }, diff --git a/test/standard-lint.test.ts b/test/standard-lint.test.ts index 825959a..cb14eef 100644 --- a/test/standard-lint.test.ts +++ b/test/standard-lint.test.ts @@ -714,7 +714,12 @@ test("the checks of a standard stay bounded on any data, and never throw", () => } // A field of something in the drawing: a long name, a value of the wrong type, or a field // nobody knows that is large written out. - const records: Data[] = [drawing, sheetLayout, ...lists.flatMap(([o, f]) => o[f] as Data[])]; + // A list the sheet does not have, such as its xrefs, holds no record. + const records: Data[] = [ + drawing, + sheetLayout, + ...lists.flatMap(([o, f]) => (o[f] as Data[] | undefined) ?? []), + ]; for (const e of [...sheetLayout.entities, ...(drawing.entities as Data[])]) { if (e.attributes) records.push((e.attributes = { ...(e.attributes as Data) })); } From 462fb94bfd76bcd45b9ac2529a3801736529a53b Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 19 Nov 2026 12:18:44 -0500 Subject: [PATCH 03/35] readDXF leaves out what a file marks invisible, so a dynamic block reads as the state it shows `readDXF` now leaves out of a block's and a space's `entities` any entity the file marks invisible (group 60), and counts it under `other` as `invisible`. A dynamic block's definition, and each anonymous `*U` block that holds one of its states, keep the entities of every state. The entities of the states a block doesn't show are marked invisible. So an insert of a dynamic block now reads as the state it shows, where it used to read as every state drawn over each other. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++ docs/reading.md | 17 +++++++--- src/read/dxf.ts | 26 ++++++++++++---- src/read/entities.ts | 3 +- test/read.test.ts | 74 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 114 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34a89ab..85de3fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- `readDXF` leaves out of a block's and a space's `entities` an entity the file marks invisible, + group 60, and counts it under `other` as `invisible`. A dynamic block's definition and each `*U` + block that holds one of its states keep the entities of every state, with those of the states + it does not show marked invisible, so an insert of one now reads as the state it shows. An + attribute or attribute definition marked so is `invisible`, as one whose own flag hides it is, + and a space counts such a definition under `other`. - Attachments, and the xrefs of a referenced drawing in the preview and the plot. `d.xref(name, path, { attach: true })` writes an attachment, which a drawing that references this one draws too, where an xref is an overlay by default, and `Xref` holds `attach`. `toSVG` diff --git a/docs/reading.md b/docs/reading.md index cb7c078..4020b79 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -56,8 +56,14 @@ states and keeps each object's handle, and it keeps going past what it does not in. Two entries of one name are both kept, in the order of the file. - `blocks`: each with its base point, its attribute definitions and its entities, below. What else a block draws is counted under `other` by kind, such as `HATCH` or `LWPOLYLINE in 3D`, - and so is what stands in another plane than the block's. The blocks keep `BLOCK_ITEMS`, - 400,000 items in all, counted as below, and count what comes past that under `past the limit`. + and so is what stands in another plane than the block's. An entity the file marks invisible, + group 60, draws nothing and is counted under `invisible`: a dynamic block's states each keep + the entities of every state, with those of the others marked so, and an insert reads as the + block it names: the definition, for the state the definition shows, or a `*U` block for + another, which draws the state it shows. An attribute or attribute definition hidden that way + is `invisible`, as one whose own flag hides it is, and a space counts such a definition under + `other`. The blocks keep `BLOCK_ITEMS`, 400,000 items in all, counted as below, and count what + comes past that under `past the limit`. The pictures the leading CAD app makes for dimensions, the blocks named `*D` and a number, are kept by a read with `geometry` alone. - `xrefs`: each with its name, its path as the file holds it, and whether it is an overlay. @@ -136,9 +142,10 @@ seen from below reads backward. ### What a read keeps What the spaces draw counts against one budget, `GEOMETRY_ITEMS`, 400,000 items, and the blocks -against `BLOCK_ITEMS`. An entity is one item, and each of its points, each attribute and tag, and -each 32 characters of its names and its text one more. What comes past a budget is counted -under `past the limit` in its space's or block's `other`. A read of a DXF of more than 500 MB that +against `BLOCK_ITEMS`. An entity is one item, and each of its points, each bulge and pair of +widths of a polyline's sides, each attribute and tag, and each 32 characters of its names and its +text one more. What comes past a budget is counted under `past the limit` in its space's or +block's `other`. A read of a DXF of more than 500 MB that reaches `GEOMETRY_ITEMS` and every census list answers in about 110 MB of JSON, within the 128 MB the command takes. diff --git a/src/read/dxf.ts b/src/read/dxf.ts index cc883c8..b2563da 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -174,7 +174,9 @@ const ALL: ReadonlySet = new Set(); const NOTHING: ReadonlySet = new Set(); /** What the census of a space reads of an entity it only counts. */ // 102 too, so that the owner is told from the handles of an application's group. -const CENSUS: ReadonlySet = new Set([5, 6, 8, 62, 67, 102, 330, 370, 420]); +const CENSUS: ReadonlySet = new Set([5, 6, 8, 60, 62, 67, 102, 330, 370, 420]); +/** What a block reads of an entity of a kind it counts: whether it shows. */ +const VISIBILITY: ReadonlySet = new Set([60]); /** The kinds a block's definition reads whole, and a space's with `geometry`. */ const BLOCK_READS = new Set([ "ARC", @@ -426,6 +428,12 @@ interface PolylineOwner { /** The longest name a map of the file's names is keyed by: the most a DXF string holds. */ const LONGEST_NAME = 2049; +/** + * True for an entity the file marks invisible, group 60, which draws nothing. A dynamic block's + * record holds the entities of every state, with those of the states it does not show marked so. + */ +const hidden = (r: Rec): boolean => num(r, 60) === 1; + class DxfReader { #section = ""; #variable = ""; @@ -574,7 +582,7 @@ class DxfReader { case "BLOCKS": if (type === "BLOCK" || type === "ENDBLK") return ALL; if (this.#inDimensionPicture) return NOTHING; - if (this.#block) return BLOCK_READS.has(type) ? ALL : NOTHING; + if (this.#block) return BLOCK_READS.has(type) ? ALL : VISIBILITY; return inSpace(); case "ENTITIES": return inSpace(); @@ -877,7 +885,10 @@ class DxfReader { // A space lists an insert in any plane, as its census does; a block keeps it flat. const place = face !== 0 || !block; let keep = target !== undefined; - if (target && face === 0) { + if (target && hidden(r)) { + add(target.other, "invisible"); + keep = false; + } else if (target && face === 0) { add(target.other, "INSERT in 3D"); keep = false; } else if (target && ((num(r, 70) ?? 1) > 1 || (num(r, 71) ?? 1) > 1)) { @@ -903,7 +914,8 @@ class DxfReader { return; } case "ATTDEF": { - if (!block) return; + // A space keeps no attribute definition, but counts one that does not show. + if (!block) return target && hidden(r) ? add(target.other, "invisible") : undefined; if (face === 0) { add(block.other, "ATTDEF in 3D"); return; @@ -930,7 +942,7 @@ class DxfReader { ...(prompt !== undefined && { prompt }), default: value, layer, - invisible: (flags & 1) !== 0, + invisible: (flags & 1) !== 0 || hidden(r), constant: (flags & 2) !== 0, }; if (pending) this.#starts.push({ ...pending, placement: definition }); @@ -951,6 +963,7 @@ class DxfReader { } } if (!target) return; + if (hidden(r)) return add(target.other, "invisible"); const reading = readingOf(r, baseOf(r, layer, handle), face, this.#later, this.#r12); const kept = reading !== undefined && "entity" in reading && this.#kept(target, reading.entity); for (const pending of this.#settle(kept, target)) this.#starts.push(pending); @@ -1132,7 +1145,8 @@ class DxfReader { const r = owner.rec; const flags = num(r, 70) ?? 0; // 8 is a 3D polyline, 16 a mesh and 64 a face mesh. - if ((flags & (8 | 16 | 64)) !== 0 || owner.face === 0) add(target.other, "POLYLINE in 3D"); + if (hidden(r)) add(target.other, "invisible"); + else if ((flags & (8 | 16 | 64)) !== 0 || owner.face === 0) add(target.other, "POLYLINE in 3D"); else if (owner.broken) add(this.unread.malformed, "POLYLINE with a number that is not finite"); else if (owner.over) add(target.other, "past the limit"); else { diff --git a/src/read/entities.ts b/src/read/entities.ts index ff75e2a..f09b4e8 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -433,7 +433,8 @@ export function attributeOf( ...placement, tag: textTwice(first(r, 2) ?? ""), value, - ...(((num(r, 70) ?? 0) & 1) !== 0 && { invisible: true }), + // Its own flag, group 70, or the entity's, group 60, as a dynamic block's state hides it. + ...((((num(r, 70) ?? 0) & 1) !== 0 || num(r, 60) === 1) && { invisible: true }), }; if (pending) later.start({ ...pending, placement: attribute }); return attribute; diff --git a/test/read.test.ts b/test/read.test.ts index fc06c2f..42ef4dd 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -705,6 +705,80 @@ test("readDXF reads the widths of a polyline's sides, and leaves out widths of 0 assert.deepEqual(plain(read.blocks[0]?.other), {}); }); +test("readDXF counts an entity the file marks invisible, in a block and in a space, and hides such an attribute", async () => { + const hidden = (type: string): (readonly [number, string | number])[] => [ + [0, type], + [8, "0"], + [60, 1], + [10, 0], + [20, 0], + [11, 1], + [21, 0], + ]; + const read = await readDXF( + dxf([ + ...section( + "BLOCKS", + [ + [0, "BLOCK"], + [2, "B"], + ], + hidden("LINE"), + hidden("HATCH"), + [[0, "ENDBLK"]], + ), + ...section( + "ENTITIES", + hidden("LINE"), + [ + [0, "INSERT"], + [8, "0"], + [60, 1], + [2, "B"], + ], + [ + [0, "INSERT"], + [8, "0"], + [2, "B"], + [66, 1], + ], + [ + [0, "ATTRIB"], + [8, "0"], + [60, 1], + [10, 0], + [20, 0], + [40, 1], + [1, "V"], + [2, "TAG"], + [70, 0], + ], + [[0, "SEQEND"]], + [ + [0, "ATTDEF"], + [8, "0"], + [60, 1], + [10, 0], + [20, 0], + [40, 1], + [1, ""], + [2, "TAG"], + [70, 0], + ], + ), + [0, "EOF"], + ]), + { geometry: true }, + ); + assert.deepEqual(read.blocks[0]?.entities, []); + assert.deepEqual(plain(read.blocks[0]?.other), { invisible: 2 }); + const [insert] = read.model.entities ?? []; + assert.equal(insert?.kind === "insert" && insert.attributes?.[0]?.invisible, true); + assert.equal(read.model.entities?.length, 1); + assert.deepEqual(plain(read.model.other), { invisible: 3 }); + assert.deepEqual(plain(read.model.census.layers["0"]?.kinds), { LINE: 1, INSERT: 2, ATTDEF: 1 }); +}); + test("checkDrawingRead takes no hole or getter for a value", async () => { const read = (await readDXF(fieldsFile())) as unknown as Record; const text = (read.model as { census: { texts: Record[] } }).census.texts[0]!; From ef5b4d33cf28a47a66ab63e7e717bbecb8b30316 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 19 Nov 2026 15:24:58 -0500 Subject: [PATCH 04/35] Paragraph text: one note that wraps to a width, with underline, bold and stacked fractions Paragraph text: `d.paragraph(value, options)` draws one note that wraps to a width and is held as one `MTEXT`, which a CAD user edits as one. `at` places its box by the corner or side `align` and `valign` name, the upper left by default, and it takes a `height` or, under a standard, a `role`, a `style`, a `rotation`, a `lineSpacing` factor from 0.25 to 4 and a `lineSpacingStyle` of `"at-least"` or `"exactly"`. A line feed in the value starts a new paragraph. The value holds an `MTEXT`'s own inline codes, and `underline`, `bold`, `stack`, `superscript`, `subscript` and `plain` write them: underline, strike-through, bold in a TrueType font, stacked fractions, slash stacks and tolerances, superscript and subscript, `%%d`, `%%p`, `%%c`, `\U+XXXX` and the escapes. `lint`, the builder and the value's type refuse a brace never closed, a code tsdraft does not lay out yet (a tab, a list's indents, columns, a change of height or an overline), a stacked part in lower case, a stack in underlined text, `%%c` in an SHX font, a font that is not one of `FONTS`, italic, bold in an SHX font, and a paragraph in an R12 drawing. `layoutParagraph` and `measureParagraph` lay a paragraph out as the leading CAD app does. Each line is set by the ink of its first and last letters and broken only at a space, where the next word's ink would pass the width. Lines are spaced by what their letters and stacks reach, and each run, bold face, underline, bar and stack part is drawn where that app draws it. The extents, `toSVG`, `toPDF` and `inspectText` take a paragraph's lines and box from them. `FONT_METRICS` holds each character's ink and each TrueType font's bold face, and `FONTS` names each bold file, which `toPDF` takes under the font's name and ` Bold`. `tsdraft render` and `tsdraft dev` find the bold files as they find the regular ones. `readDXF` reads an `MTEXT`'s line spacing and its group 50 in degrees, and `layoutMtext` lays a read one out. The example sheet's general notes are paragraphs. `toSVG` and `toPDF` now draw every text in a TrueType font from its first point at its characters' advances, as it plots, where they stretched it to its ink before; the ink still sets where a text sits and its box. A paragraph is laid out from its numbers as written. [docs/paragraphs.md](docs/paragraphs.md) describes it all. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 25 +- CHANGELOG.md | 41 + GUIDE.md | 48 +- README.md | 24 +- cli/AGENTS.md | 5 +- cli/src/fonts.ts | 97 +- cli/src/png-child.ts | 19 +- cli/test/png.test.ts | 56 +- docs/assets/site-plan-dark.svg | 138 +- docs/assets/site-plan-light.svg | 138 +- docs/command.md | 3 + docs/format.md | 8 + docs/paragraphs.md | 226 ++ docs/plotting.md | 4 + docs/reading.md | 7 +- docs/rules.md | 10 + docs/text.md | 9 +- examples/site-plan.ts | 38 +- scripts/readme-drawing.ts | 7 +- src/drawing.ts | 215 +- src/dxf-r2018.ts | 62 +- src/extents.ts | 14 +- src/font-metrics.ts | 3494 +++++++++++++++++++++++++++++++ src/fonts.ts | 32 +- src/format.ts | 11 + src/index.ts | 43 +- src/inspect.ts | 53 +- src/lint.ts | 66 +- src/measure.ts | 49 +- src/paragraph-codes.ts | 543 +++++ src/paragraphs.ts | 1169 +++++++++++ src/pdf.ts | 109 +- src/read/check.ts | 2 + src/read/entities.ts | 7 +- src/read/model.ts | 6 +- src/read/mtext.ts | 64 + src/rules.ts | 444 ++++ src/shape.ts | 12 + src/standard/define.ts | 4 +- src/standard/lint.ts | 95 +- src/svg.ts | 173 +- test/bounded.test.ts | 150 ++ test/format.test.ts | 2 +- test/measure.test.ts | 25 +- test/paragraphs.test.ts | 470 +++++ test/read-agreement.ts | 28 + test/read.test.ts | 12 +- test/rules.test.ts | 79 + test/shape.test.ts | 18 +- 49 files changed, 8014 insertions(+), 340 deletions(-) create mode 100644 docs/paragraphs.md create mode 100644 src/paragraph-codes.ts create mode 100644 src/paragraphs.ts create mode 100644 src/read/mtext.ts create mode 100644 test/paragraphs.test.ts diff --git a/AGENTS.md b/AGENTS.md index aaa5535..cfdc0d0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -162,9 +162,23 @@ anywhere else. `src/font-metrics.ts` holds, for each font of `FONTS` and each character from U+0020 to U+007E and U+00A0 to U+00FF, the numbers of a text of height 1. It is data: never edit a number by hand, and keep its header to what the numbers are. -- `toSVG` draws a text from where `measureText` starts it, with no `text-anchor`, and holds - it to its length with `textLength` and `lengthAdjust="spacingAndGlyphs"`, so every renderer - draws it as long as it plots in whatever typeface it has. `xml:space="preserve"` keeps its +- `src/paragraphs.ts` is the one layout of a paragraph, `layoutParagraph` and `measureParagraph`: + where each line and each run sits, its strokes and its box, from the font tables' advances and + their paragraph columns, each letter's ink and each bold face. + The extents, `toSVG`, `inspectText`, the writers' boxes and `src/read/mtext.ts` all take a + paragraph from it, and every rule of where a line goes is in the block at its top. Its value is + read only by `parseParagraph` in `src/paragraph-codes.ts`, in one pass with a stack of its own + and at most `PARAGRAPH_NESTING` formats, and `ParagraphValue` in `src/rules.ts` is the same + grammar as a type, which gives up past a fixed number of steps and leaves the rest to the + runtime check. Two rules only the runtime check holds: `%%c` in the style's font, which the type + does not know, and a character above U+FFFF, since TypeScript never splits the surrogate pair + that holds one. A code it does not lay out is refused by `lint`, never drawn as a guess. +- `toSVG` draws a text with no `text-anchor`, and holds it to a length with `textLength` and + `lengthAdjust="spacingAndGlyphs"`, so every renderer draws it as long in whatever typeface it + has. A text or a paragraph's run in a TrueType font is drawn from its first point and held to + its characters' advances, which the leading CAD app's PDF sets at `100 Tz`; one in an SHX + font, which plots as strokes, from where `measureText` starts it and held to the length it + plots. `xml:space="preserve"` keeps its spaces. `data-height` follows `font-family` directly, and `font-size` comes before both: the command finds the three together to size a text for the typeface it draws. - `inspectText` in `src/inspect.ts` warns about text as it plots. It is not `lint`: its rules @@ -364,7 +378,10 @@ seed. - The writers print numbers with 6 decimals. `written` in `src/format.ts` is that rounding, and `lint` judges sizes, points and arc angles as written. A new - check on a number must do the same. + check on a number must do the same. One exception: a paragraph's line-spacing factor is judged + as given, from 0.25 to 4, as its type holds a literal, which cannot round. Both ends have 6 + decimals, so no factor in the range rounds out of it when written, and the type and the runtime + check agree. - The leading CAD app reads two exponent digits from DXF, so no number may be written as 1e100 or more. `lint` refuses those in a drawing. A number a writer works out for itself, such as an extent, must go through `readable` in `src/format.ts`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 85de3fa..ebdf93f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,47 @@ it does not show marked invisible, so an insert of one now reads as the state it shows. An attribute or attribute definition marked so is `invisible`, as one whose own flag hides it is, and a space counts such a definition under `other`. +- Paragraph text, in R2018 drawings: `d.paragraph(value, options)` draws one text whose lines wrap + at `width` and break at each line feed, held as an `MTEXT` that a CAD user edits as one. Its + box is placed by `at`, the point `align` and `valign` name, its upper left corner by default, + and it takes a `height`, a `rotation`, a `style`, a `lineSpacing` factor from 0.25 to 4 and a + `lineSpacingStyle`, and under a standard a `role` and a `view`, as a text does. Its value holds + the inline codes of an `MTEXT`: underline, strike-through, bold in a TrueType font, stacked + fractions, slash stacks and tolerances, a superscript and a subscript, `%%d`, `%%p`, `%%c`, + `\U+XXXX` and the escapes; `underline`, `bold`, `stack`, `superscript`, `subscript` and `plain` + write them, and `parseParagraph` reads them. `lint` and the builder refuse a value with a brace + never closed, a code it does not know or does not lay out yet, such as a tab, a list's indents, + columns, a change of height or an overline, a stacked part of lower-case letters, a stack in + underlined text, a font that is not one of `FONTS`, italic, bold in an SHX font, a font option + other than `b0`, `b1`, `i0`, and `c` or `p` with digits, or one given twice, and a paragraph in + an R12 drawing; a literal value with one of these is a compile error. They also refuse `%%c` in + an SHX font, which draws a diameter sign of its own that is not laid out yet; a literal value's + type refuses it in a font a `\f` or `\F` code sets, and leaves a character above U+FFFF to them. + `layoutParagraph` and `measureParagraph` lay a paragraph out as the leading CAD app does: each + line set by the ink of its first and last letters, broken where the next word's ink would pass + the width, spaced by what its letters and stacks reach, with each run, bold face, underline, + bar and stack part where that app draws it, from the font tables' new columns and the numbers as + the writers write them. The extents, `toSVG`, `toPDF` and `inspectText` take a paragraph's lines + and its box from them, and a long value many paragraphs share is laid out once in each of its + settings. A paragraph's rotation is taken within a turn and to 6 decimals, and + `paragraphDirection` gives the one direction both writers write and its layout is placed by. + `FONTS` names + each TrueType font's bold file, `capHeightOf` gives the height of a face's capital `A`, `toPDF` + sets a bold run in the file `fonts` gives under the font's name and ` Bold`, and `tsdraft render` + and `tsdraft dev` find the bold files as they find the regular ones. `readDXF` reads an + `MTEXT`'s line spacing as `lineSpacing` and `lineSpacingStyle`, and its group 50 in degrees, and + `layoutMtext` and `measureMtext` lay a read one out. [docs/paragraphs.md](docs/paragraphs.md) + describes them. +- `toSVG` draws a text in a TrueType font from its first point, held to its characters' advances, + and `toPDF` sets it at 100 `Tz` there, as the leading CAD app plots it: a text that ended in a + letter whose ink passes its advance, as an `f` does, was stretched to its ink. `layoutText` + gives the advances alone as `advances`. +- `measureText` turns a text by its rotation as the writers write it, to 6 decimals, so a tall + text turned by less than a millionth of a degree is measured as the file draws it. +- `FONT_METRICS` holds, for each character of each font, where its ink starts and ends, how far + it reaches above and below the baseline, the room each font leaves after a stack, and for each + TrueType font its bold face's own numbers. +- The example sheet's general notes are paragraphs that wrap at the width of its column of notes. - Attachments, and the xrefs of a referenced drawing in the preview and the plot. `d.xref(name, path, { attach: true })` writes an attachment, which a drawing that references this one draws too, where an xref is an overlay by default, and `Xref` holds `attach`. `toSVG` diff --git a/GUIDE.md b/GUIDE.md index 9799a5a..a4290f3 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -223,24 +223,32 @@ measureText({ value: "GENERAL NOTES", height: 0.125, font: "Arial" }).length; // `font` is the font of the text's style, and `txt.shx`, the font of `Standard`, when left out. A capital of `txt.shx` takes a whole text height of the line, far more than most screen fonts -do, so a note sized by eye runs long. Pass the style's `widthFactor` too when it has one. -Break a note into lines with it, and check that a value fits its cell before you draw it: +do, so a note sized by eye runs long. Pass the style's `widthFactor` too when it has one, and +check that a value fits its cell before you draw it. + +A note of more than one line is a paragraph, which wraps at its width and which a drafter edits +as one. Never break a note into texts of one line: ```ts -/** Breaks a sentence into lines that plot no longer than `width`. */ -function wrap(sentence: string, height: number, width: number): string[] { - const lines: string[] = []; - for (const word of sentence.split(" ")) { - const longer = lines.length > 0 ? `${lines.at(-1)} ${word}` : word; - const fits = measureText({ value: longer, height }).length <= width; - if (lines.length > 0 && fits) lines[lines.length - 1] = longer; - else lines.push(word); - } - return lines; -} +import { layoutParagraph, underline } from "tsdraft"; + +d.paragraph(`1. ${underline("VERIFY")} ALL DIMENSIONS IN THE FIELD.\n2. DO NOT SCALE.`, { + at: [1, 20], // the upper left corner of its box + width: 4, + height: 0.1, +}); +layoutParagraph({ value: "...", height: 0.1, width: 4 }).lines.length; // how many lines it takes ``` -Space lines one and a half text heights apart or more. Given `at`, `align`, `valign` and +A line feed starts a new paragraph. `measureParagraph` gives its lines and its box, from the +widths `measureText` uses, and `inspectText` checks each line as a text. `underline`, `bold`, +`stack`, `superscript` and `subscript` write the codes for what they name, and `plain(text)` +escapes text from elsewhere. `lint` refuses a code tsdraft does not lay out, such as a tab, a +list's indents or a change of height, and names it. +[docs/paragraphs.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/paragraphs.md) +has the codes. + +Space the lines of a column of texts one and a half text heights apart or more. Given `at`, `align`, `valign` and `rotation` as well, `measureText` returns `corners`, the box the text's capitals fill, which is the box the `text-` warnings and their `bounds` use. A character outside Latin-1 is measured as a `?`, and the result then has `approximate: true`. @@ -285,8 +293,9 @@ ARCH D layout, 36 by 24 inches, its border, a title block whose fields are attri a legend, the view's title and a graphic scale. Start a new drawing from it. It is not in the npm package. Copy it and change its import string `"../src/index.ts"` to `"tsdraft"`. -Its parameters come first and every position is worked out from them. Its columns and line -breaks are laid out with `measureText`. Its symbols are blocks. +Its parameters come first and every position is worked out from them. Its columns are laid +out with `measureText`, and each general note is a paragraph that wraps at the width of the +column of notes. Its symbols are blocks. It is drawn to a standard of its own, which extends `BUILT_IN_STANDARD` with the layers `V-TREE` and `C-ANNO-REVS`, as the section above shows, and a leader style. A text names a `role` of the standard, @@ -590,10 +599,9 @@ writeFileSync("plan.dxf", toDXF(drawing)); viewport is a locked rectangle that shows every layer at one scale. - A paper outside the list in the section on layouts, a paper in portrait, and a page setup for another plotter. -- Multiline text, but a leader's note. A text is a single line: break a note into lines with - `measureText`. A text - takes a text style with a font, and `align` and `valign` to justify it to its point, as the - example sheet does. +- Lists with hanging indents, tab stops and columns in a paragraph, and the codes that change + the height, width, slant, spacing or color of characters inside one. Number a list with a + text beside each note's paragraph, as the example sheet does. - Ellipses and splines. - A color on a single entity. Color comes from the layer. - DWG files. tsdraft writes DXF. diff --git a/README.md b/README.md index ff7c8c2..624e7da 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,23 @@ d.donut([10, 10], 0.5); // a filled dot `bulges` makes any side an arc, and `widths` gives each side a width at each end. [Polylines](docs/polylines.md) has the rest. +A paragraph is one text whose lines wrap at a width, which a CAD user edits as one. A line feed +starts a new paragraph, and small helpers write the codes for an underline, bold, a stacked +fraction and a superscript: + +```ts +import { stack, underline } from "tsdraft"; + +d.paragraph(`GENERAL NOTES\n1. ${underline("VERIFY")} ALL DIMENSIONS. GAP 3${stack("1", "2")}"`, { + at: [1, 20], // the upper left corner of its box + width: 4, + height: 0.1, +}); +``` + +`measureParagraph` gives its lines and its box. [Paragraphs](docs/paragraphs.md) has the codes +it takes and what it refuses. + A dimension measures between two points and writes what it measures. In the file it is a dimension, which a CAD program measures again when its points move, and a dimension style says how it is drawn: @@ -224,14 +241,14 @@ included, can break code written for the one before. [CHANGELOG.md](CHANGELOG.md starts each breaking change with `Breaking:`. It draws layers, lines, polylines with arcs and widths, rectangles, revision clouds, donuts, -circles, arcs and single-line text, with +circles, arcs, single-line text and paragraph text that wraps to a width, with linetypes and lineweights, text styles and justification, blocks with attributes and inserts of them, references to DWG files as xrefs, linear and aligned dimensions in decimal units or feet and inches, leaders, layouts with a page setup and viewports, which can freeze their own layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one +It does not yet have lists, tab stops, columns or overlines in paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit @@ -283,6 +300,7 @@ the drawing's version, and `toDXF(drawing, { version })` writes another one. | Drawing units | Stored in `$INSUNITS`. | Not stored. Set them in CAD with `UNITS`. | | Polylines | `LWPOLYLINE` | `POLYLINE` with `VERTEX` records | | Polyline arcs and widths | Yes | No | +| Paragraph text | `MTEXT` | No | | Text | UTF-8 | ASCII, with `\U+XXXX` escapes for other characters | | Layer names | Up to 255 characters, except those in [the rules](docs/rules.md#errors) | Up to 31 letters, digits, `$`, `-` and `_` | | Linetypes, lineweights | Yes | No: only `Continuous`, and no lineweights | @@ -332,6 +350,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version block, names, handles and what the preview draws. - [Polylines](docs/polylines.md) covers arcs by their bulge, rounded corners, revision clouds, widths and donuts, how a wide polyline plots, and what `lint` refuses of them. +- [Paragraphs](docs/paragraphs.md) covers paragraph text: its width and box, the codes its + value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. - [Xrefs](docs/xrefs.md) covers references to DWG files: the path, units, a diff --git a/cli/AGENTS.md b/cli/AGENTS.md index f19777e..44fedc5 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -29,8 +29,9 @@ there is no `prlimit`. - The renderer consults no system font by name. `src/fonts.ts` looks in the machine's font folders, once for the life of the command, for the file of each TrueType font of `FONTS`, - or of a font made to its widths, and takes a file only when the family name inside it is - the one expected. `src/png.ts` sends the renderer's process the files a picture needs, and + or of a font made to its widths, and of its bold beside it, and takes a file only when the + family name inside it is the one expected. A bold text's `font-weight` comes before the three + attributes `src/png-child.ts` sizes a text by, so it sizes one by its bold face's cap height. `src/png.ts` sends the renderer's process the files a picture needs, and the process sets the SVG's font family to the file's own. Every other font is drawn in the shipped JetBrains Mono. `outputs.pngFonts` and each layout's `pngFonts` say which, from `pictureFaces`, the one function that picks the files `toPNG` sends. A PDF embeds the same diff --git a/cli/src/fonts.ts b/cli/src/fonts.ts index 2c555e0..5c1446e 100644 --- a/cli/src/fonts.ts +++ b/cli/src/fonts.ts @@ -8,7 +8,7 @@ import { readdirSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; -import { FONTS, pdfFace } from "tsdraft"; +import { boldFontKey, capHeightOf, FONTS, pdfFace } from "tsdraft"; import type { PngFont } from "./state.ts"; /** The font the command ships: JetBrains Mono, under the OFL in assets/fonts/OFL.txt. */ @@ -28,10 +28,30 @@ export function shippedCap(): number { * Fonts made to the widths of another: each has, letter for letter, the advance widths of the * font it stands in for. The Liberation fonts are installed on most Linux machines. */ -const SAME_WIDTHS: Readonly> = { - Arial: [{ face: "Liberation Sans", file: "LiberationSans-Regular.ttf" }], - "Courier New": [{ face: "Liberation Mono", file: "LiberationMono-Regular.ttf" }], - "Times New Roman": [{ face: "Liberation Serif", file: "LiberationSerif-Regular.ttf" }], +const SAME_WIDTHS: Readonly< + Record +> = { + Arial: [ + { + face: "Liberation Sans", + file: "LiberationSans-Regular.ttf", + bold: "LiberationSans-Bold.ttf", + }, + ], + "Courier New": [ + { + face: "Liberation Mono", + file: "LiberationMono-Regular.ttf", + bold: "LiberationMono-Bold.ttf", + }, + ], + "Times New Roman": [ + { + face: "Liberation Serif", + file: "LiberationSerif-Regular.ttf", + bold: "LiberationSerif-Bold.ttf", + }, + ], }; /** A font file the renderer loads, and what the SVG's `font-family` becomes for it. */ @@ -43,6 +63,8 @@ export interface Face { readonly file: string; /** The height of a capital in the file, as a share of the font's size. */ readonly capHeight: number; + /** The file of the face's bold, of the same family, and the height of a capital in it. */ + readonly bold?: { readonly file: string; readonly capHeight: number }; } /** The folders an operating system keeps its fonts in. */ @@ -160,30 +182,57 @@ export function capHeight(bytes: Uint8Array): number | undefined { * @param folders - Where to look. The operating system's font folders unless given. */ export function findFaces(folders: readonly string[] = fontFolders()): Map { - const wanted: { font: string; face: string; file: string }[] = []; + const wanted: { font: string; face: string; file: string; bold: readonly string[] }[] = []; for (const [font, info] of Object.entries(FONTS)) { if (!("capHeight" in info)) continue; // Windows names the file as `FONTS` does, and macOS by the typeface. - for (const file of [info.file, `${font}.ttf`]) wanted.push({ font, face: font, file }); - for (const same of SAME_WIDTHS[font] ?? []) wanted.push({ font, ...same }); + const bold = "bold" in info ? [info.bold.file, `${font} Bold.ttf`] : []; + for (const file of [info.file, `${font}.ttf`]) wanted.push({ font, face: font, file, bold }); + for (const same of SAME_WIDTHS[font] ?? []) wanted.push({ font, ...same, bold: [same.bold] }); } - const files = findFiles(folders, new Set(wanted.map((w) => w.file.toLowerCase()))); - const faces = new Map(); - for (const { font, face, file } of wanted) { + const files = findFiles( + folders, + new Set(wanted.flatMap((w) => [w.file, ...w.bold]).map((file) => file.toLowerCase())), + ); + /** The bytes of a file found, of the family `face`, or undefined. */ + const read = (file: string, face: string): Uint8Array | undefined => { const path = files.get(file.toLowerCase()); - if (faces.has(font) || path === undefined) continue; - let bytes; + if (path === undefined) return undefined; try { - bytes = readFileSync(path); + const bytes = readFileSync(path); + return familyName(bytes) === face ? bytes : undefined; } catch { - continue; + return undefined; } - if (familyName(bytes) !== face) continue; + }; + const faces = new Map(); + for (const { font, face, file, bold } of wanted) { + if (faces.has(font)) continue; + const bytes = read(file, face); + if (bytes === undefined) continue; const info: { family: string; capHeight?: number } = FONTS[font as keyof typeof FONTS]; // The font's own file is sized as `FONTS` says the leading CAD app sizes the font. A font that // stands in for it is sized by its own capitals, and one that states no cap height as the font. - const cap = (face === font ? undefined : capHeight(bytes)) ?? info.capHeight ?? shippedCap(); - faces.set(font, { family: info.family, face, file: path, capHeight: cap }); + const own = face === font; + const cap = (own ? undefined : capHeight(bytes)) ?? info.capHeight ?? shippedCap(); + const found: Face = { + family: info.family, + face, + file: files.get(file.toLowerCase())!, + capHeight: cap, + }; + const boldFile = bold.find((name) => read(name, face) !== undefined); + if (boldFile === undefined) { + faces.set(font, found); + continue; + } + const boldBytes = read(boldFile, face)!; + const boldCap = + (own ? capHeightOf(font, true) : capHeight(boldBytes)) ?? info.capHeight ?? shippedCap(); + faces.set(font, { + ...found, + bold: { file: files.get(boldFile.toLowerCase())!, capHeight: boldCap }, + }); } return faces; } @@ -228,9 +277,17 @@ export function pngFonts( }); } -/** The files a PDF embeds, by the font each sets: the faces the machine has. */ +/** + * The files a PDF embeds, by the font each sets: the faces the machine has, and the bold of each + * by `boldFontKey` of its font. + */ export function pdfFiles(known: ReadonlyMap = faces()): Record { - return Object.fromEntries([...known].map(([font, face]) => [font, face.file])); + return Object.fromEntries( + [...known].flatMap(([font, face]) => [ + [font, face.file], + ...(face.bold ? [[boldFontKey(font), face.bold.file]] : []), + ]), + ); } /** The face a PDF sets a font in with a file, by the font and the file's path, read once. */ diff --git a/cli/src/png-child.ts b/cli/src/png-child.ts index c9989f2..b22f079 100644 --- a/cli/src/png-child.ts +++ b/cli/src/png-child.ts @@ -33,6 +33,8 @@ export interface PngRequest { readonly face: string; readonly file: string; readonly capHeight: number; + /** The file of its bold, of the same family name, and the height of a capital in it. */ + readonly bold?: { readonly file: string; readonly capHeight: number }; }[]; /** The height of a capital of this process's own font, as a share of its size. */ readonly capHeight: number; @@ -59,14 +61,16 @@ async function draw({ svg, width: fitted, faces, capHeight }: PngRequest): Promi ? Math.max(1, 1 / (base * (fitted / w))) : Math.max(1, fitted / 1200) / (fitted / w) / base; // `toSVG` gives each text the height of its capitals, and sizes it for the font it names. - // Here it is sized for the face it is drawn in, so that its capitals are that tall. + // Here it is sized for the face it is drawn in, so that its capitals are that tall, in bold where + // the text is bold and the face has one. const byFamily = new Map(faces.map((face) => [attribute(face.family), face])); let set = svg.replace( - / font-size="[^"]*" font-family="([^"]*)" data-height="([^"]*)"/g, - (_, family: string, height: string) => { + /( font-weight="bold")? font-size="[^"]*" font-family="([^"]*)" data-height="([^"]*)"/g, + (_, bold: string | undefined, family: string, height: string) => { const face = byFamily.get(family); - const size = Number(height) / (face?.capHeight ?? capHeight); - return ` font-size="${size}" font-family="${face ? attribute(face.face) : family}"`; + const cap = (bold ? face?.bold?.capHeight : undefined) ?? face?.capHeight ?? capHeight; + const size = Number(height) / cap; + return `${bold ?? ""} font-size="${size}" font-family="${face ? attribute(face.face) : family}"`; }, ); // A picture from a copy of tsdraft that gives no height keeps its sizes. @@ -86,7 +90,10 @@ async function draw({ svg, width: fitted, faces, capHeight }: PngRequest): Promi fitTo: { mode: "width", value: fitted }, background: BACKGROUND, font: { - fontFiles: [FONT, ...faces.map((face) => face.file)], + fontFiles: [ + FONT, + ...faces.flatMap((face) => [face.file, ...(face.bold ? [face.bold.file] : [])]), + ], loadSystemFonts: false, defaultFontFamily: "JetBrains Mono", monospaceFamily: "JetBrains Mono", diff --git a/cli/test/png.test.ts b/cli/test/png.test.ts index 3562a36..e554ce7 100644 --- a/cli/test/png.test.ts +++ b/cli/test/png.test.ts @@ -3,12 +3,13 @@ import { test } from "node:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { createDrawing, FONTS, measureText, toSVG, type Font } from "tsdraft"; +import { capHeightOf, createDrawing, FONTS, measureText, toSVG, type Font } from "tsdraft"; import { capHeight, faces, familyName, findFaces, + pdfFiles, pngFonts, shippedCap, SHIPPED, @@ -17,6 +18,12 @@ import { import { pngUnavailable, RendererCrashed, toPNG } from "../src/png.ts"; import { decode, ink } from "./pixels.ts"; +/** A font's family and the height of its capitals, as a face of it has them. */ +const faceOf = (font: "Arial" | "Times New Roman") => ({ + family: FONTS[font].family, + capHeight: FONTS[font].capHeight, +}); + test( "a renderer whose process cannot start gives each picture the reason, and the command lives", { skip: pngUnavailable() ?? false }, @@ -82,8 +89,8 @@ test("a font file is a face of the font only when it names itself so", (t) => { { font: "Arial", face: "JetBrains Mono" }, { font: "romans.shx", face: "JetBrains Mono" }, ]); - const arial = { ...FONTS.Arial, face: "Liberation Sans", file: "/fonts/a.ttf" }; - const times = { ...FONTS["Times New Roman"], face: "Times New Roman", file: "/t" }; + const arial = { ...faceOf("Arial"), face: "Liberation Sans", file: "/fonts/a.ttf" }; + const times = { ...faceOf("Times New Roman"), face: "Times New Roman", file: "/t" }; const both = new Map([ ["Arial", arial], ["Times New Roman", times], @@ -96,6 +103,47 @@ test("a font file is a face of the font only when it names itself so", (t) => { ]); }); +/** A copy of a TrueType file whose Windows names give `family`, no longer than its own, as its family. */ +function renamed(bytes: Uint8Array, family: string): Uint8Array { + const copy = new Uint8Array(bytes); + const view = new DataView(copy.buffer); + for (let i = 0; i < view.getUint16(4); i++) { + const entry = 12 + i * 16; + if (String.fromCharCode(...copy.subarray(entry, entry + 4)) !== "name") continue; + const table = view.getUint32(entry + 8); + const strings = table + view.getUint16(table + 4); + for (let n = 0; n < view.getUint16(table + 2); n++) { + const record = table + 6 + n * 12; + if (view.getUint16(record) !== 3 || view.getUint16(record + 6) !== 1) continue; + const offset = strings + view.getUint16(record + 10); + for (let k = 0; k < family.length; k++) view.setUint16(offset + 2 * k, family.charCodeAt(k)); + view.setUint16(record + 8, family.length * 2); + } + } + return copy; +} + +test("a TrueType font's bold file is found beside its own, and the PDF is given it", (t) => { + const dir = mkdtempSync(join(tmpdir(), "tsdraft-fonts-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const arial = renamed(readFileSync(SHIPPED.file), "Arial"); + assert.equal(familyName(arial), "Arial"); + writeFileSync(join(dir, "arial.ttf"), arial); + // No bold yet: the face has none. + assert.equal(findFaces([dir]).get("Arial")?.bold, undefined); + writeFileSync(join(dir, "arialbd.ttf"), arial); + const found = findFaces([dir]); + // The font's own bold is sized as the leading CAD app sizes it. + assert.deepEqual(found.get("Arial")?.bold, { + file: join(dir, "arialbd.ttf"), + capHeight: capHeightOf("Arial", true), + }); + assert.deepEqual(pdfFiles(found), { + Arial: join(dir, "arial.ttf"), + "Arial Bold": join(dir, "arialbd.ttf"), + }); +}); + /** Pixels to a drawing unit in the pictures below, which are 60 units wide. */ const SCALE = 50; @@ -180,7 +228,7 @@ test( const own = faces().get("Arial"); if (own) check(await drawn(value, { font: "Arial" }), own.face); // A face that says its capitals are half as tall as they are is drawn twice too tall. - const wrong = new Map([["Arial", { ...FONTS.Arial, ...SHIPPED, capHeight: 0.73 / 2 }]]); + const wrong = new Map([["Arial", { ...faceOf("Arial"), ...SHIPPED, capHeight: 0.73 / 2 }]]); const [, bottom, , top] = await drawn(value, { font: "Arial" }, wrong); assert.ok(Math.abs(top - bottom - 2) <= 3 / SCALE); }, diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index f1316dd..a3b441d 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -282,68 +282,88 @@ GENERAL NOTES 1. - PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD - SURVEY WAS MADE FOR THIS PLAN. - 2. - DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE - FOUNDATION WALL. - 3. - SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY LINE - TO THE NEAREST WALL. - 4. - THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. - 5. - LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. - 6. - GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE - STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. - 7. - PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL - THE LOT IS STABILIZED. - 8. - PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. - 9. - WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. - 10. - REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING - CONSTRUCTION. - LEGEND - - - PROPERTY LINE - - ADJOINING LOT LINE - - BUILDING SETBACK LINE - - BUILDING FOOTPRINT - - EDGE OF PAVEMENT OR CONCRETE - - STREET CENTERLINE + + PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD + SURVEY WAS MADE FOR THIS PLAN. + + 2. + + DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE + FOUNDATION WALL. + + 3. + + SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY LINE + TO THE NEAREST WALL. + + 4. + + THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. + + 5. + + LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. + + 6. + + GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE + STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. + + 7. + + PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL + THE LOT IS STABILIZED. + + 8. + + PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. + + 9. + + WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. + + 10. + + REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING + CONSTRUCTION. + + LEGEND + + + PROPERTY LINE + + ADJOINING LOT LINE + + BUILDING SETBACK LINE + + BUILDING FOOTPRINT + + EDGE OF PAVEMENT OR CONCRETE + + STREET CENTERLINE - + - PROPERTY CORNER + PROPERTY CORNER - - - + + + - EXISTING TREE TO REMAIN - ABBREVIATIONS - - AC - ACRES - CONC. - CONCRETE - ELEV. - ELEVATION - F.F.E. - FINISHED FLOOR ELEVATION - MAX. - MAXIMUM - SF - SQUARE FEET + EXISTING TREE TO REMAIN + ABBREVIATIONS + + AC + ACRES + CONC. + CONCRETE + ELEV. + ELEVATION + F.F.E. + FINISHED FLOOR ELEVATION + MAX. + MAXIMUM + SF + SQUARE FEET diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index db02147..576db28 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -282,68 +282,88 @@ GENERAL NOTES 1. - PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD - SURVEY WAS MADE FOR THIS PLAN. - 2. - DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE - FOUNDATION WALL. - 3. - SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY LINE - TO THE NEAREST WALL. - 4. - THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. - 5. - LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. - 6. - GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE - STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. - 7. - PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL - THE LOT IS STABILIZED. - 8. - PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. - 9. - WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. - 10. - REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING - CONSTRUCTION. - LEGEND - - - PROPERTY LINE - - ADJOINING LOT LINE - - BUILDING SETBACK LINE - - BUILDING FOOTPRINT - - EDGE OF PAVEMENT OR CONCRETE - - STREET CENTERLINE + + PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD + SURVEY WAS MADE FOR THIS PLAN. + + 2. + + DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE + FOUNDATION WALL. + + 3. + + SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY LINE + TO THE NEAREST WALL. + + 4. + + THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. + + 5. + + LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. + + 6. + + GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE + STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. + + 7. + + PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL + THE LOT IS STABILIZED. + + 8. + + PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. + + 9. + + WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. + + 10. + + REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING + CONSTRUCTION. + + LEGEND + + + PROPERTY LINE + + ADJOINING LOT LINE + + BUILDING SETBACK LINE + + BUILDING FOOTPRINT + + EDGE OF PAVEMENT OR CONCRETE + + STREET CENTERLINE - + - PROPERTY CORNER + PROPERTY CORNER - - - + + + - EXISTING TREE TO REMAIN - ABBREVIATIONS - - AC - ACRES - CONC. - CONCRETE - ELEV. - ELEVATION - F.F.E. - FINISHED FLOOR ELEVATION - MAX. - MAXIMUM - SF - SQUARE FEET + EXISTING TREE TO REMAIN + ABBREVIATIONS + + AC + ACRES + CONC. + CONCRETE + ELEV. + ELEVATION + F.F.E. + FINISHED FLOOR ELEVATION + MAX. + MAXIMUM + SF + SQUARE FEET diff --git a/docs/command.md b/docs/command.md index 879dac0..ccc5c85 100644 --- a/docs/command.md +++ b/docs/command.md @@ -315,6 +315,9 @@ set each TrueType font in: - a font made to its widths, whose letters each take the room of the font's own: Liberation Sans for Arial, Liberation Serif for Times New Roman and Liberation Mono for Courier New. +Beside each, it looks for the file of its bold, such as `arialbd.ttf`, the name `FONTS` gives +it, or `LiberationSans-Bold.ttf`, for the bold runs of paragraphs, and a PDF embeds it too. + A file counts only when the family name inside it is the one expected. An SHX font, and a TrueType font the machine has neither file for, is set in JetBrains Mono. diff --git a/docs/format.md b/docs/format.md index b399d3b..f84e29d 100644 --- a/docs/format.md +++ b/docs/format.md @@ -75,6 +75,14 @@ list of points from its tip. Where it has them of its own it has a `side`, an `a lineweight. A drawing with no leader has the JSON it had before leaders existed. [Leaders](leaders.md) describes them. +A paragraph is an entity of kind `"paragraph"`, in `drawing.entities`, a block's `entities` or a +layout's `entities`, with its `layer`, `at`, `height`, `value` and `rotation`, as a text has them, +and where they are set a `width`, a `style`, an `align` of `"center"` or `"right"`, a `valign` of +`"middle"` or `"bottom"`, a `lineSpacing` other than 1, a `lineSpacingStyle` of `"exactly"`, and +the `linetype` and `lineweight` of every entity. Its value holds `\P` for each paragraph break. +A drawing with no paragraph has the JSON it had before paragraphs existed. +[Paragraphs](paragraphs.md) describes them. + A drawing written by hand needs `format: 0` too. `lint` reports a drawing without it, or with another version, under the rule `format`, and `toDXF` refuses to write it. `lint` takes any plain data and never throws: a list that is not an array, an entity of an unknown `kind`, a diff --git a/docs/paragraphs.md b/docs/paragraphs.md new file mode 100644 index 0000000..4519422 --- /dev/null +++ b/docs/paragraphs.md @@ -0,0 +1,226 @@ +# Paragraphs + +A paragraph is one text whose lines wrap at a width and break at each line feed. In the file it +is an `MTEXT`, which a CAD user selects, moves and edits as one: a general note, a callout of +several lines, a block of specifications. A text, `d.text`, is one line and never wraps. + +Paragraphs are R2018 only. The builder's types make one a compile error in an R12 drawing, and +`lint` refuses one there. + +## Placing a paragraph + +```ts +d.paragraph("ALL WORK SHALL COMPLY WITH THE CODES IN FORCE.", { + at: [1, 20], + width: 4, + height: 0.1, +}); +``` + +`at` is a point of the paragraph's box, which `align` and `valign` name: `"left"`, `"center"` or +`"right"` across it, and `"top"`, `"middle"` or `"bottom"` up and down it. The defaults put `at` +at the box's upper left corner. `align` also sets each line in the box: flush left, centered or +flush right. + +- `width` is the width the lines wrap at. Without it, the lines break only at line feeds, and + the box is as wide as the widest line. +- `height` is the height of a capital, 0.125 by default, as a text's is. +- `rotation` turns the paragraph about `at`, in degrees counterclockwise. It is taken within a + turn, from 0 up to 360, and to 6 decimals, as the writers write it: `paragraphDirection` gives + the direction its lines run in, which both writers write and its layout is placed by. +- `style` is a text style of the drawing, or a definition of one, as a text's is. +- `lineSpacing` is a factor of the spacing of the lines, from 0.25 to 4, 1 by default. + `lineSpacingStyle` is `"at-least"`, the default, or `"exactly"`. + +A paragraph takes the options of every entity: an `id`, a `linetype`, a `lineweight` and, under +a standard, a `pen`. Under a standard it names a `role`, which gives its height and text style as +it gives a text's, and in model space the `view` it is read in. + +## The value + +A line feed in the value given to `paragraph()` starts a new paragraph. The paragraph holds it as +`\P`, the code a CAD program writes, so a value read back from a file has `\P` where the line +feed was. + +The value holds the inline codes of an `MTEXT`, as the DXF Reference gives them. tsdraft lays out +these: + +| Code | Draws | +| -------------------- | --------------------------------------------------------------------------- | +| `\P` | A paragraph break | +| `\~` | A space the line does not break at | +| `\\`, `\{`, `\}` | A backslash and a brace | +| `{` and `}` | A group: what a code sets inside it ends at its `}`, 16 groups deep at most | +| `\L` and `\l` | Underline on and off | +| `\K` and `\k` | Strike-through on and off | +| `\fArial\|b1;` | A TrueType font of `FONTS`, in bold with `b1`: `i0`, `c` and `p` pass | +| `\Fromans.shx;` | An SHX font of `FONTS` | +| `\S1/2;` | A fraction stacked over a level bar | +| `\S1#2;` | A fraction stacked beside a slash | +| `\S+0.1^-0.2;` | Two parts stacked with no bar, as a tolerance | +| `\S2^ ;` and `\S^2;` | A superscript and a subscript | +| `%%d`, `%%p`, `%%c` | A degree sign, a plus-or-minus sign and a diameter sign | +| `\U+XXXX` | The character of that code point | + +`%%` before any other character draws as it is: `100%%%` draws three percent signs, and `%%%d` +a percent sign and a degree sign. + +A stack's parts hold digits or capitals, with `.`, `,`, `+` or `-` beside them, as a fraction or +a tolerance does, or only spaces, as the bottom of a superscript does, or nothing, as the top of +a subscript does. Its parts are as tall as the text around them. + +Helpers write the codes, so a value reads as what it draws: + +```ts +import { bold, plain, stack, subscript, superscript, underline } from "tsdraft"; + +d.paragraph( + `${bold("GENERAL NOTES", "Arial")} +1. ${underline("VERIFY")} ALL DIMENSIONS IN THE FIELD. +2. GAP 3${stack("1", "2")}", AREA 12 FT${superscript("2")}. +3. OWNER: ${plain(owner)}`, + { at: [1, 20], width: 4, height: 0.1 }, +); +``` + +- `underline(text)` underlines a group. +- `bold(text, font)` sets a group in the bold face of a TrueType font of `FONTS`, which it is then + set in, and measured by its own widths. A bold code names its font, so the helper takes one. +- `stack(top, bottom, divider)` stacks two parts: over a level bar for `"/"`, the default, + beside a slash for `"#"`, and with no bar for `"^"`. +- `superscript(text)` and `subscript(text)` set a part above the line, and at its foot. +- `plain(text)` escapes what would start a code: a backslash, a brace, and the second percent + sign of `%%d`, `%%p` and `%%c`, written as `\U+0025`, so a value that comes from elsewhere draws + as it is. + +## What `lint` refuses + +`lint` refuses a value it cannot lay out as the leading CAD app does, and the builder refuses the +same as the code runs; a literal value with one of these mistakes is a compile error too. Each +message names the code. + +- A `{` that is never closed, a `}` that closes nothing, and groups nested more than 16 deep. +- A code tsdraft does not know, such as `\Z`, and a backslash at the end of the value. +- A code with no `;` to end it, such as `\fArial` with nothing after it. +- A font in `\f` or `\F` that is not one of `FONTS`, since the leading CAD app draws a font it does + not have in another font. Italic, `\f...|i1;`, since tsdraft has no widths for italic letters. + Bold in an SHX font, which has no bold. An option other than `b0`, `b1`, `i0`, and `c` or `p` + with digits after it, and an option given twice, as `\fArial|b1|b0;`. +- `%%c` in an SHX font, the style's or one a `\f` code sets, which draws a diameter sign of its + own, narrower than `Ø`, that tsdraft does not lay out yet. A TrueType font draws it as `Ø`, and + keeps it. The type of a literal value refuses it in a font a `\f` or `\F` code sets, as far as + that code's group reaches; in the style's font only `lint` and the builder refuse it, since the + type does not know the style's font. A read `MTEXT` that holds one is laid out as approximate. +- A control character, a tab among them, a character above U+FFFF and the private-use characters + U+E800 to U+E8FF, which a text cannot hold either. The type of a literal value refuses all but a + character above U+FFFF, which only `lint` and the builder refuse: TypeScript reads a template + literal type by characters and never splits the two halves of one, so no type can find it. +- The codes tsdraft does not lay out yet: `\p`, a paragraph's indents, tab stops and alignment, + which numbered and lettered lists are made of; `\N`, columns; `\H` the height, `\W` the width + factor, `\Q` the oblique angle, `\T` the spacing and `\A` the alignment of the characters after + it; `\C` and `\c` color; `\O`, an overline, which sits at a TrueType font's ascent, which + tsdraft's tables do not hold; `\X`, which only a dimension's text holds; and `\M+NXXXX`, a + character of a code page. A paragraph that held one would plot otherwise than tsdraft draws it. +- A stacked part that holds other characters than those above, such as `\Sx/y;`, since where it + stands depends on the top of its letters, which tsdraft's tables hold only for digits and + capitals; and a stack in underlined or struck-through characters, which is laid out otherwise. + +It also refuses a height or a width that is not greater than 0 as written, a line spacing outside +0.25 to 4 as given, so none rounds into the range or out of it, an `align`, a `valign` or a `lineSpacingStyle` that is not one of its +choices, and a text style the drawing does not have. + +## How a paragraph is laid out + +`layoutParagraph` and `measureParagraph` are the one layout of a paragraph. The extents, `toSVG`, +`toPDF`, `inspectText` and the box of the view a DXF opens at all take a paragraph's lines and its +box from them, from the widths `measureText` measures a text by and the ink of each character +that `FONT_METRICS` holds beside them. They read the height, the width, the line spacing factor +and the style's width factor and oblique angle as the writers write them, to 6 decimals, so a +paragraph wraps in the picture where it wraps in the file. + +```ts +const { lines, corners, frame } = measureParagraph({ + value: "ALL WORK SHALL COMPLY WITH THE CODES IN FORCE.", + height: 0.1, + width: 1.5, + font: "Arial", +}); +``` + +`lines` holds each line that draws a character, with the box of its capitals, as `measureText` +gives a text's. `corners` is the box of all the paragraph draws, and `frame` the box `align` and +`valign` place it by. `layoutParagraph` gives the same before the paragraph is turned and moved, +with each run of characters in one font and format, where it starts, and each underline and bar. +`paragraphInStyle(paragraph, style)` gives a paragraph in its text style, as `measureParagraph` +takes it. + +tsdraft lays a paragraph out by the rules of the leading CAD app, in heights `h` of the paragraph, +from the widths and the ink of each character that `FONT_METRICS` holds: + +- A run is characters of one font, face and format, set by their advances. The next run starts + where the last one's advances end, or where its last character's ink ends where that is + further, as after an `f`. +- A line starts at the left of its first character's ink and ends at the right of its last + one's. It keeps the spaces it starts with and drops those it ends with. `"left"` puts that + start on `at`, `"right"` that end, and `"center"` the middle of the two: the width moves no line. +- A line breaks only at a space, and only to keep the next word inside the width: the word stays + when the advances up to it, from the line's first point, and its own ink come to no more than + the width. The left of the line's first letter has no part in it. A word wider than the width + stays whole and passes it. In a word that holds a stack, what follows the last stack stands + for the word, or the stack where it ends the word. +- With `"at-least"` spacing, each line takes `lineSpacing` times its ascent, a third of the height + of what reaches highest, and `h/3`. Its ascent is how far its letters reach above the baseline, + at least `h`, as an `Å` or a stack reaches further: a plain line takes `5h/3`. The first line's + top is the top of the box, and the box ends at the bottom of the last line's ink. +- With `"exactly"`, the first baseline is `h` below the top of the box and each next one + `lineSpacing` times `5h/3` below it, whatever the lines hold, and the box ends `h/3` below the + last. +- The style's width factor scales everything along a line. In a TrueType font its oblique angle + moves where a line starts by its first letter's bottom, and where it ends by its ascent, times + the angle's tangent. +- An underline runs from a run's first character to the end of its last one's advance, at the + font's descent in a TrueType font and `h/5` below the baseline in an SHX font. A + strike-through runs `h/2` above it. +- A bold run is in its font's bold face, with that face's own widths and ink. +- A fraction's top part has its ink's top at the top of the stack and its baseline `h/6` above a + bar as long as the wider part's ink, and the bottom part its ink `h/6` below the bar and its + baseline on the line's. Each part is centered on the bar. `^` sets both parts from the stack's + start with no bar, as a tolerance; `#` sets them side by side with a slash between. A + superscript is a tolerance over a space, `h/3` up, and a subscript one under nothing, on the + baseline. The next character starts a little past the stack's ink, by the font. + +`approximate` is true where tsdraft's numbers are an estimate: a value with a code it does not +lay out or a character outside its tables, a font that is not one of `FONTS`, an oblique angle in +an SHX font, `%%c` in an SHX font, which draws a diameter sign of its own, and a stack in a +TrueType font other than Arial, whose digits and capitals may stand lower than its `A`. + +`inspectText` checks each line of a paragraph as it checks a text: one that plots over another +text, runs past the outline it starts in, or off the paper. + +## In the picture and the plot + +`toSVG` draws a paragraph as a group, `data-paragraph`, with each run as a text is drawn: in a +TrueType font from its first point and held to its characters' advances, and in an SHX font from +where its layout starts it to where it ends. Each underline, strike-through, bar and slash is a +line of its pen. Each part of a stack is a run of its own. A bold run has `font-weight="bold"` and is +sized by its bold face's own capital `A`, which `capHeightOf(font, true)` gives. `toPDF` sets a +bold run in the bold face of its font's file when `fonts` holds one under the font's name and +` Bold`, as `{ "Arial Bold": bytes }`, which `boldFontKey` gives, and in Helvetica-Bold, +Times-Bold or Courier-Bold otherwise. `FONTS` names each TrueType font's bold file, such as +`arialbd.ttf`, which `tsdraft render` and `tsdraft dev` look for beside the regular one. + +## Reading + +`readDXF` reads an `MTEXT` with its point, height, width, attachment, rotation, text style, value, +line spacing factor and line spacing style. Its rotation comes from its direction, groups 11 and +21, or else from group 50 in degrees, as the leading CAD app reads it, though the DXF Reference +gives radians; tsdraft writes the direction. `layoutMtext(mtext, style)` and `measureMtext` lay +one out by the same rules, in the font of `FONTS` nearest its style's, and say it is approximate +when the font is not the style's own or the value holds a code tsdraft does not lay out. +[Reading drawing files](reading.md) has the rest. + +## Not yet + +Numbered and lettered lists with hanging indents, tab stops, columns, the codes that change the +height, width, slant, spacing, alignment or color of the characters after them, an overline, +stacked parts in lower case, and attributes of more than one line. diff --git a/docs/plotting.md b/docs/plotting.md index 39870c7..080d8be 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -80,6 +80,10 @@ const fonts = { Arial: readFileSync("arial.ttf"), "Times New Roman": readFileSyn writeFileSync("set.pdf", toPDF(drawing, { xrefs, deflate, fonts })); ``` +A bold run of a paragraph is set in the file given under its font's name and ` Bold`, which +`boldFontKey` gives: `{ "Arial Bold": readFileSync("arialbd.ttf") }`. `FONTS` names each bold +file. + The PDF embeds each file, cut to the glyphs of the characters its pages set, so every character plots in the letters of the file: `°`, `±`, `½` and `≥` as `A` does. A set embeds each font once, for all its pages. The file may be the font's own, or one made to its widths, such as Liberation diff --git a/docs/reading.md b/docs/reading.md index 4020b79..ca0f9e3 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -106,8 +106,11 @@ A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers scale and rotation, `tags`, and with `geometry` its `attributes`: each a text with its `tag` and its `value` where the file places it, and `invisible` for one that does not show. An insert with columns and rows is counted under `other`. -- `mtext`: a paragraph text with its point, height, width, attachment, rotation, style and - value, its formatting codes kept. It is not laid out. +- `mtext`: a paragraph text with its point, height, width, attachment, rotation, from its + direction or else from group 50 in degrees, style, + value, its formatting codes kept, `lineSpacing`, its line spacing factor, 1 where the file + states none, and `lineSpacingStyle`, `"at-least"` or `"exactly"`. `layoutMtext` and + `measureMtext` lay it out as tsdraft lays out a paragraph: [Paragraphs](paragraphs.md#reading). - `dimension`: a linear or aligned dimension, with its two points, the point where its dimension line meets its second extension line, its direction, the middle of its text, what it measures, its text, its style and the block of its picture. The other kinds of dimension are counted diff --git a/docs/rules.md b/docs/rules.md index af4fe52..f94ce5f 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -36,6 +36,16 @@ it would take `1e+100` for `1e+10` and report nothing. since the leading CAD app reads a negative width of every side as 0 and keeps a negative width of one side with no `AUDIT` error, and a polyline has one width for every side or one for each, not both. [Polylines](polylines.md#checks) has the rest. +- A paragraph is R2018 only. Its height, and its width where it has one, are greater than 0 as + written, its line spacing is a factor from 0.25 to 4 as written, and its value holds only the + codes tsdraft lays out: its braces close, each code is one tsdraft knows and ends with its `;` + where it takes one, a font is one of `FONTS`, in bold only for a TrueType font and never in + italic, and braces nest at most 16 deep. The codes of lists, tab stops, columns, the height, + width, slant, spacing, alignment and color of characters, and an overline, are refused until + tsdraft lays them out, since a paragraph that held one would plot otherwise than tsdraft draws + it. So are a stacked part of other characters than digits and capitals with `.`, `,`, `+` or + `-`, or spaces, and a stack in underlined or struck-through characters. + [Paragraphs](paragraphs.md#what-lint-refuses) has the rest. - Arc angles are stored from 0 up to 360, so -90 becomes 270. An arc cannot come within 0.000001 degrees of a full turn, because its two angles would be written the same and the leading CAD app holds such an arc as having no length. Draw a diff --git a/docs/text.md b/docs/text.md index 18272bb..bcfc7d8 100644 --- a/docs/text.md +++ b/docs/text.md @@ -127,9 +127,12 @@ drawing's extents, `toSVG` and `inspectText` all take a text's box from it. ## Text as it plots -`toSVG` starts each text where `measureText` says it plots, sets its `textLength` to the length -it plots at, and keeps its spaces, so a text is as long in the picture as on paper, in any -font. It draws the text in a CSS font family for its font, ending in a generic family for a +`toSVG` starts each text where `measureText` places it, sets its `textLength`, and keeps its +spaces, so a text is as long in the picture as on paper, in any font. A text in a TrueType font +starts at its first point and is held to its characters' advances, where the leading CAD app's +PDF sets its glyphs, so a last letter whose ink reaches past its advance, as an `f` does, +stretches nothing. A text in an SHX font, which plots as strokes, starts where it starts to draw +and is held to the length it plots at. It draws the text in a CSS font family for its font, ending in a generic family for a screen that lacks the font, at a size that makes that font's capitals the text's height: the height itself is in the element's `data-height`. An SHX font is drawn in a generic family, as a font whose capitals are 0.7 of its size, so on a screen an SHX text's letters have other diff --git a/examples/site-plan.ts b/examples/site-plan.ts index b32eac2..04109fb 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -52,9 +52,12 @@ // as a gap, into feet at the view's ratio. So the same code draws the sheet at another scale: // the plan changes size in its viewport and its text keeps its plotted height. // - A text names a role of the standard, which gives its text style and height, and is -// justified to its point with `align` and `valign`. Columns and line breaks are laid out by -// the length `measureText` gives a text in its role. The title block's texts, below, are the -// one exception. +// justified to its point with `align` and `valign`. Columns are laid out by the length +// `measureText` gives a text in its role. The title block's texts, below, are the one +// exception. +// - A general note is one paragraph, which wraps at the width of the column of notes and which a +// drafter edits as one. `layoutParagraph` gives its lines, so its first line sits on its +// number's row and the next note starts under its last line. // - A symbol is a block, drawn once and inserted where it is needed. The tree and the property // corner are in the plan and in the legend, so each is inserted in model space and on the // layout. A block's entities are on layer 0, so each insert draws on its own layer. @@ -80,6 +83,7 @@ import { checkIntent, createDrawing, defineStandard, + layoutParagraph, measureText, toDXF, toSVG, @@ -680,22 +684,6 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee } } - /** Breaks a sentence into lines no longer than `width`, by the length each plots at. */ - function wrap(sentence: string, role: Role, width: number): string[] { - const lines: string[] = []; - let line = ""; - for (const word of sentence.split(" ")) { - const longer = line ? `${line} ${word}` : word; - if (line && widthOf(longer, role) > width) { - lines.push(line); - line = word; - } else { - line = longer; - } - } - return [...lines, line]; - } - columnHeading("SITE DATA"); d.layer("C-ANNO-TEXT", () => { const coverage = (footprintArea / lotArea) * 100; @@ -740,13 +728,15 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee "REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING CONSTRUCTION.", ]; const indent = widthOf("00. ", "label"); + const width = column.width - indent; notes.forEach((note, i) => { d.text([column.left, row], `${i + 1}.`, { role: "label" }); - for (const line of wrap(note, "label", column.width - indent)) { - d.text([column.left + indent, row], line, { role: "label" }); - row -= leading; - } - row -= leading / 3; + // The note's first baseline is on its number's row, and the next note starts a line and a + // third below its last. + const { lines } = layoutParagraph({ value: note, ...roles.label, width }); + const [first, last] = [lines[0]!.baseline, lines.at(-1)!.baseline]; + d.paragraph(note, { role: "label", at: [column.left + indent, row - first], width }); + row += last - first - leading - leading / 3; }); }); diff --git a/scripts/readme-drawing.ts b/scripts/readme-drawing.ts index 1b72241..b95ea9d 100644 --- a/scripts/readme-drawing.ts +++ b/scripts/readme-drawing.ts @@ -158,8 +158,11 @@ const group = /** The white rectangle toSVG draws the paper of a layout with. */ const PAPER = 'fill="#ffffff" data-paper-sheet=""/>'; -/** A dimension or a leader is a group that names the layer, and its parts are the lines after it. */ -const GROUPED = / data-(dimension|leader)="/; +/** + * A dimension, a leader or a paragraph is a group that names the layer, and its parts are the + * lines after it. + */ +const GROUPED = / data-(dimension|leader|paragraph)="/; /** A line one pixel wide just inside the edge of the picture, which is the sheet's edge. */ function sheetOutline(x: number, y: number, w: number, h: number, pixel: number, color: string) { diff --git a/src/drawing.ts b/src/drawing.ts index 5c3102a..82be8aa 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -27,7 +27,8 @@ import { validDimensionStyleHandle, type DimensionPlace, } from "./dimensions.ts"; -import { STANDARD_TEXT_STYLE } from "./fonts.ts"; +import { STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; +import { paragraphUnknownCode, parseParagraph } from "./paragraph-codes.ts"; import { leaderArrowheadHandles, leaderDrawnProblem, @@ -103,6 +104,9 @@ import { sizeProblem, textAlignProblem, textProblem, + lineSpacingProblem, + paragraphChoiceProblem, + paragraphProblemIn, textStyleNameProblem, textStyleProblem, undefinedAttributeProblem, @@ -145,6 +149,9 @@ import { type PolylineWidth, type R12Leaders, type R12Polylines, + type R12Paragraphs, + type LineSpacing, + type ParagraphValue, type LineweightMm, type LineweightOf, type LinetypeName, @@ -178,6 +185,9 @@ import { type Ratio, type TEXT_ALIGNS, type TEXT_VERTICAL_ALIGNS, + type LINE_SPACING_STYLES, + type PARAGRAPH_ALIGNS, + type PARAGRAPH_VERTICAL_ALIGNS, type LEADER_ATTACHMENTS, type LEADER_SIDES, } from "./rules.ts"; @@ -424,6 +434,48 @@ export interface Text extends EntityBase { readonly valign?: TextVerticalAlign; } +/** Where a paragraph's `at` point is across its box, and how its lines are set in it. */ +export type ParagraphAlign = (typeof PARAGRAPH_ALIGNS)[number]; + +/** Where a paragraph's `at` point is up and down its box. */ +export type ParagraphVerticalAlign = (typeof PARAGRAPH_VERTICAL_ALIGNS)[number]; + +/** + * How a paragraph's line spacing is taken: as the least its lines are apart, so a line whose + * letters reach further pushes the next one down, or as exactly that. + */ +export type LineSpacingStyle = (typeof LINE_SPACING_STYLES)[number]; + +/** + * Paragraph text: one entity whose lines wrap at a width and break at each `\P`, which the + * leading CAD app holds as one multi-line text and a drafter edits as one. Its value holds that + * app's inline codes, such as `\L` for an underline and `\S1/2;` for a stacked fraction, which + * `parseParagraph` reads. R2018 only. + */ +export interface Paragraph extends EntityBase { + readonly kind: "paragraph"; + /** The point of its box `align` and `valign` name: with their defaults, its upper left corner. */ + readonly at: Point; + /** The height of a capital, where no code sets another. */ + readonly height: number; + /** The value, with its codes. `\P` breaks a paragraph. */ + readonly value: string; + /** Degrees counterclockwise. */ + readonly rotation: number; + /** The width its lines wrap at. Missing, its lines break only at `\P`. */ + readonly width?: number; + /** A text style of the drawing. Defaults to `"Standard"`. */ + readonly style?: string; + /** Defaults to `"left"`. */ + readonly align?: ParagraphAlign; + /** Defaults to `"top"`. */ + readonly valign?: ParagraphVerticalAlign; + /** A factor of the spacing of its lines, from 0.25 to 4. Defaults to 1. */ + readonly lineSpacing?: number; + /** Defaults to `"at-least"`. */ + readonly lineSpacingStyle?: LineSpacingStyle; +} + /** * A block placed at a point. It draws the block's entities there, scaled and turned about the * block's base point, and carries a value for each of the block's attribute definitions. An @@ -541,6 +593,7 @@ export type Entity = | Circle | Arc | Text + | Paragraph | Insert | LinearDimension | AlignedDimension @@ -1179,6 +1232,50 @@ interface TextPlacement { readonly valign?: V extends "R12" ? "baseline" | R12Text : TextVerticalAlign; } +/** + * The options of `paragraph()`: where its box is, its width, height, rotation, style, + * justification and line spacing, and the options of every entity. + * + * @typeParam N - The width as written. + * @typeParam F - The line spacing factor as written. + */ +export type ParagraphOptions< + H extends number = number, + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + S extends string = string, + D extends TextStyleValue = TextStyleDefinition, + Z extends Standard | undefined = undefined, + P extends string = string, + R extends string = string, + N extends number = number, + F extends number = number, +> = EntityOptions<"R2018", T, W, L, I, Z, P> & + ParagraphPlacement & + Sized, TextStyleChoice>; + +/** Where a paragraph is, how wide, turned and justified, how its lines are spaced, and the view it is read in. */ +interface ParagraphPlacement { + /** The point of the paragraph's box `align` and `valign` name. */ + readonly at: Point; + /** The width its lines wrap at. Missing, its lines break only at a line feed. */ + readonly width?: Positive; + /** Degrees counterclockwise. */ + readonly rotation?: number; + /** In model space, the view a paragraph with a role is read in, which `view()` returns. */ + readonly view?: Z extends Standard ? View : ViewWithoutStandard; + /** Where `at` is across the box, and how the lines are set in it. Defaults to `"left"`. */ + readonly align?: ParagraphAlign; + /** Where `at` is up and down the box. Defaults to `"top"`. */ + readonly valign?: ParagraphVerticalAlign; + /** A factor of the spacing of its lines, from 0.25 to 4. Defaults to 1. */ + readonly lineSpacing?: LineSpacing; + /** Defaults to `"at-least"`. */ + readonly lineSpacingStyle?: LineSpacingStyle; +} + /** * The role, height and style of a text or an attribute, where `Height` and `Style` are what it * takes without a standard. Under a standard a text names a role, which gives its height and its @@ -2492,6 +2589,116 @@ export class DrawingBuilder< })); } + /** + * Paragraph text: one entity whose lines wrap at `width` and break at each line feed, held as + * the leading CAD app's multi-line text. Its box is placed by `at`, which `align` and `valign` + * name a point of, its upper left corner by default. The value may hold that app's inline + * codes, which `underline`, `bold`, `stack`, `superscript`, `subscript` and `plain` write, and + * a line feed in it is written as `\P`. R2018 only. + * + * ```ts + * d.paragraph(`GENERAL NOTES\n1. ALL WORK SHALL COMPLY WITH ${underline("THE CODES")}.`, { + * at: [1, 10], + * width: 4, + * height: 0.1, + * }); + * ``` + */ + paragraph< + Q extends string, + H extends number = number, + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + S extends string = string, + const D extends TextStyleValue = TextStyleDefinition, + P extends string = string, + R extends string = string, + N extends number = number, + F extends number = number, + >( + value: ParagraphValue, + options: V extends "R12" ? R12Paragraphs : ParagraphOptions, + ): this { + const o = options as unknown as ParagraphOptions; + return this.#add(DrawingBuilder.prototype.paragraph, o, () => { + if (this.dxf === "R12") refuse("paragraph", R12_ONLY.paragraphs); + return this.#paragraph(value, o); + }); + } + + /** Checks a paragraph and returns it on the current layer. */ + #paragraph(given: unknown, o: ParagraphOptions): Paragraph { + if (typeof given !== "string") + return refuse("paragraph", "A paragraph's value must be a string"); + // A backslash would escape the `\` of the `\P` a line feed becomes, as the type refuses it. + let backslashes = 0; + for (let i = 0; i < given.length; i++) { + const code = given.charCodeAt(i); + if (code === 92) backslashes++; + else { + if (code === 10 && backslashes % 2 === 1) { + return refuse("paragraph", paragraphUnknownCode("\n")); + } + backslashes = 0; + } + } + const value = given.replaceAll("\n", "\\P"); + const parsed = parseParagraph(value); + if (parsed.problem) refuse("paragraph", parsed.problem); + const at: unknown = o?.at; + if (!Array.isArray(at) || at.length !== 2) { + return refuse("geometry", "at must be a point, [x, y], of the paragraph's box"); + } + const role = this.#role(o as unknown as TextOptions); + const paragraph: { -readonly [K in keyof Paragraph]?: Paragraph[K] } & Pick< + Paragraph, + "kind" | "layer" | "at" | "value" | "height" | "rotation" + > = { + kind: "paragraph", + layer: this.#current, + at: pt(at as unknown as Point), + value, + height: positive(role ? role.height : (o.height ?? 0.125), "height"), + rotation: kept(o.rotation ?? 0, "rotation"), + }; + if (o.width !== undefined) paragraph.width = positive(o.width, "width"); + if (role) paragraph.style = role.style; + else if (o.style !== undefined) { + const style = this.#textStyleName(o.style); + if (style !== STANDARD_TEXT_STYLE) paragraph.style = style; + } + // A value is checked in its style's font, which decides what `%%c` draws. + const font = + paragraph.style === undefined + ? STANDARD_FONT + : (this.#textStyles.get(layerKey(paragraph.style))?.font ?? STANDARD_FONT); + const problem = paragraphProblemIn(parsed, font); + if (problem) refuse("paragraph", problem); + const { align, valign, lineSpacing, lineSpacingStyle } = o as unknown as Record< + string, + unknown + >; + for (const [field, chosen, plain] of [ + ["align", align, "left"], + ["valign", valign, "top"], + ["lineSpacingStyle", lineSpacingStyle, "at-least"], + ] as const) { + if (chosen === undefined) continue; + const choiceProblem = paragraphChoiceProblem(field, chosen); + if (choiceProblem) + refuse(field === "lineSpacingStyle" ? "paragraph" : "text-align", choiceProblem); + if (chosen !== plain) (paragraph as Record)[field] = chosen; + } + if (lineSpacing !== undefined) { + const spacingProblem = lineSpacingProblem(lineSpacing); + if (spacingProblem) refuse("paragraph", spacingProblem); + if (lineSpacing !== 1) paragraph.lineSpacing = lineSpacing as number; + } + return paragraph as Paragraph; + } + /** * Defines a block: what `draw` draws goes in the block and not in the drawing, in the * block's own coordinates, and `insert` then places it. Inside `draw` the current layer @@ -3822,7 +4029,7 @@ export class DrawingBuilder< const styles = new Set(); for (const block of closure) { for (const e of block.entities) - if (e.kind === "text" && e.style) styles.add(layerKey(e.style)); + if ((e.kind === "text" || e.kind === "paragraph") && e.style) styles.add(layerKey(e.style)); for (const a of block.attributes ?? []) if (a.style) styles.add(layerKey(a.style)); } // Every refusal comes before the drawing takes a text style, block, id or handle, and @@ -4213,7 +4420,9 @@ export class DrawingBuilder< /** True for a text with a role, and for an insert of a block that holds one. */ #drawsRoles(made: Entity, options: object): boolean { - if (made.kind === "text") return (options as { readonly role?: unknown }).role !== undefined; + if (made.kind === "text" || made.kind === "paragraph") { + return (options as { readonly role?: unknown }).role !== undefined; + } return made.kind === "insert" && this.#roleBlocks.has(layerKey(made.block)); } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 2a9c90f..6549379 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -61,8 +61,9 @@ import { } from "./papers.ts"; import { fontInfo, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { ID_HANDLE_SEED, validIdHandle } from "./handles.ts"; -import { dxfOnce, dxfText, fmt, readable, written, writtenAngle } from "./format.ts"; +import { dxfOnce, dxfText, fifteenDigits, fmt, readable, written, writtenAngle } from "./format.ts"; import { layerKey, layerZeroFirst } from "./layers.ts"; +import { lineSpacingStyleCode, paragraphAttachment, paragraphDirection } from "./paragraphs.ts"; import { attachmentCode, LEADER_STYLE_DICTIONARY, @@ -464,7 +465,7 @@ export function toDXFR2018( entity, own, owner, - entity.kind === "text" ? styleOf(entity.style) : undefined, + entity.kind === "text" || entity.kind === "paragraph" ? styleOf(entity.style) : undefined, paper, ); return; @@ -1017,6 +1018,26 @@ function writeEntity( g(50, writtenAngle(e.startAngle)); g(51, writtenAngle(e.endAngle)); return; + case "paragraph": { + begin("MTEXT", "AcDbMText"); + point(g, 10, ...e.at); + g(40, e.height); + g(41, e.width ?? 0); // the width its lines wrap at, or 0 for none + g(46, 0); // no height of its own + g(71, paragraphAttachment(e)); + g(72, 1); // left to right + writeMtextValue(g, e.value); + g(7, style?.name ?? STANDARD_TEXT_STYLE); + const [cos, sin] = paragraphDirection(e.rotation); + if (cos !== 1 || sin !== 0) { + g(11, fifteenDigits(cos)); + g(21, fifteenDigits(sin)); + g(31, 0); + } + g(73, lineSpacingStyleCode(e)); + g(44, e.lineSpacing ?? 1); + return; + } case "text": begin("TEXT", "AcDbText"); writeTextFields(g, e, style, undefined); @@ -1200,15 +1221,7 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi g(71, 5); // placed by its middle g(72, 1); // left to right // The leading CAD app writes the text with a code that centers what is stacked in it. - const text = dxfOnce(`\\A1;${label.value}`); - let at = 0; - while (text.length - at > TEXT_CHUNK) { - // A caret and what it escapes stay in one group. - const end = text[at + TEXT_CHUNK - 1] === "^" ? at + TEXT_CHUNK - 1 : at + TEXT_CHUNK; - g(3, text.slice(at, end)); - at = end; - } - g(1, text.slice(at)); + writeMtextValue(g, `\\A1;${label.value}`); g(7, textStyle); if (written(label.rotation) !== 0) { // 15 digits of the direction: 6 decimals would turn the text off the leading CAD app's own. @@ -1222,6 +1235,22 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi }); } +/** + * Writes the value of an MTEXT, which the leading CAD app decodes once: in groups 3 of + * `TEXT_CHUNK` characters, and the rest in group 1. + */ +function writeMtextValue(g: Group, value: string): void { + const text = dxfOnce(value); + let at = 0; + while (text.length - at > TEXT_CHUNK) { + // A caret and what it escapes stay in one group. + const end = text[at + TEXT_CHUNK - 1] === "^" ? at + TEXT_CHUNK - 1 : at + TEXT_CHUNK; + g(3, text.slice(at, end)); + at = end; + } + g(1, text.slice(at)); +} + /** What a dimension reads, as the DXF writes it: the length times the style's measurement scale. */ function measurementValue(dimension: Dimension, style: DimensionStyle): string { return fifteenDigits( @@ -1229,17 +1258,6 @@ function measurementValue(dimension: Dimension, style: DimensionStyle): string { ); } -/** - * A number with 15 significant digits and no exponent, which JavaScript writes for a number - * under a millionth. Summed as a whole number, 15 digits stay under 2^53, so the double - * the leading CAD app reads from them can be worked out exactly, where a 16th may move it a unit in - * the last place. - */ -function fifteenDigits(value: number): string { - const kept = Number(value.toPrecision(15)); - return Math.abs(kept) < 1e-6 ? kept.toFixed(20) : String(kept); -} - /** A layout with what the writer works out for it once. */ interface Sheet { readonly layout: Layout; diff --git a/src/extents.ts b/src/extents.ts index fadb720..b4be151 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -27,6 +27,7 @@ import { layerKey, layerKeys } from "./layers.ts"; import { hasArcsOrWidths, mayCurve, polylineBox, PolylineMemo } from "./polylines.ts"; import { leaderPicture, leaderRepeats } from "./leaders.ts"; import { inStyle, measurer } from "./measure.ts"; +import { paragraphInStyle, paragraphMeasurer } from "./paragraphs.ts"; import { filled } from "./shape.ts"; type Bounds = [number, number, number, number]; @@ -63,7 +64,8 @@ const LONG = 256; * Approximate extents. Arcs use their full circle, and a polyline counts for its points, the * arcs of its sides and its wide sides with their joins. A text counts for the box `measureText` * gives it, its capitals as long as the text plots, justified, turned and leaned as it is, - * and for what its font draws below the baseline. An insert counts for the box of what its block + * and for what its font draws below the baseline, and a paragraph for the box of all it draws, + * as `measureParagraph` gives it. An insert counts for the box of what its block * draws, in the block's coordinates, where the insert puts the box's corners, so a turned insert * may count for more than it draws. An insert of an xref counts for the drawing given for it in * `xrefs`, and for nothing without one. A dimension counts for its lines, its arrowheads and its @@ -199,6 +201,7 @@ export function boxer( ): Boxer { const key = layerKeys(); const { measure, again: readAgain } = measurer(); + const paragraphs = paragraphMeasurer(); interface Names { readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; @@ -288,6 +291,15 @@ export function boxer( add(c1[0] - (c2[0] - c1[0]) * below, c1[1] - (c2[1] - c1[1]) * below); break; } + case "paragraph": { + const style = e.style === undefined ? undefined : from.textStyles.get(key(e.style)); + const paragraph = paragraphInStyle(e, style); + // A long value laid out again is paid for first; a box already kept is mapped alone. + const again = paragraphs.boxAgain(paragraph); + if (again > 0 && !spend(again)) break; + for (const [x, y] of paragraphs.box(paragraph) ?? []) add(x, y); + break; + } case "linear-dimension": case "aligned-dimension": dimension(e, from, add); diff --git a/src/font-metrics.ts b/src/font-metrics.ts index 65c4526..b23bbe0 100644 --- a/src/font-metrics.ts +++ b/src/font-metrics.ts @@ -14,6 +14,46 @@ export interface FontMetrics { readonly tails: readonly number[]; /** Where the first character of a text starts to draw, from the text's first point. */ readonly heads: readonly number[]; + /** + * Where a line of paragraph text that starts with the character starts to draw, from the + * character's first point: the left of its ink, and never before that point. 0 for a space. + */ + readonly lefts: readonly number[]; + /** + * Where the character's ink ends, from its first point: past its advance for a letter that + * overhangs it. A space's is its advance. + */ + readonly rights: readonly number[]; + /** + * How far above the baseline the character raises a line of paragraph text: the top of its + * ink, and never less than 1. A mark that lies wholly above the baseline in a TrueType font, + * such as a degree sign, raises the line by 1. + */ + readonly tops: readonly number[]; + /** + * Where the bottom of a paragraph's box lies, from the baseline, when the character is in the + * paragraph's last line: the bottom of its ink, and never above the baseline. + */ + readonly bottoms: readonly number[]; + /** + * How far past the end of a stacked fraction's ink the next character's first point lies, for + * a stack of height 1. + */ + readonly afterStack: number; + /** For a TrueType font, its bold face. */ + readonly bold?: FontFace; +} + +/** + * A face of a font: its own advances and ink, as `FontMetrics` holds the regular face's, for + * the face drawn so that its own capital A is as tall as the text's height. + */ +export interface FontFace { + readonly advances: readonly number[]; + readonly lefts: readonly number[]; + readonly rights: readonly number[]; + readonly tops: readonly number[]; + readonly bottoms: readonly number[]; } /** The first and last character of each run the tables hold, in order. */ @@ -90,6 +130,71 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0.05047748977, 0, 0.12824010914, 0, 0.04160982265, 0.00204638472, 0, 0, + 0.07776261937, 0.04433833561, 0.00204638472, 0, 0, 0, 0.1, 0.1, 0.1514324693, 0, + 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, 0, 0, 0, 0, 0.02251023192, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + ], + rights: [ + 1, 0, 0.33333333333, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.16666666667, 0.33333333333, 0.33333333333, 0.66666666667, 0.66666666667, 0.16666666667, + 0.66666666667, 0, 0.66666666667, 0.5, 0.33333333333, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0, + 0.16666666667, 0.5, 0.66666666667, 0.5, 0.5, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.33333333333, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 1, 1, 0.66666666667, 0.66666666667, 0.66666666667, 0.33333333333, + 0.66666666667, 0.33333333333, 0.66666666667, 0.66666666667, 0.16666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0, 0.5, 0.66666666667, 0.16666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.33333333333, 0, 0.33333333333, 0.66666666667, 1, 0, 0.66666666667, 0.66666666667, + 0.7210095498, 0.66666666667, 0.23533424284, 0.5, 0.42428376535, 1.03137789904, 0.33333333333, + 0.66666666667, 0.7380627558, 0.42155525239, 1.03137789905, 0.79263301501, 0.33333333333, + 0.66666666667, 0.5, 0.45, 0.4031377899, 0.66666666667, 0.7551159618, 0.30218281037, + 0.36834924966, 0.32469304229, 0.33333333333, 0.66666666667, 0.83333333333, 0.83333333333, + 1.1446111869, 0.5, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.33333333333, 0.33333333333, 0.33333333333, 0.33333333333, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.70463847203, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.33333333333, 0.33333333333, 0.33333333333, + 0.33333333333, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + ], + tops: [ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, -0.29399727149, 0, 0, + -0.01227830832, 0, 0, 0, 0, -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, + 0, -0.28717598909, 0, 0, 0, 0, 0, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, + 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, -0.33333333333, + ], + afterStack: 0.33333333333, }, "monotxt.shx": { below: 0.33333333333, @@ -147,6 +252,72 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0.16666666667, 0.16666666667, 0.16666666667, 0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.33333333333, 0, 0, 0.33333333333, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0.33333333333, 0.33333333333, 0, 0, 0, 0, 0, + 0.05047748977, 0, 0.12824010914, 0, 0.04160982265, 0.00204638472, 0.16666666667, 0, + 0.07776261937, 0.04433833561, 0.00204638472, 0, 0, 0, 0.1, 0.1, 0.1514324693, 0, + 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, 0.16666666667, 0, 0, 0, + 0.02251023192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0.16666666667, + 0.16666666667, 0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0.16666666667, 0.16666666667, 0.16666666667, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ], + rights: [ + 1, 0, 0.33333333333, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.16666666667, 0.33333333333, 0.33333333333, 0.66666666667, 0.66666666667, 0.16666666667, + 0.66666666667, 0, 0.66666666667, 0.66666666667, 0.5, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0, + 0.16666666667, 0.5, 0.66666666667, 0.5, 0.5, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.5, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.33333333333, + 0.66666666667, 0.33333333333, 0.66666666667, 0.66666666667, 0.16666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.33333333333, 0.5, 0.66666666667, 0.5, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.5, + 0.33333333333, 0.66666666667, 0.66666666667, 1, 0, 0.66666666667, 0.66666666667, 0.7210095498, + 0.66666666667, 0.23533424284, 0.5, 0.42428376535, 1.03137789904, 0.5, 0.66666666667, + 0.7380627558, 0.42155525239, 1.03137789905, 0.79263301501, 0.33333333333, 0.66666666667, 0.5, + 0.45, 0.4031377899, 0.66666666667, 0.7551159618, 0.30218281037, 0.36834924966, 0.32469304229, + 0.5, 0.66666666667, 0.66666666667, 0.66666666667, 1.1446111869, 0.5, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.5, 0.5, 0.5, 0.5, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.70463847203, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.5, 0.5, 0.5, 0.5, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, + ], + tops: [ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, -0.29399727149, 0, 0, + -0.01227830832, 0, 0, 0, 0, -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, + 0, -0.28717598909, 0, 0, 0, 0, 0, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, + 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, -0.33333333333, + ], + afterStack: 0.33333333333, }, "simplex.shx": { below: 0.33333333333, @@ -231,6 +402,79 @@ export const FONT_METRICS: Readonly> = { -0.14285714286, -0.14285714286, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0.05047748977, 0, 0.12824010914, 0, 0.04160982265, 0.00204638472, 0, 0, + 0.07776261937, 0.04433833561, 0.00204638472, 0, 0, 0, 0, 0.1, 0.1514324693, 0, 0.00068212824, + 0.16234652115, 0.07298772169, 0.07298772169, 0, 0, 0, 0, 0.02251023192, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ], + rights: [ + 0.90476190476, 0.09523809524, 0.38095238095, 0.71428571429, 0.66666666667, 0.85714285714, + 0.95238095238, 0.09523809524, 0.33333333333, 0.33333333333, 0.47619047619, 0.85714285714, + 0.09523809524, 0.85714285714, 0.09523809524, 0.85714285714, 0.66666666667, 0.2380952381, + 0.66666666667, 0.66666666667, 0.71428571429, 0.66666666667, 0.61904761905, 0.66666666667, + 0.66666666667, 0.61904761905, 0.09523809524, 0.09523809524, 0.7619047619, 0.85714285714, + 0.7619047619, 0.52380952381, 1, 0.7619047619, 0.66666666667, 0.71428571429, 0.66666666667, + 0.61904761905, 0.61904761905, 0.71428571429, 0.66666666667, 0, 0.47619047619, 0.66666666667, + 0.57142857143, 0.7619047619, 0.66666666667, 0.7619047619, 0.66666666667, 0.7619047619, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.7619047619, 0.95238095238, + 0.66666666667, 0.7619047619, 0.66666666667, 0.33333333333, 0.85714285714, 0.33333333333, + 0.66666666667, 0.95238095238, 0.09523809524, 0.57142857143, 0.57142857143, 0.57142857143, + 0.57142857143, 0.57142857143, 0.38095238095, 0.57142857143, 0.52380952381, 0.09523809524, + 0.28571428571, 0.52380952381, 0, 1.04761904762, 0.52380952381, 0.61904761905, 0.57142857143, + 0.57142857143, 0.38095238095, 0.52380952381, 0.38095238095, 0.52380952381, 0.57142857143, + 0.7619047619, 0.52380952381, 0.61904761905, 0.52380952381, 0.2380952381, 0, 0.2380952381, + 0.85714285714, 0.90476190476, 0.09523809524, 0.57142857143, 0.66666666667, 0.7210095498, + 0.7619047619, 0.23533424284, 0.66666666667, 0.42428376535, 1.03137789904, 0.2380952381, + 0.57142857143, 0.7380627558, 0.42155525239, 1.03137789905, 0.79263301501, 0.19047619048, + 0.85714285714, 0.33333333333, 0.45, 0.4031377899, 0.7619047619, 0.7551159618, 0.30218281037, + 0.36834924966, 0.32469304229, 0.2380952381, 0.57142857143, 0.95238095238, 0.95238095238, + 1.1446111869, 0.52380952381, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, + 0.76190476191, 0.76190476191, 0.76190476191, 0.71428571429, 0.61904761905, 0.61904761905, + 0.61904761905, 0.61904761905, 0, 0.09523809524, 0.09523809524, 0.14285714286, 0.66666666667, + 0.66666666667, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, + 0.70463847203, 0.76190476191, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.76190476191, 0.57142857143, 0.57142857143, 0.57142857143, 0.57142857143, 0.57142857143, + 0.57142857143, 0.57142857143, 0.57142857143, 0.66666666667, 0.57142857143, 0.57142857143, + 0.57142857143, 0.57142857143, 0.57142857143, 0.38095238095, 0.38095238095, 0.38095238095, + 0.38095238095, 0.61904761905, 0.52380952381, 0.61904761905, 0.61904761905, 0.61904761905, + 0.61904761905, 0.61904761905, 0.57142857143, 0.61904761905, 0.52380952381, 0.52380952381, + 0.52380952381, 0.52380952381, 0.61904761905, 0.66666666667, 0.61904761905, + ], + tops: [ + 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, + 1, 1, 1, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, + 1, 1, 1.017053206, 1.19047619048, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1.25, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.017053206, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.04761904762, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, + -0.19047619048, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.19047619048, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, + 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, 0, 0, + -0.14285714286, 0, 0, 0, -0.29399727149, -0.19047619048, 0, -0.01227830832, 0, 0, 0, 0, + -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, 0, -0.28717598909, 0, 0, 0, + -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, -0.33333333333, + ], + afterStack: 0.28571428571, }, "romans.shx": { below: 0.33333333333, @@ -339,6 +583,103 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.04761904762, 0.14285714286, 0.04761904762, ], + lefts: [ + 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, + 0.19047619048, 0.19047619048, 0.09523809524, 0.14285714286, 0.28571428571, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, 0.14285714286, + 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, + 0.14285714286, 0.14285714286, 0.04761904762, 0.19047619048, 0.14285714286, 0.19047619048, + 0.19047619048, 0.19047619048, 0.14285714286, 0.19047619048, 0.19047619048, 0.09523809524, + 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.14285714286, 0.19047619048, + 0.14285714286, 0.19047619048, 0.14285714286, 0.04761904762, 0.19047619048, 0.04761904762, + 0.09523809524, 0.14285714286, 0.04761904762, 0.14285714286, 0.19047619048, 0.09523809524, + 0.09523809524, 0.14285714286, 0.09523809524, 0.19047619048, 0.14285714286, 0.19047619048, + 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.14285714286, 0.19047619048, + 0.14285714286, 0.04761904762, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, + 0.14285714286, 0.19047619048, 0.14285714286, 0.19047619048, 0.14285714286, 0.09523809524, + 0.19047619048, 0.09523809524, 0.14285714286, 0.14285714286, 0.04761904762, 0.14285714286, + 0.19047619048, 0.19047619048, 0.2380952381, 0.19047619048, 0, 0.19047619048, 0.14285714286, + 0.14285714286, 0.05047748977, 0.04761904762, 0.12824010914, 0.14285714286, 0.04160982265, + 0.00204638472, 0.19047619048, 0.14285714286, 0.07776261937, 0.04433833561, 0.00204638472, 0, + 0.04761904762, 0.19047619048, 0.09523809524, 0.1, 0.1514324693, 0, 0.00068212824, + 0.16234652115, 0.07298772169, 0.07298772169, 0.19047619048, 0.14285714286, 0.19047619048, + 0.19047619048, 0.02251023192, 0.14285714286, 0.04761904762, 0.04761904762, 0.04761904762, + 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0.14285714286, 0.19047619048, + 0.19047619048, 0.19047619048, 0.19047619048, 0.09523809524, 0.19047619048, 0.09523809524, + 0.04761904762, 0, 0.19047619048, 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, + 0.14285714286, 0.10982264666, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, + 0.19047619048, 0.04761904762, 0.10777626194, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.04979536153, 0.19047619048, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, + 0.19047619048, 0.19047619048, 0.19047619048, 0.04761904762, 0.09208731242, 0.04761904762, + ], + rights: [ + 1, 0.28571428571, 0.57142857143, 0.85714285714, 0.80952380952, 1, 1.09523809524, + 0.28571428571, 0.52380952381, 0.47619047619, 0.61904761905, 1.04761904762, 0.28571428571, + 1.04761904762, 0.28571428571, 0.95238095238, 0.80952380952, 0.52380952381, 0.80952380952, + 0.80952380952, 0.85714285714, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, + 0.7619047619, 0.28571428571, 0.28571428571, 0.95238095238, 1.04761904762, 0.95238095238, + 0.71428571429, 1.14285714286, 0.80952380952, 0.85714285714, 0.85714285714, 0.85714285714, + 0.80952380952, 0.80952380952, 0.85714285714, 0.85714285714, 0.19047619048, 0.57142857143, + 0.85714285714, 0.7619047619, 0.95238095238, 0.85714285714, 0.90476190476, 0.85714285714, + 0.90476190476, 0.85714285714, 0.80952380952, 0.71428571429, 0.85714285714, 0.80952380952, + 1.04761904762, 0.80952380952, 0.80952380952, 0.80952380952, 0.52380952381, 0.95238095238, + 0.42857142857, 0.90476190476, 1.04761904762, 0.28571428571, 0.71428571429, 0.7619047619, + 0.71428571429, 0.71428571429, 0.71428571429, 0.47619047619, 0.71428571429, 0.71428571429, + 0.2380952381, 0.33333333333, 0.71428571429, 0.19047619048, 1.2380952381, 0.71428571429, + 0.7619047619, 0.7619047619, 0.71428571429, 0.57142857143, 0.66666666667, 0.47619047619, + 0.71428571429, 0.66666666667, 0.90476190476, 0.66666666667, 0.66666666667, 0.66666666667, + 0.42857142857, 0.19047619048, 0.47619047619, 1.04761904762, 1, 0.28571428571, 0.71428571429, + 0.80952380952, 0.7210095498, 0.80952380952, 0.23533424284, 0.80952380952, 0.42428376535, + 1.03137789904, 0.42857142857, 0.71428571429, 0.7380627558, 0.42155525239, 1.03137789905, + 0.79263301501, 0.2380952381, 1.04761904762, 0.42857142857, 0.45, 0.4031377899, 0.7619047619, + 0.7551159618, 0.30218281037, 0.36834924966, 0.32469304229, 0.42857142857, 0.71428571429, + 1.14285714286, 1.14285714286, 1.1446111869, 0.66666666667, 0.80952380952, 0.80952380952, + 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.85714285714, + 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.19047619048, 0.28571428571, + 0.28571428571, 0.33333333333, 0.93451568895, 0.85714285714, 0.85714285714, 0.85714285714, + 0.85714285714, 0.90476190476, 0.90476190476, 0.70463847203, 0.90476190476, 0.85714285714, + 0.85714285714, 0.85714285714, 0.85714285714, 0.80952380952, 0.87107776262, 0.71428571429, + 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, + 0.80952380952, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, + 0.52380952381, 0.52380952381, 0.52380952381, 0.52380952381, 0.7210095498, 0.71428571429, + 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.71428571429, + 0.76190476191, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, 0.66666666667, + 0.7210095498, 0.66666666667, + ], + tops: [ + 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1, 1, 1, 1, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.19047619048, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1.19047619048, 1, 1.017053206, 1, 1, 1, 1, + 1.017053206, 1, 1, 1, 1.25, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.017053206, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, + -0.19047619048, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.19047619048, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, + 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, 0, 0, + -0.14285714286, 0, 0, 0, -0.29399727149, -0.19047619048, 0, -0.01227830832, 0, 0, 0, 0, + -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, 0, -0.28717598909, 0, 0, 0, + -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, -0.27762619372, -0.33333333333, + ], + afterStack: 0.14285714286, }, "romand.shx": { below: 0.33333333333, @@ -448,6 +789,101 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.09523809524, 0.14285714286, 0.09523809524, ], + lefts: [ + 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, + 0.19047619048, 0.19047619048, 0.09523809524, 0.14285714286, 0.28571428571, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, 0.14285714286, + 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, + 0.14285714286, 0.14285714286, 0.09523809524, 0.19047619048, 0.14285714286, 0.19047619048, + 0.19047619048, 0.19047619048, 0.14285714286, 0.19047619048, 0.19047619048, 0.14285714286, + 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.14285714286, 0.19047619048, + 0.14285714286, 0.19047619048, 0.14285714286, 0.09523809524, 0.19047619048, 0.09523809524, + 0.09523809524, 0.14285714286, 0.09523809524, 0.14285714286, 0.19047619048, 0, 0.14285714286, + 0.14285714286, 0.09523809524, 0.19047619048, 0.14285714286, 0.19047619048, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, 0, + 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.14285714286, 0.19047619048, + 0.14285714286, 0.19047619048, 0.14285714286, 0.09523809524, 0.19047619048, 0.09523809524, + 0.14285714286, 0.14285714286, 0.09523809524, 0.14285714286, 0.19047619048, 0.19047619048, + 0.2380952381, 0.19047619048, 0, 0.19047619048, 0.14285714286, 0.14285714286, 0.05047748977, + 0.09523809524, 0.12824010914, 0.14285714286, 0.04160982265, 0.00204638472, 0.19047619048, + 0.14285714286, 0.07776261937, 0.04433833561, 0.00204638472, 0, 0.04761904762, 0.19047619048, + 0.1, 0.1, 0.1514324693, 0, 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, + 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.02251023192, 0.14285714286, + 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, + 0.09523809524, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, + 0.04761904762, 0.19047619048, 0.04761904762, 0.04761904762, 0, 0.19047619048, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.10982264666, 0.14285714286, + 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.09523809524, 0.10777626194, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.14285714286, 0.04979536153, + 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, + 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, + 0.09523809524, 0.09208731242, 0.09523809524, + ], + rights: [ + 1, 0.33333333333, 0.66666666667, 0.92857142857, 0.7619047619, 1.04761904762, 1.04761904762, + 0.33333333333, 0.52380952381, 0.52380952381, 0.66666666667, 1, 0.33333333333, 1, + 0.33333333333, 1, 0.80952380952, 0.52380952381, 0.80952380952, 0.80952380952, 0.85714285714, + 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.7619047619, 0.33333333333, + 0.33333333333, 0.95238095238, 1, 0.95238095238, 0.7619047619, 1.14285714286, 0.85714285714, + 0.80952380952, 0.85714285714, 0.85714285714, 0.7619047619, 0.7619047619, 0.85714285714, + 0.85714285714, 0.2380952381, 0.61904761905, 0.85714285714, 0.7619047619, 0.95238095238, + 0.85714285714, 0.90476190476, 0.80952380952, 0.90476190476, 0.80952380952, 0.80952380952, + 0.71428571429, 0.85714285714, 0.85714285714, 1.14285714286, 0.80952380952, 0.80952380952, + 0.80952380952, 0.52380952381, 0.90476190476, 0.47619047619, 0.90476190476, 1.04761904762, + 0.33333333333, 0.7619047619, 0.80952380952, 0.71428571429, 0.7619047619, 0.71428571429, + 0.52380952381, 0.7619047619, 0.7619047619, 0.28571428571, 0.28571428571, 0.7619047619, + 0.2380952381, 1.28571428571, 0.7619047619, 0.7619047619, 0.80952380952, 0.7619047619, + 0.61904761905, 0.66666666667, 0.42857142857, 0.7619047619, 0.66666666667, 1, 0.71428571429, + 0.66666666667, 0.71428571429, 0.42857142857, 0.2380952381, 0.47619047619, 1.09523809524, 1, + 0.33333333333, 0.71428571429, 0.80952380952, 0.7210095498, 0.80952380952, 0.23533424284, + 0.80952380952, 0.42428376535, 1.03137789904, 0.45238095238, 0.71428571429, 0.7380627558, + 0.42155525239, 1.03137789905, 0.79263301501, 0.33333333333, 1, 0.5, 0.45, 0.4031377899, + 0.7619047619, 0.7551159618, 0.30218281037, 0.36834924966, 0.32469304229, 0.45238095238, + 0.7619047619, 1.09523809524, 1.09523809524, 1.1446111869, 0.76190476191, 0.85714285714, + 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, + 0.85714285714, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.2380952381, + 0.38095238095, 0.38095238095, 0.38095238095, 0.93451568895, 0.85714285714, 0.90476190476, + 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.70463847203, 0.90476190476, + 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, 0.80952380952, 0.87107776262, + 0.71428571429, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, + 0.76190476191, 1.09523809524, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, + 0.71428571429, 0.57142857143, 0.57142857143, 0.57142857143, 0.61904761905, 0.7210095498, + 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.80952380952, 0.76190476191, + 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, + 0.66666666667, 0.7210095498, 0.66666666667, + ], + tops: [ + 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, + 1, 1, 1, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, + 1, 1, 1.017053206, 1.19047619048, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.017053206, 1, 1.2380952381, 1.2380952381, + 1.2380952381, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1.2380952381, 1.2380952381, 1.2380952381, 1.2380952381, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.14285714286, 1.19047619048, 1, + 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.2380952381, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, + -0.19047619048, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.19047619048, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, -0.14285714286, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, + 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, 0, 0, + -0.14285714286, 0, 0, 0, -0.29399727149, -0.19047619048, 0, -0.01227830832, 0, 0, 0, 0, + -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, 0, -0.28717598909, 0, 0, 0, + -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, -0.27762619372, -0.33333333333, + ], + afterStack: 0.14285714286, }, "romanc.shx": { below: 0.33333333333, @@ -557,6 +993,102 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, 0.09523809524, ], + lefts: [ + 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, + 0.19047619048, 0.19047619048, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, + 0.14285714286, 0.14285714286, 0.04761904762, 0.09523809524, 0.14285714286, 0.09523809524, + 0.09523809524, 0.09523809524, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, + 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, 0.09523809524, + 0.14285714286, 0.09523809524, 0.14285714286, 0.09523809524, 0.09523809524, 0.04761904762, + 0.04761904762, 0.04761904762, 0.04761904762, 0.14285714286, 0.19047619048, 0.09523809524, + 0.14285714286, 0.14285714286, 0.09523809524, 0.19047619048, 0.14285714286, 0.09523809524, + 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, + 0.09523809524, 0.04761904762, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, + 0.14285714286, 0.09523809524, 0.14285714286, 0.09523809524, 0.14285714286, 0.09523809524, + 0.09523809524, 0.04761904762, 0.04761904762, 0.09523809524, 0.09523809524, 0.14285714286, + 0.19047619048, 0.19047619048, 0.2380952381, 0, 0, 0.19047619048, 0.14285714286, 0.14285714286, + 0.05047748977, 0.04761904762, 0.12824010914, 0.14285714286, 0.04160982265, 0.00204638472, + 0.14285714286, 0.14285714286, 0.07776261937, 0.04433833561, 0.00204638472, 0, 0.04761904762, + 0.19047619048, 0.1, 0.1, 0.1514324693, 0.09523809524, 0.00068212824, 0.16234652115, + 0.07298772169, 0.07298772169, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, + 0.02251023192, 0.14285714286, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, + 0.04761904762, 0.04761904762, 0.04761904762, 0.14285714286, 0.09523809524, 0.09523809524, + 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0, + 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.10982264666, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, + 0.04761904762, 0.10777626194, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, + 0.09523809524, 0.04979536153, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, + 0.09523809524, 0.09523809524, 0.09523809524, 0.09208731242, 0.09523809524, + ], + rights: [ + 1, 0.28571428571, 0.57142857143, 0.85714285714, 0.80952380952, 1, 1.04761904762, + 0.28571428571, 0.52380952381, 0.47619047619, 0.61904761905, 1.04761904762, 0.28571428571, + 1.04761904762, 0.28571428571, 0.95238095238, 0.80952380952, 0.57142857143, 0.80952380952, + 0.80952380952, 0.85714285714, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, + 0.80952380952, 0.28571428571, 0.28571428571, 0.95238095238, 1.04761904762, 0.95238095238, + 0.71428571429, 1.14285714286, 0.90476190476, 0.90476190476, 0.85714285714, 0.90476190476, + 0.85714285714, 0.85714285714, 1, 1.04761904762, 0.42857142857, 0.61904761905, 1, + 0.80952380952, 1.09523809524, 1, 0.90476190476, 0.90476190476, 0.90476190476, 0.95238095238, + 0.80952380952, 0.80952380952, 1.04761904762, 0.90476190476, 1.09523809524, 0.90476190476, + 0.95238095238, 0.80952380952, 0.52380952381, 0.95238095238, 0.47619047619, 0.90476190476, + 1.04761904762, 0.28571428571, 0.85714285714, 0.85714285714, 0.7619047619, 0.90476190476, + 0.7619047619, 0.52380952381, 0.7619047619, 0.95238095238, 0.42857142857, 0.33333333333, + 0.90476190476, 0.42857142857, 1.47619047619, 0.95238095238, 0.80952380952, 0.85714285714, + 0.90476190476, 0.71428571429, 0.66666666667, 0.61904761905, 0.95238095238, 0.80952380952, + 1.09523809524, 0.85714285714, 0.85714285714, 0.71428571429, 0.42857142857, 0.19047619048, + 0.47619047619, 0.85714285714, 1, 0.28571428571, 0.7619047619, 0.85714285714, 0.7210095498, + 0.95238095238, 0.23533424284, 0.80952380952, 0.42428376535, 1.03137789904, 0.42857142857, + 0.71428571429, 0.7380627558, 0.42155525239, 1.03137789905, 0.79263301501, 0.38095238095, + 1.04761904762, 0.5, 0.45, 0.4031377899, 0.95238095238, 0.7551159618, 0.30218281037, + 0.36834924966, 0.32469304229, 0.42857142857, 0.71428571429, 1.19047619048, 1.2380952381, + 1.1446111869, 0.71428571429, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, + 0.90476190476, 0.90476190476, 0.90476190476, 0.85714285714, 0.85714285714, 0.85714285714, + 0.85714285714, 0.85714285714, 0.42857142857, 0.42857142857, 0.42857142857, 0.42857142857, + 0.93451568895, 1, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, + 0.70463847203, 0.90476190476, 1.04761904762, 1.04761904762, 1.04761904762, 1.04761904762, + 0.95238095238, 0.87107776262, 0.71428571429, 0.85714285714, 0.85714285714, 0.85714285714, + 0.85714285714, 0.85714285714, 0.85714285714, 1.04761904762, 0.76190476191, 0.76190476191, + 0.76190476191, 0.76190476191, 0.76190476191, 0.57142857143, 0.57142857143, 0.57142857143, + 0.57142857143, 0.7210095498, 0.95238095238, 0.80952380952, 0.80952380952, 0.80952380952, + 0.80952380952, 0.80952380952, 0.71428571429, 0.80952380952, 0.95238095238, 0.95238095238, + 0.95238095238, 0.95238095238, 0.85714285714, 0.7210095498, 0.85714285714, + ], + tops: [ + 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, + 1, 1, 1, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, + 1, 1, 1.017053206, 1.19047619048, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.017053206, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.2380952381, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, + -0.19047619048, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.19047619048, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2380952381, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, + 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, 0, 0, + -0.14285714286, 0, 0, 0, -0.29399727149, -0.19047619048, 0, -0.01227830832, 0, 0, 0, 0, + -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, 0, -0.28717598909, 0, 0, 0, + -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, -0.27762619372, -0.33333333333, + ], + afterStack: 0.14285714286, }, "romant.shx": { below: 0.33333333333, @@ -667,6 +1199,100 @@ export const FONT_METRICS: Readonly> = { 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, 0.04761904762, 0.14285714286, 0.04761904762, ], + lefts: [ + 0, 0.09523809524, 0.19047619048, 0.14285714286, 0.14285714286, 0.09523809524, 0.19047619048, + 0.19047619048, 0.14285714286, 0.19047619048, 0.14285714286, 0.19047619048, 0.19047619048, + 0.19047619048, 0.19047619048, 0.09523809524, 0.14285714286, 0.2380952381, 0.14285714286, + 0.14285714286, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, + 0.14285714286, 0.14285714286, 0.04761904762, 0.09523809524, 0.14285714286, 0.09523809524, + 0.09523809524, 0.09523809524, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, + 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, 0.09523809524, + 0.14285714286, 0.09523809524, 0.14285714286, 0.09523809524, 0.09523809524, 0.04761904762, + 0.04761904762, 0.04761904762, 0.04761904762, 0.14285714286, 0.19047619048, 0, 0.14285714286, + 0.14285714286, 0.09523809524, 0.19047619048, 0.14285714286, 0.09523809524, 0.14285714286, + 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, + 0.04761904762, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, + 0.09523809524, 0.14285714286, 0.09523809524, 0.14285714286, 0.09523809524, 0.09523809524, + 0.04761904762, 0.04761904762, 0.09523809524, 0.04761904762, 0.14285714286, 0.19047619048, + 0.19047619048, 0.2380952381, 0.19047619048, 0, 0.09523809524, 0.14285714286, 0.09523809524, + 0.05047748977, 0.04761904762, 0.12824010914, 0.14285714286, 0.04160982265, 0.00204638472, + 0.14285714286, 0.14285714286, 0.07776261937, 0.04433833561, 0.00204638472, 0, 0.04761904762, + 0.19047619048, 0.1, 0.1, 0.1514324693, 0, 0.00068212824, 0.16234652115, 0.07298772169, + 0.07298772169, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.02251023192, + 0.14285714286, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, + 0.04761904762, 0.04761904762, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, + 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0, 0.09523809524, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.10982264666, + 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.04761904762, + 0.10777626194, 0.04761904762, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, + 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, + 0.04979536153, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, + 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, + 0.14285714286, 0.04761904762, 0.09208731242, 0.04761904762, + ], + rights: [ + 1, 0.2380952381, 0.66666666667, 0.92857142857, 0.80952380952, 1.09523809524, 1.09523809524, + 0.33333333333, 0.47619047619, 0.52380952381, 0.61904761905, 1, 0.33333333333, 1, + 0.33333333333, 1, 0.80952380952, 0.71428571429, 0.80952380952, 0.80952380952, 0.85714285714, + 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.33333333333, + 0.33333333333, 0.95238095238, 1, 0.95238095238, 0.7619047619, 1.14285714286, 0.90476190476, + 0.90476190476, 0.85714285714, 0.90476190476, 0.85714285714, 0.85714285714, 1, 1.04761904762, + 0.47619047619, 0.66666666667, 1, 0.80952380952, 1.14285714286, 1.04761904762, 0.90476190476, + 0.90476190476, 0.90476190476, 0.95238095238, 0.80952380952, 0.85714285714, 1.04761904762, + 0.90476190476, 1.09523809524, 0.90476190476, 1, 0.80952380952, 0.52380952381, 0.90476190476, + 0.47619047619, 0.90476190476, 1.04761904762, 0.33333333333, 0.85714285714, 0.85714285714, + 0.7619047619, 0.90476190476, 0.7619047619, 0.61904761905, 0.80952380952, 1, 0.47619047619, + 0.42857142857, 0.95238095238, 0.47619047619, 1.52380952381, 1, 0.80952380952, 0.85714285714, + 0.90476190476, 0.71428571429, 0.66666666667, 0.66666666667, 1, 0.80952380952, 1.09523809524, + 0.85714285714, 0.85714285714, 0.71428571429, 0.42857142857, 0.2380952381, 0.47619047619, + 1.04761904762, 1, 0.2380952381, 0.7619047619, 0.7619047619, 0.7210095498, 1, 0.23533424284, + 0.80952380952, 0.42428376535, 1.03137789904, 0.42857142857, 0.71428571429, 0.7380627558, + 0.42155525239, 1.03137789905, 0.79263301501, 0.47619047619, 1, 0.5, 0.45, 0.4031377899, 1, + 0.7551159618, 0.30218281037, 0.36834924966, 0.32469304229, 0.42857142857, 0.7619047619, + 1.28571428571, 1.38095238095, 1.1446111869, 0.76190476191, 0.90476190476, 0.90476190476, + 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 1.04761904762, 0.85714285714, + 0.90476190476, 0.85714285714, 0.85714285714, 0.85714285714, 0.47619047619, 0.47619047619, + 0.47619047619, 0.47619047619, 0.93451568895, 1.04761904762, 0.90476190476, 0.90476190476, + 0.90476190476, 0.90476190476, 0.90476190476, 0.70463847203, 0.90476190476, 1.04761904762, + 1.04761904762, 1.04761904762, 1.04761904762, 1, 0.87107776262, 0.80952380952, 0.85714285714, + 0.85714285714, 0.90476190476, 0.90476190476, 0.85714285714, 0.85714285714, 1.09523809524, + 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.52380952381, + 0.52380952381, 0.47619047619, 0.52380952381, 0.7210095498, 1, 0.80952380952, 0.80952380952, + 0.80952380952, 0.80952380952, 0.80952380952, 0.76190476191, 0.80952380952, 1, 1, 1, + 1.04761904762, 0.85714285714, 0.7210095498, 0.85714285714, + ], + tops: [ + 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, + 1, 1, 1, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, + 1, 1, 1.017053206, 1.09523809524, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.017053206, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, + -0.19047619048, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.19047619048, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2380952381, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, -0.14285714286, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, + 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, 0, 0, + -0.14285714286, 0, 0, 0, -0.29399727149, -0.09523809524, 0, -0.01227830832, 0, 0, 0, 0, + -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, 0, -0.28717598909, 0, 0, 0, + -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, -0.27762619372, -0.33333333333, + ], + afterStack: 0.14285714286, }, "complex.shx": { below: 0.33333333333, @@ -747,6 +1373,80 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0.05047748977, 0, 0.12824010914, 0, 0.04160982265, 0.00204638472, 0, 0, + 0.07776261937, 0.04433833561, 0.00204638472, 0, 0, 0, 0.1, 0.1, 0.1514324693, 0, + 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, 0, 0, 0, 0, 0.02251023192, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + ], + rights: [ + 1, 0.09523809524, 0.38095238095, 0.71428571429, 0.66666666667, 0.85714285714, 0.90476190476, + 0.09523809524, 0.33333333333, 0.33333333333, 0.47619047619, 0.85714285714, 0.09523809524, + 0.85714285714, 0.09523809524, 0.85714285714, 0.66666666667, 0.42857142857, 0.66666666667, + 0.66666666667, 0.7619047619, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.09523809524, 0.09523809524, 0.7619047619, 0.85714285714, 0.7619047619, + 0.57142857143, 1, 0.85714285714, 0.80952380952, 0.71428571429, 0.80952380952, 0.7619047619, + 0.7619047619, 0.85714285714, 0.95238095238, 0.33333333333, 0.52380952381, 0.90476190476, + 0.71428571429, 1, 0.90476190476, 0.7619047619, 0.80952380952, 0.7619047619, 0.85714285714, + 0.66666666667, 0.71428571429, 0.95238095238, 0.85714285714, 1.04761904762, 0.85714285714, + 0.90476190476, 0.66666666667, 0.33333333333, 0.85714285714, 0.33333333333, 0.7619047619, + 0.95238095238, 0.09523809524, 0.71428571429, 0.7619047619, 0.61904761905, 0.7619047619, + 0.61904761905, 0.42857142857, 0.66666666667, 0.85714285714, 0.33333333333, 0.28571428571, + 0.80952380952, 0.33333333333, 1.38095238095, 0.85714285714, 0.66666666667, 0.7619047619, + 0.7619047619, 0.61904761905, 0.52380952381, 0.52380952381, 0.85714285714, 0.7619047619, + 1.04761904762, 0.7619047619, 0.7619047619, 0.57142857143, 0.2380952381, 0, 0.2380952381, + 0.85714285714, 1, 0.09523809524, 0.61904761905, 0.71428571429, 0.7210095498, 0.90476190476, + 0.23533424284, 0.66666666667, 0.42428376535, 1.03137789904, 0.28571428571, 0.57142857143, + 0.7380627558, 0.42155525239, 1.03137789905, 0.79263301501, 0.33333333333, 0.85714285714, 0.5, + 0.45, 0.4031377899, 0.95238095238, 0.7551159618, 0.30218281037, 0.36834924966, 0.32469304229, + 0.28571428571, 0.57142857143, 1, 1.04761904762, 1.1446111869, 0.57142857143, 0.85714285714, + 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, + 0.71428571429, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.33333333333, + 0.33333333333, 0.33333333333, 0.33333333333, 0.80952380952, 0.90476190476, 0.76190476191, + 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.70463847203, 0.76190476191, + 0.95238095238, 0.95238095238, 0.95238095238, 0.95238095238, 0.90476190476, 0.76190476191, + 0.57142857143, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, + 0.71428571429, 0.90476190476, 0.61904761905, 0.61904761905, 0.61904761905, 0.61904761905, + 0.61904761905, 0.47619047619, 0.47619047619, 0.47619047619, 0.47619047619, 0.66666666667, + 0.85714285714, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.57142857143, 0.66666666667, 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, + 0.76190476191, 0.80952380952, 0.76190476191, + ], + tops: [ + 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, + 1, 1, 1, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, + 1, 1, 1.017053206, 1.19047619048, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.017053206, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, + -0.19047619048, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.19047619048, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2380952381, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, 0, + 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, 0, 0, + -0.14285714286, 0, 0, 0, -0.29399727149, -0.19047619048, 0, -0.01227830832, 0, 0, 0, 0, + -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, 0, -0.28717598909, 0, 0, 0, + -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, -0.33333333333, + ], + afterStack: 0.28571428571, }, "italic.shx": { below: 0.33333333333, @@ -827,6 +1527,82 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0, 0, 0, 0, 0, 0, 0.2380952381, 0, 0, 0.04761904762, 0.09523809524, 0, 0, 0, 0, 0, + 0.04761904762, 0, 0, 0, 0, 0, 0.04761904762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0.04761904762, 0, 0.04761904762, 0, 0, 0.09523809524, 0.04761904762, + 0.14285714286, 0.09523809524, 0, 0.14285714286, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904762, 0, 0, + 0, 0, 0, 0, 0.04761904762, 0, 0.04761904762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0.05047748977, 0, 0.12824010914, 0.04761904762, 0.04160982265, + 0.00204638472, 0, 0, 0.07776261937, 0.04433833561, 0.00204638472, 0, 0, 0, 0.1, 0.1, + 0.1514324693, 0, 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, 0, 0, 0, 0, + 0.02251023192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904762, + 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0.10982264666, 0, 0.04761904762, + 0.04761904762, 0.04761904762, 0.04761904762, 0.14285714286, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + ], + rights: [ + 1, 0.33333333333, 0.52380952381, 0.71428571429, 0.80952380952, 0.85714285714, 1.04761904762, + 0.38095238095, 0.57142857143, 0.57142857143, 0.52380952381, 0.95238095238, 0.14285714286, + 0.85714285714, 0.09523809524, 1.2380952381, 0.71428571429, 0.42857142857, 0.80952380952, + 0.7619047619, 0.71428571429, 0.80952380952, 0.71428571429, 0.7619047619, 0.7619047619, + 0.71428571429, 0.2380952381, 0.28571428571, 0.90476190476, 1, 0.85714285714, 0.61904761905, 1, + 0.85714285714, 1, 0.80952380952, 0.95238095238, 1, 1, 0.80952380952, 1.2380952381, + 0.61904761905, 0.80952380952, 1.19047619048, 0.80952380952, 1.28571428571, 1.19047619048, + 0.80952380952, 1.04761904762, 0.80952380952, 1, 0.90476190476, 0.90476190476, 1.04761904762, + 1, 1.14285714286, 1.14285714286, 1.04761904762, 0.95238095238, 0.71428571429, 0.57142857143, + 0.71428571429, 0.7619047619, 0.95238095238, 0.09523809524, 0.80952380952, 0.61904761905, + 0.57142857143, 0.80952380952, 0.57142857143, 0.80952380952, 0.7619047619, 0.85714285714, + 0.57142857143, 0.57142857143, 0.7619047619, 0.33333333333, 1.47619047619, 1, 0.57142857143, + 0.90476190476, 0.66666666667, 0.71428571429, 0.61904761905, 0.42857142857, 1, 0.7619047619, + 1.19047619048, 0.7619047619, 0.85714285714, 0.66666666667, 0.57142857143, 0.38095238095, + 0.42857142857, 0.85714285714, 1, 0.33333333333, 0.57142857143, 0.71428571429, 0.7210095498, + 0.90476190476, 0.23533424284, 0.7619047619, 0.42428376535, 1.03137789904, 0.33333333333, + 0.66666666667, 0.7380627558, 0.42155525239, 1.03137789905, 0.79263301501, 0.33333333333, 1, + 0.5, 0.45, 0.4031377899, 1.09523809524, 0.7551159618, 0.30218281037, 0.36834924966, + 0.32469304229, 0.28571428571, 0.61904761905, 1.09523809524, 1.09523809524, 1.1446111869, + 0.61904761905, 0.85714285714, 1, 0.95238095238, 1, 1, 0.85714285714, 1.09523809524, + 0.80952380952, 0.95238095238, 0.95238095238, 1, 1, 0.61904761905, 0.66666666667, + 0.66666666667, 0.61904761905, 0.95238095238, 1.14285714286, 0.85714285714, 0.85714285714, + 0.85714285714, 0.80952380952, 0.90476190476, 0.70463847203, 0.76190476191, 1.04761904762, + 1.04761904762, 1.04761904762, 1.04761904762, 1.04761904762, 0.90476190476, 0.71428571429, + 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 1, + 0.57142857143, 0.57142857143, 0.66666666667, 0.61904761905, 0.71428571429, 0.57142857143, + 0.61904761905, 0.57142857143, 0.66666666667, 0.57142857143, 1, 0.57142857143, 0.66666666667, + 0.61904761905, 0.66666666667, 0.71428571429, 0.52380952381, 0.57142857143, 1, 1, 1, 1, + 0.85714285714, 0.97619047619, 0.85714285714, + ], + tops: [ + 1, 1, 1, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, + 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, + 1, 1, 1.017053206, 1.19047619048, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1.19047619048, 1.19047619048, 1.017053206, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + ], + bottoms: [ + 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, + -0.19047619048, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.19047619048, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2380952381, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.33333333333, -0.33333333333, -0.33333333333, 0, -0.09523809524, 0, 0, 0, 0, 0, 0, + -0.33333333333, -0.33333333333, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, -0.33333333333, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, -0.33333333333, + -0.28571428571, 0, 0, 0, -0.14285714286, 0, 0, 0, -0.29399727149, -0.19047619048, 0, + -0.01227830832, 0, 0, 0, 0, -0.01227830832, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, + 0, -0.28717598909, 0, 0, 0, -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, + 0, 0, -0.28571428571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.28571428571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, + ], + afterStack: 0.28571428571, }, "isocp.shx": { below: 0.3, @@ -882,6 +1658,67 @@ export const FONT_METRICS: Readonly> = { 0.11893398282, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.125, 0.11375631329, 0.11375631329, 0.11375631329, 0.11375631329, 0.15, 0.09142135624, 0.15, ], + lefts: [ + 0, 0.15, 0.15, 0.15, 0.1188976378, 0.15, 0.0912007874, 0.15, 0.15039370079, 0.15, 0.15, 0.15, + 0.15, 0.15, 0.15, 0.15, 0.14921259843, 0.15, 0.12460629921, 0.15, 0.15, 0.15, 0.09015748032, + 0.15, 0.15, 0.11207297426, 0.15, 0.15, 0.15, 0.15, 0.15, 0.1468503937, 0.07751262658, 0.15, + 0.15, 0.10340097423, 0.15, 0.15, 0.15, 0.0982233047, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, + 0.15, 0.15, 0.15, 0.15, 0.11039370079, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, + 0.15, 0.15, 0, 0.15, 0.15, 0.15, 0.11375631329, 0.11375631329, 0.11893398282, 0.15, + 0.11375631329, 0.15, 0.15, 0.15, 0.15, 0.12928932188, 0.15, 0.15, 0.15, 0.15, 0.11375631329, + 0.15, 0.11793307087, 0.15, 0.11375631329, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, + 0.15, 0, 0.15, 0.11375631329, 0.15, 0.15, 0.15, 0.15, 0.14182778634, 0.15, 0.15, 0.15, 0.15, + 0, 0, 0.15, 0.15, 0.15, 0.15, 0.13503937008, 0.15, 0.15, 0.11375631329, 0.15, 0.15, 0.15, + 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.10966535433, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, + 0.10340097423, 0.15, 0.15, 0.15, 0.15, 0.1, 0.1, 0.15, 0.1, 0.15, 0.15, 0.15, 0.15, 0.15, + 0.15, 0.15, 0.15, 0.1, 0.15, 0.15, 0.15, 0.15, 0.15, 0.06213203436, 0.11893398282, 0.15, 0.15, + 0.15, 0.15, 0.15, 0.15, 0.15, 0.11375631329, 0.11893398282, 0.11893398282, 0.11893398282, + 0.11893398282, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.125, + 0.11375631329, 0.11375631329, 0.11375631329, 0.11375631329, 0.15, 0.09142135624, 0.15, + ], + rights: [ + 0.4, 0.15, 0.45, 0.75, 0.5811023622, 0.95, 0.75, 0.2, 0.25, 0.24960629921, 0.55, 0.55, 0.2, + 0.55, 0.15, 0.55, 0.55078740157, 0.35, 0.61005905512, 0.59142135624, 0.65, 0.59142135624, + 0.59960629921, 0.55, 0.55, 0.621593479, 0.15, 0.2, 0.55, 0.55, 0.55, 0.59033464567, 0.95, + 0.75, 0.65, 0.55, 0.70695436483, 0.55, 0.55, 0.65, 0.65, 0.15, 0.49142135624, 0.655, 0.55, + 0.75, 0.65, 0.65, 0.65, 0.75, 0.65, 0.68960629921, 0.65, 0.65, 0.75, 0.95, 0.75, 0.75, 0.65, + 0.25, 0.55, 0.25, 0.45, 1.1, 0.35, 0.58624368671, 0.58624368671, 0.45, 0.55, 0.55, 0.45, + 0.58624368671, 0.58624368671, 0.15, 0.39142135624, 0.55, 0.25, 0.78624368671, 0.58624368671, + 0.55, 0.58624368671, 0.55, 0.45, 0.57600393701, 0.45, 0.55, 0.55, 0.75, 0.55, 0.55, 0.55, + 0.35, 0.15, 0.35, 0.55, 0.4, 0.15, 0.55, 0.78106601718, 0.77109784258, 0.75, 0.15, + 0.44182778634, 0.45, 0.75, 0.58624368671, 0.6, 0.3, 0.4, 0.75, 0.55, 0.45, 0.55, + 0.49320866142, 0.35, 0.35, 0.58624368671, 0.725, 0.2, 0.2, 0.3, 0.55, 0.6, 0.95, + 0.98968503937, 0.85, 0.5531496063, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.95, 0.55, 0.55, 0.55, + 0.55, 0.55, 0.35, 0.35, 0.45, 0.35, 0.75695436483, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 1.05, + 0.7, 0.65, 0.65, 0.65, 0.65, 0.75, 0.66213203436, 0.68106601718, 0.58624368671, 0.58624368671, + 0.58624368671, 0.58624368671, 0.58624368671, 0.58624368671, 0.75, 0.45, 0.55, 0.55, 0.55, + 0.55, 0.35, 0.35, 0.45, 0.45, 0.60098645289, 0.58624368671, 0.55, 0.55, 0.55, 0.55, 0.55, + 0.55, 0.575, 0.55, 0.55, 0.55, 0.55, 0.55, 0.49142135624, 0.55, + ], + tops: [ + 1, 1, 1, 1, 1, 1, 1, 1, 1.05, 1.05, 1, 1, 1, 1, 1, 1, 1, 1, 1.00019685039, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00695436483, 1, 1, 1.0017766953, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05, 1, 1.05, 1.35, 1, 1.35, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.06771653543, 1.5, 1.06771653543, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1.25, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.28631889764, 1.25, 1.35, 1, 1, 1, 1, 1.25, 1, + 1, 1.05, 1.05, 1.05, 1, 1.35, 1.35, 1.35, 1.34960629921, 1.25, 1.35, 1, 1, 1.35, 1.35, 1.35, + 1.25, 1.35, 1.35, 1.35, 1.25, 1.00695436483, 1.34960629921, 1.35, 1.35, 1.35, 1.34960629921, + 1.25, 1, 1, 1.35, 1.35, 1.35, 1.25, 1.35, 1, 1, 1.05, 1.05, 1.05, 1.04960629921, 1, 1.05, 1, + 1, 1.05, 1.05, 1.05, 1, 1.05, 1.05, 1.05, 1, 1, 1.04960629921, 1.05, 1.05, 1.05, + 1.04960629921, 1, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1, 1, + ], + bottoms: [ + 0, 0, 0, 0, 0, 0, -0.0093503937, 0, -0.05, -0.05, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, -0.15, 0, 0, 0, 0, -0.32248737342, 0, 0, 0, -0.00695436483, 0, 0, -0.0017766953, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.05, 0, -0.05, 0, -0.25, 0, 0, 0, + 0, 0, 0, 0, -0.28624368671, 0, 0, -0.29142135624, 0, 0, 0, 0, 0, -0.25, -0.25, 0, 0, 0, 0, 0, + 0, 0, -0.25, 0, -0.06771653543, -0.4, -0.06771653543, 0, 0, 0, -0.1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0, -0.15, 0, 0, 0, -0.05, -0.05, -0.05, 0, 0, 0, 0, 0, + 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, -0.00695436483, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, -0.25, 0, -0.25, + ], + afterStack: 0.14921259843, }, "isoct.shx": { below: 0.3, @@ -937,6 +1774,67 @@ export const FONT_METRICS: Readonly> = { 0.4, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.325, 0.31375631329, 0.31375631329, 0.31375631329, 0.31375631329, 0.35, 0.31642135624, 0.35, ], + lefts: [ + 0, 0.55, 0.4, 0.25, 0.3188976378, 0.15, 0.1912007874, 0.525, 0.50039370079, 0.5, 0.35, 0.35, + 0.525, 0.35, 0.55, 0.35, 0.34921259843, 0.45, 0.32460629921, 0.35, 0.3, 0.35, 0.29015748032, + 0.35, 0.35, 0.31207297426, 0.55, 0.525, 0.35, 0.35, 0.35, 0.3468503937, 0.07751262658, 0.25, + 0.3, 0.30340097423, 0.3, 0.35, 0.35, 0.2482233047, 0.3, 0.55, 0.4, 0.3, 0.35, 0.25, 0.3, 0.3, + 0.3, 0.3, 0.3, 0.26039370079, 0.3, 0.3, 0.25, 0.15, 0.25, 0.25, 0.3, 0.5, 0.35, 0.5, 0.4, 0, + 0.45, 0.35, 0.35, 0.36375631329, 0.31375631329, 0.31893398282, 0.4, 0.31375631329, 0.35, 0.55, + 0.45, 0.35, 0.47928932188, 0.25, 0.35, 0.35, 0.35, 0.31375631329, 0.4, 0.31793307087, 0.4, + 0.31375631329, 0.35, 0.25, 0.35, 0.35, 0.35, 0.45, 0.55, 0.45, 0.35, 0, 0.55, 0.31375631329, + 0.25, 0.25, 0.25, 0.55, 0.39182778634, 0.4, 0.25, 0.35, 0.325, 0, 0, 0.25, 0.35, 0.4, 0.35, + 0.38503937008, 0.45, 0.45, 0.31375631329, 0.275, 0.525, 0.525, 0.475, 0.35, 0.325, 0.15, 0.15, + 0.225, 0.30966535433, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.15, 0.30340097423, 0.35, 0.35, + 0.35, 0.35, 0.45, 0.45, 0.4, 0.45, 0.225, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.1, 0.25, 0.3, 0.3, + 0.3, 0.3, 0.25, 0.21213203436, 0.26893398282, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.25, + 0.36375631329, 0.31893398282, 0.31893398282, 0.31893398282, 0.31893398282, 0.45, 0.45, 0.4, + 0.4, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.325, 0.31375631329, 0.31375631329, + 0.31375631329, 0.31375631329, 0.35, 0.31642135624, 0.35, + ], + rights: [ + 1.1, 0.55, 0.7, 0.85, 0.7811023622, 0.95, 0.85, 0.575, 0.6, 0.59960629921, 0.75, 0.75, 0.575, + 0.75, 0.55, 0.75, 0.75078740157, 0.65, 0.81005905512, 0.79142135624, 0.8, 0.79142135624, + 0.79488188976, 0.75, 0.75, 0.821593479, 0.55, 0.575, 0.75, 0.75, 0.75, 0.79033464567, 0.95, + 0.85, 0.8, 0.75, 0.85695436483, 0.75, 0.75, 0.8, 0.8, 0.55, 0.74142135624, 0.805, 0.75, 0.85, + 0.8, 0.8, 0.8, 0.9, 0.8, 0.83960629921, 0.8, 0.8, 0.85, 0.95, 0.85, 0.85, 0.8, 0.6, 0.75, 0.6, + 0.7, 1.1, 0.65, 0.78624368671, 0.78624368671, 0.7, 0.75, 0.75, 0.7, 0.78624368671, + 0.78624368671, 0.55, 0.69142135624, 0.75, 0.6, 0.88624368671, 0.78624368671, 0.75, + 0.78624368671, 0.75, 0.7, 0.77600393701, 0.7, 0.75, 0.75, 0.85, 0.75, 0.75, 0.75, 0.65, 0.55, + 0.65, 0.75, 1.1, 0.55, 0.75, 0.88106601718, 0.87109784258, 0.85, 0.55, 0.69182778634, 0.7, + 0.85, 0.78624368671, 0.775, 0.75, 1.1, 0.85, 0.75, 0.7, 0.75, 0.74320866142, 0.65, 0.65, + 0.78624368671, 0.85, 0.575, 0.575, 0.625, 0.75, 0.775, 0.95, 0.98968503937, 0.925, + 0.7531496063, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.95, 0.75, 0.75, 0.75, 0.75, 0.75, 0.65, + 0.65, 0.7, 0.65, 0.85695436483, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 1, 0.85, 0.8, 0.8, 0.8, 0.8, + 0.85, 0.81213203436, 0.83106601718, 0.78624368671, 0.78624368671, 0.78624368671, + 0.78624368671, 0.78624368671, 0.78624368671, 0.85, 0.7, 0.75, 0.75, 0.75, 0.75, 0.65, 0.65, + 0.7, 0.7, 0.80098645289, 0.78624368671, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.775, 0.75, 0.75, + 0.75, 0.75, 0.75, 0.71642135624, 0.75, + ], + tops: [ + 1, 1, 1, 1, 1, 1, 1, 1, 1.05, 1.05, 1, 1, 1, 1, 1, 1, 1, 1, 1.00019685039, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00695436483, 1, 1, 1.0017766953, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05, 1, 1.05, 1.35, 1, 1.35, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.06771653543, 1.5, 1.06771653543, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1.25, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.28631889764, 1.25, 1.35, 1, 1, 1, 1, 1.25, 1, + 1, 1.05, 1.05, 1.05, 1, 1.35, 1.35, 1.35, 1.34960629921, 1.25, 1.35, 1, 1, 1.35, 1.35, 1.35, + 1.25, 1.35, 1.35, 1.35, 1.25, 1.00695436483, 1.34960629921, 1.35, 1.35, 1.35, 1.34960629921, + 1.25, 1, 1, 1.35, 1.35, 1.35, 1.25, 1.35, 1, 1, 1.05, 1.05, 1.05, 1.04960629921, 1, 1.05, 1, + 1, 1.05, 1.05, 1.05, 1, 1.05, 1.05, 1.05, 1, 1, 1.04960629921, 1.05, 1.05, 1.05, + 1.04960629921, 1, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1, 1, + ], + bottoms: [ + 0, 0, 0, 0, 0, 0, -0.0093503937, 0, -0.05, -0.05, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, -0.15, 0, 0, 0, 0, -0.32248737342, 0, 0, 0, -0.00695436483, 0, 0, -0.0017766953, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.05, 0, -0.05, 0, -0.25, 0, 0, 0, + 0, 0, 0, 0, -0.28624368671, 0, 0, -0.29142135624, 0, 0, 0, 0, 0, -0.25, -0.25, 0, 0, 0, 0, 0, + 0, 0, -0.25, 0, -0.06771653543, -0.4, -0.06771653543, 0, 0, 0, -0.1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0, -0.15, 0, 0, 0, -0.05, -0.05, -0.05, 0, 0, 0, 0, 0, + 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, -0.00695436483, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, -0.25, 0, -0.25, + ], + afterStack: 0.34921259843, }, Arial: { below: 0.29604365621, @@ -996,6 +1894,258 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01159618008, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.12005457026, 0.06412005457, 0.01432469304, 0.04979536153, 0.08117326057, 0.06002728513, + 0.06139154161, 0.08458390177, 0.08458390177, 0.04365620737, 0.07776261937, 0.11596180082, + 0.04433833561, 0.12687585266, 0, 0.05798090041, 0.15211459754, 0.04092769441, 0.05866302865, + 0.01773533424, 0.05798090041, 0.05252387449, 0.06616643929, 0.05661664393, 0.05798090041, + 0.12619372442, 0.11596180082, 0.07639836289, 0.07776261937, 0.07639836289, 0.06139154161, + 0.07571623465, 0, 0.10231923602, 0.06957708049, 0.10777626194, 0.1105047749, 0.11459754434, + 0.07435197817, 0.11186903138, 0.13028649386, 0.03751705321, 0.10231923602, 0.10231923602, + 0.1036834925, 0.10641200546, 0.06753069577, 0.10777626194, 0.06002728513, 0.10982264666, + 0.06275579809, 0.03274215553, 0.10982264666, 0.00613915416, 0.017053206, 0.00613915416, + 0.00409276944, 0.02796725784, 0.09481582538, 0, 0.02660300136, 0.03683492497, 0, + 0.06070941337, 0.05047748977, 0.09140518417, 0.05457025921, 0.04774897681, 0.05115961801, + 0.01296043656, 0.04502046385, 0.09208731241, 0.09276944065, 0, 0.09276944065, 0.08935879945, + 0.09208731241, 0.09208731241, 0.04638472033, 0.09208731241, 0.04911323329, 0.09072305593, + 0.04297407913, 0.02455661664, 0.08935879945, 0.01773533424, 0.00409276944, 0.0102319236, + 0.02251023192, 0.0272851296, 0.03888130969, 0.12824010914, 0.03206002729, 0.05934515689, 0, + 0.15825375171, 0.07298772169, 0.01841746248, 0.05047748977, 0, 0.12824010914, 0.05525238745, + 0.04160982265, 0.00204638472, 0.03206002729, 0.09140518417, 0.07776261937, 0.04433833561, + 0.00204638472, 0, 0.08731241473, 0.05320600273, 0.017053206, 0.02251023192, 0.1514324693, + 0.10914051842, 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, 0.0306957708, + 0.09549795362, 0.07298772169, 0.07298772169, 0.02251023192, 0.10777626194, 0, 0, 0, 0, 0, 0, + 0.00068212824, 0.06957708049, 0.1105047749, 0.1105047749, 0.1105047749, 0.1105047749, + 0.03683492497, 0.09618008186, 0, 0.00272851296, 0, 0.10641200546, 0.06753069577, + 0.06753069577, 0.06753069577, 0.06753069577, 0.06753069577, 0.10982264666, 0.05661664393, + 0.10982264666, 0.10982264666, 0.10982264666, 0.10982264666, 0.00409276944, 0.10777626194, + 0.10436562074, 0.05047748977, 0.05047748977, 0.05047748977, 0.05047748977, 0.05047748977, + 0.05047748977, 0.04638472033, 0.05457025921, 0.05115961801, 0.05115961801, 0.05115961801, + 0.05115961801, 0.0238744884, 0.12892223738, 0, 0.00613915416, 0.04979536153, 0.09208731242, + 0.04638472033, 0.04638472033, 0.04638472033, 0.04638472033, 0.04638472033, 0.05320600273, + 0.08799454297, 0.08935879945, 0.08935879945, 0.08935879945, 0.08935879945, 0.02251023192, + 0.09208731242, 0.02251023192, + ], + rights: [ + 0.38813096862, 0.2721691678, 0.43042291951, 0.75920873124, 0.71145975443, 1.15620736699, + 0.8997271487, 0.20122783083, 0.41473396999, 0.41473396999, 0.49454297408, 0.7380627558, + 0.26398362892, 0.42155525239, 0.26671214188, 0.38813096862, 0.71009549795, 0.5204638472, + 0.70327421555, 0.71350613915, 0.70941336971, 0.7210095498, 0.71282401091, 0.71350613915, + 0.71555252387, 0.71555252387, 0.26603001364, 0.26398362892, 0.73874488404, 0.7380627558, + 0.73874488404, 0.70668485675, 1.36766712142, 0.93383356071, 0.85743519782, 0.95361527967, + 0.93451568895, 0.85675306958, 0.78922237381, 0.99931787176, 0.8963165075, 0.26261937244, + 0.59004092769, 0.92905866303, 0.72714870396, 1.05798090041, 0.89427012278, 1.0238744884, + 0.87107776262, 1.03547066849, 0.99113233288, 0.8587994543, 0.82537517053, 0.8963165075, + 0.92087312415, 1.30286493861, 0.92291950887, 0.92087312415, 0.81855388813, 0.3656207367, + 0.38813096862, 0.29740791269, 0.61869031378, 0.79263301501, 0.31718963165, 0.71759890859, + 0.71964529332, 0.68553888131, 0.67598908595, 0.71896316508, 0.43656207367, 0.68349249659, + 0.68212824011, 0.21555252387, 0.21418826739, 0.69304229195, 0.21214188267, 1.07366984993, + 0.68076398363, 0.72510231924, 0.7210095498, 0.67667121419, 0.48431105048, 0.6446111869, + 0.37789904502, 0.67667121419, 0.68212824011, 0.99795361528, 0.68826739427, 0.68622100955, + 0.66848567531, 0.43383356071, 0.23533424284, 0.42701227831, 0.75716234652, 0.38813096862, + 0.31036834925, 0.70532060027, 0.7380627558, 0.7210095498, 0.77285129604, 0.23533424284, + 0.71282401091, 0.42428376535, 1.03137789904, 0.4897680764, 0.67598908595, 0.7380627558, + 0.42155525239, 1.03137789905, 0.79263301501, 0.46589358799, 0.71350613915, 0.44201909959, + 0.44065484311, 0.4031377899, 0.69440654843, 0.7551159618, 0.30218281037, 0.36834924966, + 0.32469304229, 0.47817189632, 0.68008185539, 1.1446111869, 1.14051841746, 1.1446111869, + 0.75238744884, 0.93383356071, 0.93383356071, 0.93383356071, 0.93383356071, 0.93383356071, + 0.93383356071, 1.32060027285, 0.95361527967, 0.85675306958, 0.85675306958, 0.85675306958, + 0.85675306958, 0.29331514325, 0.34788540246, 0.40995907231, 0.38540245566, 0.93451568895, + 0.89427012278, 1.0238744884, 1.0238744884, 1.0238744884, 1.0238744884, 1.0238744884, + 0.70463847203, 1.03478854025, 0.8963165075, 0.8963165075, 0.8963165075, 0.8963165075, + 0.92087312415, 0.87107776262, 0.80968622101, 0.71759890859, 0.71759890859, 0.71759890859, + 0.71759890859, 0.71759890859, 0.71759890859, 1.18553888131, 0.68553888131, 0.71896316507, + 0.71896316507, 0.71896316507, 0.71896316507, 0.28035470669, 0.38062755798, 0.42019099591, + 0.38881309686, 0.7210095498, 0.68076398363, 0.72510231924, 0.72510231924, 0.72510231924, + 0.72510231924, 0.72510231924, 0.71350613915, 0.76671214188, 0.67667121419, 0.67667121419, + 0.67667121419, 0.67667121419, 0.68622100955, 0.7210095498, 0.68622100955, + ], + tops: [ + 1, 1, 1, 1.017053206, 1.09208731241, 1.017053206, 1.017053206, 1, 1.017053206, 1.017053206, 1, + 1, 1, 1, 1, 1.017053206, 1.00409276944, 1.00409276944, 1.00409276944, 1.00409276944, 1, 1, + 1.00409276944, 1, 1.00409276944, 1.00409276944, 1, 1, 1, 1, 1, 1.017053206, 1.01841746248, 1, + 1, 1.017053206, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1.01773533424, 1, 1.01773533424, 1, + 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1.017053206, + 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1.017053206, 1.017053206, 1, 1.017053206, 1, 1, 1, + 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1.017053206, 1.017053206, + 1, 1.25238744884, 1.25238744884, 1.25238744884, 1.21896316507, 1.20122783083, 1.21418826739, + 1, 1.017053206, 1.25238744884, 1.25238744884, 1.25238744884, 1.20122783083, 1.25238744884, + 1.25238744884, 1.25238744884, 1.20122783083, 1, 1.21896316507, 1.25238744884, 1.25238744884, + 1.25238744884, 1.21896316507, 1.20122783083, 1, 1.03683492497, 1.25238744884, 1.25238744884, + 1.25238744884, 1.20122783083, 1.25238744884, 1, 1.017053206, 1.00545702592, 1.00545702592, + 1.00545702592, 1, 1.00613915416, 1.03478854025, 1, 1, 1.00545702592, 1.00545702592, + 1.00545702592, 1.00613915416, 1.00545702592, 1.00545702592, 1.00545702592, 1.00613915416, 1, + 1, 1.00545702592, 1.00545702592, 1.00545702592, 1, 1.00613915416, 1, 1, 1.00545702592, + 1.00545702592, 1.00545702592, 1.00613915416, 1.00545702592, 1, 1.00613915416, + ], + bottoms: [ + 0, 0, 0, -0.017053206, -0.14392905866, -0.03683492497, -0.02319236016, 0, -0.29399727149, + -0.29399727149, 0, 0, -0.19781718963, 0, 0, -0.017053206, -0.017053206, 0, 0, -0.01773533424, + 0, -0.017053206, -0.017053206, 0, -0.017053206, -0.017053206, 0, -0.19781718963, 0, 0, 0, 0, + -0.29399727149, 0, 0, -0.017053206, 0, 0, 0, -0.017053206, 0, 0, -0.017053206, 0, 0, 0, 0, + -0.017053206, 0, -0.07776261937, 0, -0.017053206, 0, -0.017053206, 0, 0, 0, 0, 0, + -0.27762619372, -0.017053206, -0.27762619372, 0, -0.27762619372, 0, -0.01637107776, + -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, 0, -0.29399727149, 0, 0, + -0.29399727149, 0, 0, 0, 0, -0.01637107776, -0.27762619372, -0.27762619372, 0, -0.01637107776, + -0.00954979536, -0.01637107776, 0, 0, 0, -0.29399727149, 0, -0.29399727149, -0.29399727149, + -0.29399727149, 0, 0, -0.275579809, -0.2789904502, -0.01909959072, 0, 0, -0.29399727149, + -0.29399727149, 0, -0.01227830832, 0, 0, 0, 0, -0.01227830832, 0, 0, 0, 0, 0, 0, + -0.27762619372, -0.27762619372, 0, -0.28717598909, 0, 0, 0, -0.03888130969, -0.03888130969, + -0.03888130969, -0.29263301501, 0, 0, 0, 0, 0, 0, 0, -0.28717598909, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.017053206, -0.017053206, -0.017053206, -0.017053206, -0.017053206, 0, -0.04024556617, + -0.017053206, -0.017053206, -0.017053206, -0.017053206, 0, 0, -0.017053206, -0.01637107776, + -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, + -0.01637107776, -0.27353342428, -0.01637107776, -0.01637107776, -0.01637107776, + -0.01637107776, 0, 0, 0, 0, -0.017053206, 0, -0.01637107776, -0.01637107776, -0.01637107776, + -0.01637107776, -0.01637107776, 0, -0.05388813097, -0.01637107776, -0.01637107776, + -0.01637107776, -0.01637107776, -0.29399727149, -0.27762619372, -0.29399727149, + ], + afterStack: 0.06684856753, + bold: { + advances: [ + 0.38813096862, 0.46521145975, 0.66234652115, 0.77694406548, 0.77694406548, 1.24215552524, + 1.00886766712, 0.33219645293, 0.46521145975, 0.46521145975, 0.54365620737, 0.81582537517, + 0.38813096862, 0.46521145975, 0.38813096862, 0.38813096862, 0.77694406548, 0.77694406548, + 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, + 0.77694406548, 0.77694406548, 0.46521145975, 0.46521145975, 0.81582537517, 0.81582537517, + 0.81582537517, 0.85334242838, 1.3622100955, 1.00886766712, 1.00886766712, 1.00886766712, + 1.00886766712, 0.93178717599, 0.85334242838, 1.08663028649, 1.00886766712, 0.38813096862, + 0.77694406548, 1.00886766712, 0.85334242838, 1.16371077763, 1.00886766712, 1.08663028649, + 0.93178717599, 1.08663028649, 1.00886766712, 0.93178717599, 0.85334242838, 1.00886766712, + 0.93178717599, 1.31855388813, 0.93178717599, 0.93178717599, 0.85334242838, 0.46521145975, + 0.38813096862, 0.46521145975, 0.81582537517, 0.77694406548, 0.46521145975, 0.77694406548, + 0.85334242838, 0.77694406548, 0.85334242838, 0.77694406548, 0.46521145975, 0.85334242838, + 0.85334242838, 0.38813096862, 0.38813096862, 0.77694406548, 0.38813096862, 1.24215552524, + 0.85334242838, 0.85334242838, 0.85334242838, 0.85334242838, 0.54365620737, 0.77694406548, + 0.46521145975, 0.85334242838, 0.77694406548, 1.08663028649, 0.77694406548, 0.77694406548, + 0.69849931787, 0.54365620737, 0.39085948158, 0.54365620737, 0.81582537517, 0.38813096862, + 0.46521145975, 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, 0.39085948158, + 0.77694406548, 0.46521145975, 1.02933151432, 0.517053206, 0.77694406548, 0.81582537517, + 0.46521145975, 1.02933151432, 0.77148703956, 0.55866302865, 0.76671214188, 0.46521145975, + 0.46521145975, 0.46521145975, 0.80491132333, 0.77694406548, 0.46521145975, 0.46521145975, + 0.46521145975, 0.5102319236, 0.77694406548, 1.16507503411, 1.16507503411, 1.16507503411, + 0.85334242838, 1.00886766712, 1.00886766712, 1.00886766712, 1.00886766712, 1.00886766712, + 1.00886766712, 1.39699863574, 1.00886766712, 0.93178717599, 0.93178717599, 0.93178717599, + 0.93178717599, 0.38813096862, 0.38813096862, 0.38813096862, 0.38813096862, 1.00886766712, + 1.00886766712, 1.08663028649, 1.08663028649, 1.08663028649, 1.08663028649, 1.08663028649, + 0.81582537517, 1.08663028649, 1.00886766712, 1.00886766712, 1.00886766712, 1.00886766712, + 0.93178717599, 0.93178717599, 0.85334242838, 0.77694406548, 0.77694406548, 0.77694406548, + 0.77694406548, 0.77694406548, 0.77694406548, 1.24215552524, 0.77694406548, 0.77694406548, + 0.77694406548, 0.77694406548, 0.77694406548, 0.38813096862, 0.38813096862, 0.38813096862, + 0.38813096862, 0.85334242838, 0.85334242838, 0.85334242838, 0.85334242838, 0.85334242838, + 0.85334242838, 0.85334242838, 0.76671214188, 0.85334242838, 0.85334242838, 0.85334242838, + 0.85334242838, 0.85334242838, 0.77694406548, 0.85334242838, 0.77694406548, + ], + lefts: [ + 0, 0.12551159618, 0.07639836289, 0.01227830832, 0.04774897681, 0.06070941337, 0.06139154161, + 0.06275579809, 0.07298772169, 0.04570259209, 0.01909959072, 0.05798090041, 0.07980900409, + 0.07844474761, 0.1002728513, 0, 0.05866302865, 0.1105047749, 0.03478854025, 0.05252387449, + 0.02592087312, 0.06207366985, 0.05934515689, 0.05934515689, 0.05661664393, 0.04433833561, + 0.13710777626, 0.11596180082, 0.06480218281, 0.05798090041, 0.06480218281, 0.07230559345, + 0.04160982265, 0, 0.10231923602, 0.06616643929, 0.10095497954, 0.10163710778, 0.10300136426, + 0.06684856753, 0.10231923602, 0.09549795362, 0.0238744884, 0.10436562074, 0.1070941337, + 0.09890859482, 0.1036834925, 0.06070941337, 0.10163710778, 0.06070941337, 0.10231923602, + 0.05047748977, 0.03001364256, 0.1002728513, 0, 0.00477489768, 0, 0, 0.01500682128, + 0.09959072306, 0, 0.02592087312, 0.07844474761, 0, 0.02864938608, 0.04979536153, + 0.09208731241, 0.05798090041, 0.05729877217, 0.04433833561, 0.01637107776, 0.05729877217, + 0.09959072306, 0.1002728513, 0, 0.0934515689, 0.1002728513, 0.08594815825, 0.09890859482, + 0.05593451569, 0.09481582538, 0.06207366985, 0.09208731241, 0.03274215553, 0.02114597544, + 0.09618008186, 0.00750341064, 0.00613915416, 0.00818553888, 0.00954979536, 0.02319236016, + 0.04092769441, 0.12005457026, 0.0306957708, 0.04570259209, 0, 0.13301500682, 0.05729877217, + 0.00886766712, 0.0306957708, 0.00068212824, 0.12005457026, 0.04024556617, 0.0034106412, 0, + 0.02523874488, 0.06548431105, 0.05798090041, 0.07844474761, 0, 0, 0.05866302865, + 0.03410641201, 0.017053206, 0.0272851296, 0.1275579809, 0.07571623465, 0, 0.13642564802, + 0.02592087312, 0.06207366985, 0.01773533424, 0.07230559345, 0.06275579809, 0.06275579809, + 0.0272851296, 0.06889495225, 0, 0, 0, 0, 0, 0, 0, 0.06616643929, 0.10163710778, + 0.10163710778, 0.10163710778, 0.10163710778, 0, 0.07230559345, 0, 0, 0, 0.1036834925, + 0.06070941337, 0.06070941337, 0.06070941337, 0.06070941337, 0.06070941337, 0.07435197817, + 0.04297407913, 0.1002728513, 0.1002728513, 0.1002728513, 0.1002728513, 0, 0.10163710778, + 0.09481582538, 0.04979536153, 0.04979536153, 0.04979536153, 0.04979536153, 0.04979536153, + 0.04979536153, 0.06002728513, 0.05798090041, 0.04433833561, 0.04433833561, 0.04433833561, + 0.04433833561, 0, 0.08594815825, 0, 0, 0.05661664393, 0.09890859482, 0.05593451569, + 0.05593451569, 0.05593451569, 0.05593451569, 0.05593451569, 0.03342428377, 0.05934515689, + 0.09618008186, 0.09618008186, 0.09618008186, 0.09618008186, 0.00954979536, 0.09481582538, + 0.00954979536, + ], + rights: [ + 0.38813096862, 0.33287858117, 0.59276944065, 0.76057298772, 0.71487039563, 1.17667121419, + 0.9863574352, 0.27148703956, 0.42019099591, 0.3929058663, 0.5136425648, 0.75716234652, + 0.28717598909, 0.45497953615, 0.29195088677, 0.3894952251, 0.70804911323, 0.54979536153, + 0.70668485675, 0.71691678035, 0.7448840382, 0.7346521146, 0.72714870396, 0.71487039563, + 0.71418826739, 0.71214188267, 0.32878581173, 0.32332878581, 0.75034106412, 0.75716234652, + 0.75102319236, 0.78990450205, 1.35743519782, 1.0034106412, 0.93997271487, 0.93724420191, + 0.93929058663, 0.8622100955, 0.78854024557, 1.00204638472, 0.90177353342, 0.29740791269, + 0.66371077763, 1.00613915416, 0.81105047749, 1.06480218281, 0.89699863574, 1.0306957708, + 0.86766712142, 1.06821282401, 1.00136425648, 0.86357435198, 0.82469304229, 0.89768076398, + 0.93042291951, 1.31718963165, 0.92974079127, 0.93315143247, 0.82742155525, 0.43929058663, + 0.3894952251, 0.3656207367, 0.73669849932, 0.78376534789, 0.33765347885, 0.72987721692, + 0.79945429741, 0.741473397, 0.76466575716, 0.72510231924, 0.50613915416, 0.76398362892, + 0.75920873124, 0.29195088677, 0.28785811733, 0.76330150068, 0.29195088677, 1.1514324693, + 0.75920873124, 0.80354706685, 0.80150068213, 0.7653478854, 0.56139154161, 0.70941336971, + 0.44815825375, 0.7551159618, 0.75989085948, 1.08594815825, 0.76398362892, 0.75443383356, + 0.66984993179, 0.50750341064, 0.2721691678, 0.49727148704, 0.77012278308, 0.38813096862, + 0.34038199181, 0.74079126876, 0.7551159618, 0.741473397, 0.77012278308, 0.2721691678, + 0.72851296044, 0.46180081855, 1.03888130969, 0.482946794, 0.69918144611, 0.75716234652, + 0.45497953615, 1.03888130969, 0.78376534789, 0.49386084584, 0.73328785812, 0.43110504775, + 0.43724420191, 0.43656207367, 0.7346521146, 0.77012278308, 0.32810368349, 0.39768076398, + 0.33765347885, 0.49113233288, 0.70600272851, 1.1514324693, 1.12960436562, 1.1514324693, + 0.78717598909, 1.0034106412, 1.0034106412, 1.0034106412, 1.0034106412, 1.0034106412, + 1.0034106412, 1.32946793997, 0.93724420191, 0.8622100955, 0.8622100955, 0.8622100955, + 0.8622100955, 0.30218281037, 0.38130968622, 0.43315143247, 0.42769440655, 0.93997271487, + 0.89699863574, 1.03069577081, 1.03069577081, 1.03069577081, 1.03069577081, 1.03069577081, + 0.74010914052, 1.04774897681, 0.89768076398, 0.89768076398, 0.89768076398, 0.89768076398, + 0.93315143247, 0.86766712142, 0.80422919509, 0.72987721692, 0.72987721692, 0.72987721692, + 0.72987721692, 0.72987721692, 0.72987721692, 1.17667121419, 0.741473397, 0.72510231924, + 0.72510231924, 0.72510231924, 0.72510231924, 0.29331514325, 0.39495225102, 0.42701227831, + 0.42564802183, 0.80150068213, 0.75920873124, 0.80354706685, 0.80354706685, 0.80354706685, + 0.80354706685, 0.80354706685, 0.73260572988, 0.80695770805, 0.7551159618, 0.7551159618, + 0.7551159618, 0.7551159618, 0.75443383356, 0.80150068213, 0.75443383356, + ], + tops: [ + 1, 1, 1, 1.017053206, 1.08049113233, 1.017053206, 1.017053206, 1, 1.017053206, 1.017053206, + 1, 1, 1, 1, 1, 1.017053206, 1.00409276944, 1.00409276944, 1.00409276944, 1.00409276944, + 1.00409276944, 1, 1.00409276944, 1, 1.00409276944, 1.00409276944, 1, 1, 1, 1, 1, + 1.0102319236, 1.01773533424, 1, 1, 1.017053206, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, + 1.017053206, 1, 1.017053206, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.017053206, 1.017053206, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1.017053206, + 1.017053206, 1, 1.0204638472, 1, 1, 1, 1, 1.0204638472, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1.01227830832, 1.01227830832, 1.01227830832, 1, 1.26125511596, 1.26125511596, + 1.258526603, 1.22919508868, 1.22169167804, 1.19918144611, 1, 1.017053206, 1.26125511596, + 1.26125511596, 1.258526603, 1.22169167804, 1.26125511596, 1.26125511596, 1.258526603, + 1.22169167804, 1, 1.22919508868, 1.26125511596, 1.26125511596, 1.258526603, 1.22919508868, + 1.22169167804, 1, 1.04774897681, 1.26125511596, 1.26125511596, 1.258526603, 1.22169167804, + 1.26125511596, 1, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1, 1.017053206, + 1.04911323329, 1, 1, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1.017053206, + 1.017053206, 1.017053206, 1.017053206, 1, 1, 1.017053206, 1.017053206, 1.017053206, 1, + 1.017053206, 1, 1, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1, + 1.017053206, + ], + bottoms: [ + 0, 0, 0, -0.017053206, -0.13983628922, -0.04024556617, -0.02592087312, 0, -0.29399727149, + -0.29399727149, 0, 0, -0.22305593452, 0, 0, -0.017053206, -0.017053206, 0, 0, -0.017053206, + 0, -0.017053206, -0.017053206, 0, -0.01773533424, -0.01773533424, 0, -0.22305593452, 0, 0, + 0, 0, -0.29399727149, 0, 0, -0.017053206, 0, 0, 0, -0.017053206, 0, 0, -0.017053206, 0, 0, + 0, 0, -0.017053206, 0, -0.1002728513, 0, -0.01773533424, 0, -0.017053206, 0, 0, 0, 0, 0, + -0.28171896317, -0.017053206, -0.28171896317, 0, -0.27626193724, 0, -0.01637107776, + -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, 0, -0.29399727149, 0, 0, + -0.29399727149, 0, 0, 0, 0, -0.01637107776, -0.275579809, -0.275579809, 0, -0.01637107776, + -0.01637107776, -0.01637107776, 0, 0, 0, -0.29399727149, 0, -0.29399727149, -0.29399727149, + -0.29399727149, 0, 0, -0.27762619372, -0.27489768076, -0.017053206, 0, 0, -0.29399727149, + -0.29399727149, 0, -0.02455661664, 0, 0, 0, 0, -0.02455661664, 0, 0, 0, 0, 0, 0, + -0.27762619372, -0.27489768076, 0, -0.28581173261, 0, 0, 0, -0.03683492497, -0.03683492497, + -0.03683492497, -0.28649386085, 0, 0, 0, 0, 0, 0, 0, -0.28581173261, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, -0.017053206, -0.017053206, -0.017053206, -0.017053206, -0.017053206, 0, + -0.05593451569, -0.017053206, -0.017053206, -0.017053206, -0.017053206, 0, 0, + -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, + -0.01637107776, -0.01637107776, -0.01637107776, -0.28581173261, -0.01637107776, + -0.01637107776, -0.01637107776, -0.01637107776, 0, 0, 0, 0, -0.017053206, 0, -0.01637107776, + -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, 0, -0.04979536153, + -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.29399727149, + -0.275579809, -0.29399727149, + ], + }, }, Calibri: { below: 0.42307692308, @@ -1053,6 +2203,280 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, -0.01153846154, 0, -0.02846153846, -0.00769230769, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.20461538462, 0.10692307692, 0.02769230769, 0.07384615385, 0.05538461538, 0.08307692308, + 0.10692307692, 0.10230769231, 0.09384615385, 0.12153846154, 0.05384615385, 0.03230769231, + 0.05307692308, 0.11615384615, 0.00076923077, 0.05538461538, 0.13384615385, 0.08769230769, + 0.07923076923, 0.03692307692, 0.07769230769, 0.08230769231, 0.07615384615, 0.06307692308, + 0.06307692308, 0.14384615385, 0.05538461538, 0.05307692308, 0.07230769231, 0.07769230769, + 0.10230769231, 0.13076923077, 0.02692307692, 0.13230769231, 0.07461538462, 0.13230769231, + 0.13230769231, 0.13230769231, 0.07, 0.13230769231, 0.13230769231, 0.00538461538, + 0.13230769231, 0.13230769231, 0.13230769231, 0.13230769231, 0.07615384615, 0.13230769231, + 0.07615384615, 0.13230769231, 0.05461538462, 0.01153846154, 0.13076923077, 0.02615384615, + 0.04692307692, 0.03692307692, 0.02307692308, 0.04538461538, 0.14692307692, 0.00846153846, + 0.06923076923, 0.08153846154, 0, 0.10076923077, 0.07076923077, 0.11769230769, 0.06923076923, + 0.07384615385, 0.07153846154, 0.02846153846, 0.04076923077, 0.11769230769, 0.10230769231, 0, + 0.11769230769, 0.11769230769, 0.11769230769, 0.11769230769, 0.06923076923, 0.11769230769, + 0.07384615385, 0.11769230769, 0.06230769231, 0.02538461538, 0.11384615385, 0.02615384615, + 0.04076923077, 0.03153846154, 0.02615384615, 0.06846153846, 0.06615384615, 0.30307692308, + 0.09, 0.04692307692, 0, 0.14692307692, 0.14230769231, 0.06384615385, 0.04846153846, 0.04, + 0.33076923077, 0.09076923077, 0.10153846154, 0.13461538462, 0.08769230769, 0.09, + 0.04692307692, 0.05307692308, 0.09846153846, 0.10153846154, 0.07923076923, 0.05846153846, + 0.05769230769, 0.05, 0.10076923077, 0.11769230769, 0.08230769231, 0.11615384615, + 0.10153846154, 0.02692307692, 0.07692307692, 0.13307692308, 0.05230769231, 0.05230769231, + 0.05461538462, 0.07230769231, 0.02692307692, 0.02692307692, 0.02692307692, 0.02692307692, + 0.02692307692, 0.02692307692, 0, 0.07461538462, 0.13230769231, 0.13230769231, 0.13230769231, + 0.13230769231, 0, 0.13153846154, 0, 0, 0.02076923077, 0.13230769231, 0.07615384615, + 0.07615384615, 0.07615384615, 0.07615384615, 0.07615384615, 0.07384615385, 0.07615384615, + 0.13076923077, 0.13076923077, 0.13076923077, 0.13076923077, 0.02307692308, 0.13230769231, + 0.11769230769, 0.07076923077, 0.07076923077, 0.07076923077, 0.07076923077, 0.07076923077, + 0.07076923077, 0.07076923077, 0.06923076923, 0.07153846154, 0.07153846154, 0.07153846154, + 0.07153846154, 0, 0.11230769231, 0, 0, 0.07461538462, 0.11769230769, 0.06923076923, + 0.06923076923, 0.06923076923, 0.06923076923, 0.06923076923, 0.03307692308, 0.06923076923, + 0.11384615385, 0.11384615385, 0.11384615385, 0.11384615385, 0.02615384615, 0.11769230769, + 0.02615384615, + ], + rights: [ + 0.35615384615, 0.36615384615, 0.51230769231, 0.75615384615, 0.71692307692, 1.07076923077, + 1.00846153846, 0.24076923077, 0.38384615385, 0.37461538462, 0.65769230769, 0.73076923077, + 0.28538461538, 0.42923076923, 0.28153846154, 0.59846153846, 0.74384615385, 0.71307692308, + 0.71076923077, 0.70307692308, 0.75307692308, 0.70615384615, 0.73615384615, 0.72538461538, + 0.73384615385, 0.71846153846, 0.30538461538, 0.30538461538, 0.70692307692, 0.71153846154, + 0.73230769231, 0.65769230769, 1.27384615385, 0.88461538462, 0.78846153846, 0.79692307692, + 0.89769230769, 0.68615384615, 0.65538461538, 0.88, 0.84923076923, 0.26461538462, + 0.37230769231, 0.78153846154, 0.64846153846, 1.21461538462, 0.88461538462, 0.96615384615, + 0.74384615385, 1.08846153846, 0.79615384615, 0.66692307692, 0.75615384615, 0.88076923077, + 0.86769230769, 1.35384615385, 0.78, 0.74307692308, 0.70461538462, 0.41461538462, + 0.60692307692, 0.33692307692, 0.7, 0.78769230769, 0.35846153846, 0.63923076923, 0.75461538462, + 0.61538461538, 0.71076923077, 0.70846153846, 0.49692307692, 0.69615384615, 0.71384615385, + 0.25923076923, 0.27384615385, 0.68615384615, 0.24461538462, 1.14461538462, 0.71384615385, + 0.76153846154, 0.75461538462, 0.71076923077, 0.52230769231, 0.55230769231, 0.47769230769, + 0.71076923077, 0.68538461538, 1.08615384615, 0.64846153846, 0.68615384615, 0.55923076923, + 0.44615384615, 0.42230769231, 0.47153846154, 0.74076923077, 0.35615384615, 0.30846153846, + 0.68769230769, 0.73076923077, 0.73846153846, 0.75846153846, 0.45076923077, 0.69923076923, + 0.51692307692, 1.18, 0.52230769231, 0.67307692308, 0.70923076923, 0.42923076923, 0.7, 0.52, + 0.45461538462, 0.72615384615, 0.47307692308, 0.46230769231, 0.35846153846, 0.84923076923, + 0.78615384615, 0.28153846154, 0.38307692308, 0.28692307692, 0.58538461538, 0.71615384615, + 0.94461538462, 0.98769230769, 1.00615384615, 0.62769230769, 0.88461538462, 0.88461538462, + 0.88461538462, 0.88461538462, 0.88461538462, 0.88461538462, 1.11769230769, 0.79692307692, + 0.68615384615, 0.68615384615, 0.68615384615, 0.68615384615, 0.26769230769, 0.43846153846, + 0.45230769231, 0.43307692308, 0.91230769231, 0.88461538462, 0.96615384615, 0.96615384615, + 0.96615384615, 0.96615384615, 0.96615384615, 0.71076923077, 0.96923076923, 0.88076923077, + 0.88076923077, 0.88076923077, 0.88076923077, 0.74307692308, 0.74384615385, 0.77692307692, + 0.63923076923, 0.63923076923, 0.63923076923, 0.63923076923, 0.63923076923, 0.63923076923, + 1.14230769231, 0.61538461538, 0.70846153846, 0.70846153846, 0.70846153846, 0.70846153846, + 0.24615384615, 0.37, 0.39461538462, 0.37153846154, 0.72769230769, 0.71384615385, + 0.76153846154, 0.76153846154, 0.76153846154, 0.76153846154, 0.76153846154, 0.73846153846, + 0.76461538461, 0.71076923077, 0.71076923077, 0.71076923077, 0.71076923077, 0.68615384615, + 0.75461538462, 0.68615384615, + ], + tops: [ + 1, 1.05692307692, 1, 1, 1.17153846154, 1.02538461538, 1.04153846154, 1, 1.09153846154, + 1.09153846154, 1, 1, 1, 1, 1, 1.13076923077, 1.01, 1.00230769231, 1.01, 1.01, 1, 1, + 1.00923076923, 1, 1.01, 1.01, 1, 1, 1, 1, 1, 1.05692307692, 1.02, 1, 1, 1.00769230769, 1, 1, + 1, 1.00923076923, 1, 1, 1, 1, 1, 1, 1, 1.01, 1, 1.01, 1, 1.01, 1, 1, 1, 1, 1, 1, 1, + 1.07615384615, 1.12538461538, 1.07615384615, 1, 1, 1, 1, 1.07153846154, 1, 1.06846153846, 1, + 1.07692307692, 1, 1.07153846154, 1.02076923077, 1.02076923077, 1.07153846154, 1.07153846154, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.08307692308, 1.10307692308, 1.08307692308, 1, 1, + 1, 1.00538461538, 1.00769230769, 1, 1, 1.11846153846, 1.03461538462, 1, 1.07692307692, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.02538461538, 1.02538461538, 1.02538461538, + 1, 1.29923076923, 1.29923076923, 1.29923076923, 1.25846153846, 1.24923076923, 1.33384615385, + 1, 1.00769230769, 1.29923076923, 1.29923076923, 1.29923076923, 1.24923076923, 1.29923076923, + 1.29923076923, 1.29923076923, 1.24923076923, 1, 1.25846153846, 1.29923076923, 1.29923076923, + 1.29923076923, 1.25846153846, 1.24923076923, 1, 1.17076923077, 1.29923076923, 1.29923076923, + 1.29923076923, 1.24923076923, 1.29923076923, 1.00153846154, 1.07692307692, 1.07846153846, + 1.07846153846, 1.07846153846, 1.04230769231, 1.00769230769, 1.10307692308, 1, 1, + 1.07846153846, 1.07846153846, 1.07846153846, 1.00769230769, 1.07846153846, 1.07846153846, + 1.07846153846, 1.00769230769, 1.07, 1.04230769231, 1.07846153846, 1.07846153846, + 1.07846153846, 1.04230769231, 1.00769230769, 1, 1, 1.07846153846, 1.07846153846, + 1.07846153846, 1.00769230769, 1.07846153846, 1.07153846154, 1.00769230769, + ], + bottoms: [ + 0, -0.00769230769, 0, -0.00461538462, -0.18846153846, -0.02769230769, -0.01384615385, 0, + -0.26538461538, -0.26538461538, 0, 0, -0.22307692308, 0, -0.00692307692, -0.21615384615, + -0.01461538462, 0, 0, -0.01461538462, -0.00461538462, -0.01461538462, -0.01461538462, + -0.00461538462, -0.01461538462, -0.01461538462, -0.00692307692, -0.22230769231, 0, 0, 0, + -0.00769230769, -0.18692307692, -0.00461538462, 0, -0.01230769231, 0, 0, -0.00461538462, + -0.01384615385, -0.00461538462, -0.00461538462, -0.01384615385, -0.00461538462, 0, + -0.00461538462, -0.00461538462, -0.01461538462, -0.00461538462, -0.14692307692, + -0.00461538462, -0.01461538462, -0.00461538462, -0.01461538462, -0.00461538462, + -0.00461538462, -0.00461538462, -0.00461538462, 0, -0.24615384615, -0.21076923077, + -0.24615384615, 0, -0.28076923077, 0, -0.01461538462, -0.01461538462, -0.01461538462, + -0.01461538462, -0.01461538462, -0.00461538462, -0.28076923077, -0.00461538462, + -0.00461538462, -0.28076923077, -0.00461538462, -0.00461538462, -0.00461538462, + -0.00461538462, -0.01461538462, -0.28, -0.28, -0.00461538462, -0.01461538462, -0.01307692308, + -0.01461538462, -0.00461538462, -0.00461538462, -0.00461538462, -0.28, 0, -0.24769230769, + -0.28076923077, -0.24769230769, 0, 0, -0.14769230769, -0.01692307692, 0, 0, -0.00461538462, + -0.30076923077, -0.15615384615, 0, -0.01461538462, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.28, + -0.18, 0, -0.28076923077, 0, 0, 0, -0.02769230769, -0.02769230769, -0.02769230769, + -0.14769230769, -0.00461538462, -0.00461538462, -0.00461538462, -0.00461538462, + -0.00461538462, -0.00461538462, -0.00461538462, -0.28076923077, 0, 0, 0, 0, -0.00461538462, + -0.00461538462, -0.00461538462, -0.00461538462, 0, -0.00461538462, -0.01461538462, + -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, 0, -0.17692307692, + -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.00461538462, + -0.00692307692, -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, + -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.28076923077, + -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.00461538462, + -0.00461538462, -0.00461538462, -0.00461538462, -0.01461538462, -0.00461538462, + -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, 0, + -0.12769230769, -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.28, -0.28, + -0.28, + ], + afterStack: 0.05461538462, + bold: { + advances: [ + 0.35615384615, 0.51307692308, 0.69076923077, 0.78461538462, 0.79846153846, 1.14846153846, + 1.11, 0.36769230769, 0.49076923077, 0.49076923077, 0.78461538462, 0.78461538462, + 0.40615384615, 0.48230769231, 0.42076923077, 0.67692307692, 0.79846153846, 0.79846153846, + 0.79846153846, 0.79846153846, 0.79846153846, 0.79846153846, 0.79846153846, 0.79846153846, + 0.79846153846, 0.79846153846, 0.43461538462, 0.43461538462, 0.78461538462, 0.78461538462, + 0.78461538462, 0.73, 1.41538461538, 0.95461538462, 0.88307692308, 0.83384615385, + 0.99307692308, 0.76846153846, 0.72307692308, 1.00384615385, 0.99384615385, 0.42, + 0.52153846154, 0.86153846154, 0.66615384615, 1.37692307692, 1.03769230769, 1.06538461538, + 0.83846153846, 1.08076923077, 0.88692307692, 0.74461538462, 0.78, 1.02846153846, + 0.93153846154, 1.42769230769, 0.86769230769, 0.81846153846, 0.75307692308, 0.51153846154, + 0.67692307692, 0.51153846154, 0.78461538462, 0.78461538462, 0.47307692308, 0.77769230769, + 0.84538461538, 0.65923076923, 0.84538461538, 0.79307692308, 0.49846153846, 0.74692307692, + 0.84538461538, 0.38692307692, 0.40230769231, 0.75615384615, 0.38692307692, 1.28153846154, + 0.84538461538, 0.84692307692, 0.84538461538, 0.84538461538, 0.56, 0.62846153846, + 0.54615384615, 0.84538461538, 0.74538461538, 1.17384615385, 0.72384615385, 0.74615384615, + 0.62615384615, 0.54153846154, 0.74846153846, 0.54153846154, 0.78461538462, 0.35615384615, + 0.51307692308, 0.78461538462, 0.79846153846, 0.78461538462, 0.79846153846, 0.78461538462, + 0.78461538462, 0.65307692308, 1.31461538462, 0.65538461538, 0.84846153846, 0.78461538462, + 0.48230769231, 0.79846153846, 0.61461538462, 0.53923076923, 0.78461538462, 0.53230769231, + 0.52923076923, 0.47384615385, 0.88769230769, 0.94153846154, 0.42153846154, 0.47769230769, + 0.39769230769, 0.68538461538, 0.84846153846, 1.03615384615, 1.08846153846, 1.10538461538, + 0.73, 0.95461538461, 0.95461538461, 0.95461538462, 0.95461538462, 0.95461538462, + 0.95461538462, 1.22153846154, 0.83384615385, 0.76846153846, 0.76846153846, 0.76846153846, + 0.76846153846, 0.42, 0.42, 0.42, 0.42, 1.00692307692, 1.03769230769, 1.06538461538, + 1.06538461538, 1.06538461538, 1.06538461538, 1.06538461538, 0.78461538462, 1.07230769231, + 1.02846153846, 1.02846153846, 1.02846153846, 1.02846153846, 0.81846153846, 0.83846153846, + 0.87384615385, 0.77769230769, 0.77769230769, 0.77769230769, 0.77769230769, 0.77769230769, + 0.77769230769, 1.22076923077, 0.65923076923, 0.79307692308, 0.79307692308, 0.79307692308, + 0.79307692308, 0.38692307692, 0.38692307692, 0.38692307692, 0.38692307692, 0.84538461538, + 0.84538461538, 0.84692307692, 0.84692307692, 0.84692307692, 0.84692307692, 0.84692307692, + 0.78461538462, 0.85692307692, 0.84538461538, 0.84538461538, 0.84538461538, 0.84538461538, + 0.74615384615, 0.84538461538, 0.74615384615, + ], + lefts: [ + 0, 0.17692307692, 0.09307692308, 0.02153846154, 0.06307692308, 0.04384615385, 0.06307692308, + 0.09307692308, 0.08230769231, 0.07461538462, 0.10307692308, 0.04, 0.01769230769, + 0.04538461538, 0.09615384615, 0.00153846154, 0.04384615385, 0.11384615385, 0.06769230769, + 0.06538461538, 0.02769230769, 0.07384615385, 0.06461538462, 0.06230769231, 0.04692307692, + 0.05076923077, 0.12307692308, 0.04153846154, 0.05230769231, 0.06384615385, 0.07846153846, + 0.08846153846, 0.09230769231, 0.01769230769, 0.10846153846, 0.06076923077, 0.10846153846, + 0.10846153846, 0.10846153846, 0.05615384615, 0.10846153846, 0.10846153846, 0.00230769231, + 0.10846153846, 0.10846153846, 0.10846153846, 0.10846153846, 0.06153846154, 0.10846153846, + 0.06153846154, 0.10846153846, 0.04846153846, 0.00923076923, 0.10769230769, 0.01692307692, + 0.03307692308, 0.02538461538, 0.01230769231, 0.03923076923, 0.12076923077, 0.02153846154, + 0.06692307692, 0.02307692308, 0, 0.07769230769, 0.05461538462, 0.09692307692, 0.05538461538, + 0.05769230769, 0.05692307692, 0.01923076923, 0.02076923077, 0.09692307692, 0.08230769231, 0, + 0.09692307692, 0.09692307692, 0.09692307692, 0.09692307692, 0.05538461538, 0.09692307692, + 0.05769230769, 0.09692307692, 0.05615384615, 0.01769230769, 0.09307692308, 0.01692307692, + 0.02692307692, 0.02461538462, 0.01692307692, 0.05307692308, 0.04153846154, 0.28307692308, + 0.08076923077, 0.04384615385, 0, 0.11923076923, 0.13, 0.05846153846, 0.02538461538, + 0.02230769231, 0.30076923077, 0.06615384615, 0.07846153846, 0.12153846154, 0.07846153846, + 0.06846153846, 0.03615384615, 0.04538461538, 0.08076923077, 0.07846153846, 0.05692307692, + 0.05307692308, 0.04769230769, 0.04307692308, 0.07769230769, 0.09692307692, 0.06307692308, + 0.09615384615, 0.07846153846, 0.02230769231, 0.06538461538, 0.11615384615, 0.04307692308, + 0.04307692308, 0.04538461538, 0.06384615385, 0.01769230769, 0.01769230769, 0.01769230769, + 0.01769230769, 0.01769230769, 0.01769230769, 0, 0.06076923077, 0.10846153846, 0.10846153846, + 0.10846153846, 0.10846153846, 0, 0.10692307692, 0, 0, 0.01153846154, 0.10846153846, + 0.06153846154, 0.06153846154, 0.06153846154, 0.06153846154, 0.06153846154, 0.06461538462, + 0.06153846154, 0.10769230769, 0.10769230769, 0.10769230769, 0.10769230769, 0.01230769231, + 0.10846153846, 0.09769230769, 0.05461538462, 0.05461538462, 0.05461538462, 0.05461538462, + 0.05461538462, 0.05461538462, 0.05461538462, 0.05538461539, 0.05692307692, 0.05692307692, + 0.05692307692, 0.05692307692, 0, 0.09692307692, 0, 0, 0.05846153846, 0.09692307692, + 0.05538461539, 0.05538461539, 0.05538461539, 0.05538461539, 0.05538461539, 0.02615384615, + 0.05538461539, 0.09307692308, 0.09307692308, 0.09307692308, 0.09307692308, 0.01692307692, + 0.09692307692, 0.01692307692, + ], + rights: [ + 0.35615384615, 0.39384615385, 0.56153846154, 0.76230769231, 0.73153846154, 1.10461538462, + 1.05384615385, 0.27384615385, 0.41538461538, 0.40769230769, 0.67615384615, 0.74461538462, + 0.32461538462, 0.43692307692, 0.32461538462, 0.65692307692, 0.75538461538, 0.72615384615, + 0.73538461538, 0.73076923077, 0.76615384615, 0.72615384615, 0.75076923077, 0.73461538462, + 0.75076923077, 0.73769230769, 0.34, 0.34, 0.70384615385, 0.71846153846, 0.73076923077, + 0.66615384615, 1.31615384615, 0.93769230769, 0.82923076923, 0.79692307692, 0.93538461538, + 0.69846153846, 0.66692307692, 0.90692307692, 0.88538461538, 0.31153846154, 0.41461538462, + 0.83538461538, 0.65538461538, 1.26846153846, 0.92923076923, 1.00384615385, 0.79, + 1.09769230769, 0.84692307692, 0.69846153846, 0.77076923077, 0.92076923077, 0.91538461538, + 1.39384615385, 0.84, 0.80615384615, 0.72, 0.44461538462, 0.67384615385, 0.39230769231, + 0.75923076923, 0.78923076923, 0.39615384615, 0.68153846154, 0.78769230769, 0.61615384615, + 0.74769230769, 0.73076923077, 0.51076923077, 0.71538461538, 0.75230769231, 0.30538461538, + 0.32, 0.73461538462, 0.29076923077, 1.18846153846, 0.75230769231, 0.79076923077, + 0.78769230769, 0.74769230769, 0.53769230769, 0.58, 0.50307692308, 0.74769230769, + 0.72846153846, 1.14692307692, 0.69923076923, 0.72923076923, 0.57692307692, 0.48615384615, + 0.46538461538, 0.52615384615, 0.74384615385, 0.35615384615, 0.33615384615, 0.69307692308, + 0.73692307692, 0.76076923077, 0.77615384615, 0.48230769231, 0.72076923077, 0.57461538462, + 1.19384615385, 0.56153846154, 0.73, 0.71846153846, 0.43692307692, 0.71769230769, + 0.53615384615, 0.48230769231, 0.73153846154, 0.49, 0.48076923077, 0.39538461538, + 0.87692307692, 0.82153846154, 0.32461538462, 0.39923076923, 0.31307692308, 0.61230769231, + 0.77769230769, 0.99076923077, 1.03384615385, 1.06, 0.64153846154, 0.93769230769, + 0.93769230769, 0.93769230769, 0.93769230769, 0.93769230769, 0.93769230769, 1.14923076923, + 0.79692307692, 0.69846153846, 0.69846153846, 0.69846153846, 0.69846153846, 0.31153846154, + 0.47, 0.48846153846, 0.48, 0.95, 0.92923076923, 1.00384615385, 1.00384615385, 1.00384615385, + 1.00384615385, 1.00384615385, 0.72, 1.01076923077, 0.92076923077, 0.92076923077, + 0.92076923077, 0.92076923077, 0.80615384615, 0.79, 0.83384615385, 0.68153846154, + 0.68153846154, 0.68153846154, 0.68153846154, 0.68153846154, 0.68153846154, 1.15846153846, + 0.61615384615, 0.73076923077, 0.73076923077, 0.73076923077, 0.73076923077, 0.29153846154, + 0.41538461538, 0.43461538461, 0.41769230769, 0.76, 0.75230769231, 0.79076923077, + 0.79076923077, 0.79076923077, 0.79076923077, 0.79076923077, 0.75076923077, 0.80153846154, + 0.74769230769, 0.74769230769, 0.74769230769, 0.74769230769, 0.72923076923, 0.78769230769, + 0.72923076923, + ], + tops: [ + 1, 1.06461538462, 1, 1, 1.17307692308, 1.02307692308, 1.04538461538, 1, 1.09538461538, + 1.09538461538, 1, 1, 1, 1, 1, 1.14384615385, 1.01307692308, 1.00230769231, 1.01307692308, + 1.01307692308, 1, 1, 1.01230769231, 1, 1.01307692308, 1.01307692308, 1, 1, 1, 1, 1, + 1.06461538462, 1.03153846154, 1, 1, 1.01153846154, 1, 1, 1, 1.01230769231, 1, 1, 1, 1, 1, 1, + 1, 1.01307692308, 1, 1.01307692308, 1, 1.01307692308, 1, 1, 1, 1, 1, 1, 1, 1.08846153846, + 1.13153846154, 1.08846153846, 1, 1, 1, 1, 1.07076923077, 1, 1.06846153846, 1, 1.07692307692, + 1, 1.07076923077, 1.04461538462, 1.04461538462, 1.07076923077, 1.07076923077, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.10615384615, 1.11230769231, 1.10615384615, 1, 1, 1, + 1.00615384615, 1.01153846154, 1, 1, 1.12, 1.04230769231, 1, 1.07692307692, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.02307692308, 1.02307692308, 1.02307692308, 1, + 1.29923076923, 1.29923076923, 1.29923076923, 1.27846153846, 1.27384615385, 1.34846153846, 1, + 1.01153846154, 1.29923076923, 1.29923076923, 1.29923076923, 1.27384615385, 1.29923076923, + 1.29923076923, 1.29923076923, 1.27384615385, 1, 1.27846153846, 1.29923076923, 1.29923076923, + 1.29923076923, 1.27846153846, 1.27384615385, 1, 1.16153846154, 1.29923076923, 1.29923076923, + 1.29923076923, 1.27384615385, 1.29923076923, 1.00153846154, 1.07692307692, 1.08, 1.08, 1.08, + 1.05846153846, 1.03692307692, 1.12076923077, 1, 1, 1.08, 1.08, 1.08, 1.03692307692, 1.08, + 1.08, 1.08, 1.03692307692, 1.07230769231, 1.05846153846, 1.08, 1.08, 1.08, 1.05846153846, + 1.03692307692, 1, 1, 1.08, 1.08, 1.08, 1.03692307692, 1.08, 1.07076923077, 1.03692307692, + ], + bottoms: [ + 0, -0.01153846154, 0, -0.00461538462, -0.18923076923, -0.02615384615, -0.01692307692, 0, + -0.27153846154, -0.27153846154, 0, 0, -0.22461538462, 0, -0.01, -0.23307692308, + -0.01769230769, 0, 0, -0.01769230769, -0.00461538462, -0.01769230769, -0.01769230769, + -0.00461538462, -0.01769230769, -0.01769230769, -0.01, -0.22153846154, 0, 0, 0, + -0.01153846154, -0.19615384615, -0.00461538462, 0, -0.01615384615, 0, 0, -0.00461538462, + -0.01692307692, -0.00461538462, -0.00461538462, -0.01538461538, -0.00461538462, 0, + -0.00461538462, -0.00461538462, -0.01769230769, -0.00461538462, -0.18, -0.00461538462, + -0.01769230769, -0.00461538462, -0.01769230769, -0.00461538462, -0.00461538462, + -0.00461538462, -0.00461538462, 0, -0.26, -0.22538461538, -0.26, 0, -0.28076923077, 0, + -0.01769230769, -0.01769230769, -0.01692307692, -0.01769230769, -0.01769230769, + -0.00461538462, -0.28076923077, -0.00461538462, -0.00461538462, -0.28076923077, + -0.00461538462, -0.00461538462, -0.00461538462, -0.00461538462, -0.01769230769, + -0.27923076923, -0.27923076923, -0.00461538462, -0.01769230769, -0.01538461538, + -0.01769230769, -0.00461538462, -0.00461538462, -0.00461538462, -0.27923076923, 0, + -0.26076923077, -0.28076923077, -0.26076923077, 0, 0, -0.14846153846, -0.01923076923, 0, 0, + -0.00461538462, -0.29307692308, -0.16, 0, -0.01769230769, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.27923076923, -0.18153846154, 0, -0.28076923077, 0, 0, 0, -0.02615384615, -0.02615384615, + -0.02615384615, -0.14769230769, -0.00461538462, -0.00461538462, -0.00461538462, + -0.00461538462, -0.00461538462, -0.00461538462, -0.00461538462, -0.28076923077, 0, 0, 0, 0, + -0.00461538462, -0.00461538462, -0.00461538462, -0.00461538462, 0, -0.00461538462, + -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, 0, + -0.17153846154, -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, + -0.00461538462, -0.00692307692, -0.01615384615, -0.01769230769, -0.01769230769, + -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, + -0.28076923077, -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, + -0.00461538462, -0.00461538462, -0.00461538462, -0.00461538462, -0.01769230769, + -0.00461538462, -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, + -0.01769230769, 0, -0.13461538462, -0.01769230769, -0.01769230769, -0.01769230769, + -0.01769230769, -0.27923076923, -0.27923076923, -0.27923076923, + ], + }, }, Consolas: { below: 0.39326702372, @@ -1108,6 +2532,267 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.32746748279, 0.1973986228, 0.03289977047, 0.08492731446, 0.01530221882, 0.04361132364, + 0.34353481255, 0.22953328233, 0.19892884468, 0.12547819434, 0.06426931905, 0.18209640398, + 0.20198928845, 0.29762815608, 0.08798775822, 0.06732976282, 0.10328997705, 0.11247130834, + 0.12547819434, 0.03289977047, 0.13618974751, 0.09410864575, 0.08951798011, 0.09104820199, + 0.07651109411, 0.31369548585, 0.19127773527, 0.10482019893, 0.10175975516, 0.15990818669, + 0.23182861515, 0.00688599847, 0.00765110941, 0.12088752869, 0.07039020658, 0.08339709258, + 0.15378729916, 0.15684774292, 0.05049732211, 0.08492731446, 0.13159908187, 0.13925019128, + 0.11935730681, 0.17827084927, 0.03749043611, 0.09104820199, 0.04361132364, 0.12088752869, + 0.04361132364, 0.13006885998, 0.08492731446, 0.06579954093, 0.08339709258, 0.00306044376, + 0.03442999235, 0.01377199694, 0, 0.08492731446, 0.26396327467, 0.12241775057, 0.22035195103, + 0.09257842387, 0, 0.13312930375, 0.10175975516, 0.12241775057, 0.12088752869, 0.08339709258, + 0.08951798011, 0.06120887529, 0.07192042846, 0.12241775057, 0.13159908187, 0.10022953328, + 0.13925019128, 0.13159908187, 0.0688599847, 0.12241775057, 0.07039020658, 0.12241775057, + 0.08339709258, 0.15378729916, 0.13925019128, 0.04820198929, 0.12241775057, 0.05049732211, + 0.02830910482, 0.05355776588, 0.04514154552, 0.12547819434, 0.12394797246, 0.36801836266, + 0.17521040551, 0.04896710023, 0, 0.33205814843, 0.09563886764, 0.07039020658, 0.06579954093, + 0.04208110176, 0.36801836266, 0.10788064269, 0.1805661821, 0.00918133129, 0.17214996174, + 0.10941086458, 0.08951798011, 0.20198928845, 0.08110175976, 0.23029839327, 0.16296863045, + 0.07957153787, 0.18821729151, 0.20964039786, 0.35118592196, 0.12241775057, 0.08339709258, + 0.30374904361, 0.33358837031, 0.17368018363, 0.16908951798, 0.11935730681, 0.01530221882, + 0.01530221882, 0.01530221882, 0.15531752104, 0.00765110941, 0.00765110941, 0.00765110941, + 0.00765110941, 0.00765110941, 0.00765110941, 0, 0.07039020658, 0.15378729916, 0.15378729916, + 0.15378729916, 0.15378729916, 0.13159908187, 0.13159908187, 0.13159908187, 0.13159908187, 0, + 0.09104820199, 0.04361132364, 0.04361132364, 0.04361132364, 0.04361132364, 0.04361132364, + 0.11247130834, 0.04361132364, 0.08339709258, 0.08339709258, 0.08339709258, 0.08339709258, 0, + 0.12088752869, 0.11247130834, 0.10175975516, 0.10175975516, 0.10175975516, 0.10175975516, + 0.10175975516, 0.10175975516, 0.02371843917, 0.12088752869, 0.08951798011, 0.08951798011, + 0.08951798011, 0.08951798011, 0.13159908187, 0.13159908187, 0.13159908187, 0.13159908187, + 0.07651109411, 0.12241775057, 0.07039020658, 0.07039020658, 0.07039020658, 0.07039020658, + 0.07039020658, 0.06426931905, 0.07039020658, 0.12241775057, 0.12241775057, 0.12241775057, + 0.12241775057, 0.04514154552, 0.12241775057, 0.04514154552, + ], + rights: [ + 0.86151491966, 0.52945677123, 0.66411629686, 0.8286151492, 0.76817138485, 0.84621270084, + 0.86151491966, 0.51874521806, 0.66258607498, 0.63198163734, 0.73680183627, 0.79724560061, + 0.55164498852, 0.65952563122, 0.55164498852, 0.73986228003, 0.79418515685, 0.76281560826, + 0.77123182862, 0.75210405509, 0.82096403979, 0.74598316756, 0.78347360367, 0.76587605203, + 0.77123182862, 0.76587605203, 0.54858454476, 0.56082631982, 0.70237184392, 0.7597551645, + 0.75669472073, 0.70543228768, 0.85080336649, 0.85386381025, 0.77735271614, 0.76128538638, + 0.80566182096, 0.72226472839, 0.7207345065, 0.77429227238, 0.77735271614, 0.7299158378, + 0.67100229533, 0.80107115532, 0.75363427697, 0.82402448355, 0.77123182862, 0.8194338179, + 0.77735271614, 0.86151491966, 0.80413159908, 0.76281560826, 0.79571537873, 0.77888293803, + 0.8584544759, 0.82708492731, 0.84315225708, 0.86151491966, 0.77582249426, 0.64116296863, + 0.77429227238, 0.59755164499, 0.77582249426, 0.86151491966, 0.51109410865, 0.73527161438, + 0.77888293803, 0.71920428462, 0.73527161438, 0.77123182862, 0.80413159908, 0.79877582249, + 0.73986228003, 0.74751338944, 0.66717674063, 0.81331293037, 0.74751338944, 0.79265493497, + 0.73986228003, 0.79112471308, 0.77888293803, 0.73527161438, 0.7895944912, 0.73068094874, + 0.74139250191, 0.73986228003, 0.80566182096, 0.83397092578, 0.81484315226, 0.80566182096, + 0.74445294568, 0.68630451415, 0.493496557, 0.73833205815, 0.81254781943, 0.86151491966, + 0.53404743688, 0.69395562357, 0.76970160673, 0.79571537873, 0.82402448355, 0.493496557, + 0.75822494262, 0.68171384851, 0.85233358837, 0.68936495792, 0.7429227238, 0.74292272379, + 0.65952563122, 0.78041315991, 0.6312165264, 0.69854628921, 0.78194338179, 0.67559296098, + 0.65952563122, 0.72838561591, 0.82402448355, 0.76281560826, 0.55776587605, 0.51568477429, + 0.67253251722, 0.69242540168, 0.75210405509, 0.84621270084, 0.84621270084, 0.84621270084, + 0.62815608263, 0.85386381025, 0.85386381025, 0.85386381025, 0.85386381025, 0.85386381025, + 0.85386381025, 0.83014537108, 0.76128538638, 0.72226472839, 0.72226472839, 0.72226472839, + 0.72226472839, 0.7299158378, 0.7299158378, 0.7299158378, 0.7299158378, 0.80566182096, + 0.77123182862, 0.8194338179, 0.8194338179, 0.8194338179, 0.8194338179, 0.8194338179, + 0.74904361132, 0.81790359602, 0.77888293803, 0.77888293803, 0.77888293803, 0.77888293803, + 0.86151491966, 0.77735271614, 0.78194338179, 0.73527161438, 0.73527161438, 0.73527161438, + 0.73527161438, 0.73527161438, 0.73527161438, 0.83167559296, 0.71920428462, 0.77123182862, + 0.77123182862, 0.77123182862, 0.77123182862, 0.74751338944, 0.74751338944, 0.74751338944, + 0.74751338944, 0.76970160673, 0.73986228003, 0.79112471308, 0.79112471308, 0.79112471308, + 0.79112471308, 0.79112471308, 0.79724560061, 0.79112471308, 0.73986228003, 0.73986228003, + 0.73986228003, 0.73986228003, 0.80566182096, 0.77888293803, 0.80566182096, + ], + tops: [ + 1, 1.08110175976, 1, 1, 1.14384085692, 1.09181331293, 1.05891354246, 1, 1.13925019128, + 1.13925019128, 1, 1, 1, 1, 1, 1.08110175976, 1.01377199694, 1.00459066565, 1.01377199694, + 1.01377199694, 1, 1, 1, 1, 1.01377199694, 1.01377199694, 1, 1, 1, 1, 1, 1.08110175976, + 1.09028309105, 1, 1, 1.01224177506, 1, 1, 1, 1.01377199694, 1, 1, 1, 1, 1, 1, 1, + 1.01377199694, 1, 1.01377199694, 1, 1.01377199694, 1, 1, 1, 1, 1, 1, 1, 1.10788064269, + 1.08110175976, 1.10788064269, 1, 1, 1, 1, 1.08110175976, 1, 1.08110175976, 1, 1.09028309105, + 1, 1.08110175976, 1.09028309105, 1.09028309105, 1.08110175976, 1.08110175976, 1, 1, 1, 1, 1, + 1, 1, 1.01377199694, 1, 1, 1, 1, 1, 1, 1.10788064269, 1.2532517215, 1.10788064269, 1, 1, 1, + 1.14384085692, 1.01377199694, 1, 1, 1.2532517215, 1.09028309105, 1, 1.01224177506, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.08110175976, 1, 1, 1, 1, 1, 1.09028309105, 1.09028309105, + 1.09181331293, 1, 1.26931905126, 1.26931905126, 1.26931905126, 1.27850038256, 1.26931905126, + 1.33129303749, 1, 1.01224177506, 1.26931905126, 1.26931905126, 1.26931905126, 1.26931905126, + 1.26931905126, 1.26931905126, 1.26931905126, 1.26931905126, 1, 1.27850038256, 1.26931905126, + 1.26931905126, 1.26931905126, 1.27850038256, 1.26931905126, 1, 1.16449885233, 1.26931905126, + 1.26931905126, 1.26931905126, 1.26931905126, 1.26931905126, 1, 1.09028309105, 1.08110175976, + 1.08110175976, 1.08110175976, 1.08110175976, 1.07498087223, 1.14843152257, 1, 1, + 1.08110175976, 1.08110175976, 1.08110175976, 1.07498087223, 1.08110175976, 1.08110175976, + 1.08110175976, 1.07498087223, 1.08110175976, 1.08110175976, 1.08110175976, 1.08110175976, + 1.08110175976, 1.08110175976, 1.07498087223, 1, 1, 1.08110175976, 1.08110175976, + 1.08110175976, 1.07498087223, 1.08110175976, 1.08110175976, 1.07498087223, + ], + bottoms: [ + 0, -0.01377199694, 0, 0, -0.1805661821, -0.01071155318, -0.01071155318, 0, -0.32134659526, + -0.32134659526, 0, 0, -0.26166794185, 0, -0.01377199694, -0.16449885233, -0.01377199694, 0, 0, + -0.01377199694, 0, -0.01377199694, -0.01377199694, 0, -0.01377199694, 0, -0.01377199694, + -0.26166794185, -0.01224177506, 0, -0.01224177506, -0.01377199694, -0.31828615149, 0, 0, + -0.01224177506, 0, 0, 0, -0.01377199694, 0, 0, -0.01071155318, 0, 0, 0, 0, -0.01377199694, 0, + -0.27543993879, 0, -0.01377199694, 0, -0.01377199694, 0, 0, 0, 0, 0, -0.31369548585, + -0.16449885233, -0.31369548585, 0, -0.31369548585, 0, -0.01377199694, -0.00918133129, + -0.01071155318, -0.01377199694, -0.01377199694, 0, -0.32134659526, 0, 0, -0.32134659526, 0, 0, + 0, 0, -0.01377199694, -0.31369548585, -0.31369548585, 0, -0.01377199694, -0.01071155318, + -0.01377199694, 0, 0, 0, -0.31828615149, 0, -0.31369548585, -0.31369548585, -0.31369548585, 0, + 0, -0.31369548585, -0.19127773527, 0, 0, 0, -0.31369548585, -0.17827084927, 0, -0.01224177506, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.31369548585, -0.17827084927, 0, -0.22570772762, 0, 0, 0, + 0, 0, 0, -0.31369548585, 0, 0, 0, 0, 0, 0, 0, -0.22570772762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, 0, + -0.16449885233, -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, 0, 0, + -0.00918133129, -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, + -0.01377199694, -0.01377199694, -0.01377199694, -0.22570772762, -0.01377199694, + -0.01377199694, -0.01377199694, -0.01377199694, 0, 0, 0, 0, -0.01377199694, 0, -0.01377199694, + -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, 0, -0.16449885233, + -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, -0.31828615149, + -0.31369548585, -0.31828615149, + ], + afterStack: 0.06732976282, + bold: { + advances: [ + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + ], + lefts: [ + 0, 0.31216526396, 0.17368018363, 0.03136954858, 0.0688599847, 0, 0.02371843917, + 0.3259372609, 0.20811017598, 0.17521040551, 0.10328997705, 0.0596786534, 0.16143840857, + 0.19280795715, 0.2792654935, 0.05508798776, 0.04055087988, 0.08798775823, 0.09410864575, + 0.10635042081, 0.0298393267, 0.11935730681, 0.07498087223, 0.08110175976, 0.07804131599, + 0.05508798776, 0.29303749044, 0.17061973986, 0.07804131599, 0.10175975516, 0.14919663351, + 0.21499617445, 0.00688599847, 0.00306044376, 0.0986993114, 0.06273909717, 0.06579954093, + 0.14078041316, 0.14078041316, 0.03596021423, 0.0726855394, 0.11476664116, 0.13159908187, + 0.0986993114, 0.15072685539, 0.03442999235, 0.07192042846, 0.02830910482, 0.10328997705, + 0.02830910482, 0.0986993114, 0.07498087223, 0.06044376435, 0.06656465187, 0, 0.02524866106, + 0.00612088753, 0.00765110941, 0.07957153787, 0.23335883703, 0.09104820199, 0.20198928845, + 0.06503442999, 0, 0.07039020658, 0.08339709258, 0.10635042081, 0.10175975516, 0.05814843152, + 0.07804131599, 0.06120887529, 0.05814843152, 0.10635042081, 0.11094108646, 0.09104820199, + 0.11400153022, 0.11094108646, 0.04514154552, 0.10635042081, 0.05508798776, 0.10635042081, + 0.05814843152, 0.1377199694, 0.11935730681, 0.04514154552, 0.10482019893, 0.01759755165, + 0.00612088753, 0.02524866106, 0.01759755165, 0.11476664116, 0.11629686305, 0.34506503443, + 0.16602907422, 0.03596021423, 0, 0.31216526396, 0.08645753634, 0.05814843152, 0.03136954858, + 0.0298393267, 0.34506503443, 0.0688599847, 0.16602907422, 0.01224177506, 0.16602907422, + 0.08798775823, 0.07804131599, 0.19280795715, 0.05202754399, 0.21729150727, 0.14537107881, + 0.07957153787, 0.17521040551, 0.1805661821, 0.33664881408, 0.10328997705, 0.05661820964, + 0.28385615914, 0.32134659526, 0.17674062739, 0.15378729916, 0.0986993114, 0, 0, 0, + 0.12394797246, 0.00306044376, 0.00306044376, 0.00306044376, 0.00306044376, 0.00306044376, + 0.00306044376, 0, 0.06273909717, 0.10175975516, 0.14078041316, 0.14078041316, 0.14078041316, + 0.10175975516, 0.11476664116, 0.11476664116, 0.11476664116, 0, 0.07192042846, 0.02830910482, + 0.02830910482, 0.02830910482, 0.02830910482, 0.02830910482, 0.08951798011, 0.02830910482, + 0.06656465188, 0.06656465188, 0.06656465188, 0.06656465188, 0.00765110941, 0.10328997705, + 0.10635042081, 0.07039020658, 0.08339709258, 0.08339709258, 0.08339709258, 0.08339709258, + 0.08339709258, 0.01377199694, 0.10175975516, 0.07039020658, 0.07804131599, 0.07804131599, + 0.07804131599, 0.0856924254, 0.11094108646, 0.11094108646, 0.11094108646, 0.05814843152, + 0.10635042081, 0.05508798776, 0.05508798776, 0.05508798776, 0.05508798776, 0.05508798776, + 0.0596786534, 0.05508798776, 0.07039020658, 0.10482019893, 0.10482019893, 0.10482019893, + 0.01759755164, 0.10635042081, 0.01759755164, + ], + rights: [ + 0.86151491966, 0.55011476664, 0.68783473604, 0.8286151492, 0.7895944912, 0.86151491966, + 0.88370313695, 0.53557765876, 0.6908951798, 0.65646518745, 0.75822494262, 0.8026013772, + 0.57689364958, 0.66870696251, 0.57689364958, 0.77123182862, 0.82096403979, 0.78194338179, + 0.77735271614, 0.78041315991, 0.8286151492, 0.76970160673, 0.8026013772, 0.77582249426, + 0.78347360367, 0.78194338179, 0.56847742923, 0.58607498087, 0.71308339709, 0.7597551645, + 0.78347360367, 0.73833205815, 0.85386381025, 0.8584544759, 0.8026013772, 0.76817138485, + 0.82096403979, 0.74292272379, 0.73144605968, 0.79112471308, 0.78882938026, 0.7467482785, + 0.69242540168, 0.83397092578, 0.76434583015, 0.82708492731, 0.79571537873, 0.83320581484, + 0.79724560061, 0.86687069625, 0.82402448355, 0.78041315991, 0.80107115532, 0.79495026779, + 0.86151491966, 0.83703136955, 0.85539403213, 0.85233358837, 0.78194338179, 0.63580719204, + 0.80719204285, 0.60290742158, 0.79648048967, 0.86151491966, 0.5233358837, 0.75363427697, + 0.80566182096, 0.73527161438, 0.75669472073, 0.78347360367, 0.80413159908, 0.81178270849, + 0.75669472073, 0.7727620505, 0.6908951798, 0.83167559296, 0.7727620505, 0.81637337414, + 0.75669472073, 0.80642693191, 0.80566182096, 0.75669472073, 0.79648048967, 0.74751338944, + 0.74751338944, 0.75516449885, 0.84621270084, 0.85386381025, 0.83856159143, 0.84621270084, + 0.74751338944, 0.69548584545, 0.51721499617, 0.74598316756, 0.82555470543, 0.86151491966, + 0.55011476664, 0.70543228768, 0.78806426932, 0.83014537108, 0.83550114767, 0.51721499617, + 0.8026013772, 0.69548584545, 0.84927314461, 0.69548584545, 0.76281560826, 0.75669472073, + 0.66870696251, 0.81025248661, 0.64422341239, 0.71614384086, 0.78194338179, 0.67865340474, + 0.67559296098, 0.7895944912, 0.8286151492, 0.79877582249, 0.58148431523, 0.54246365723, + 0.67865340474, 0.70772762051, 0.77429227238, 0.86151491966, 0.86151491966, 0.86151491966, + 0.64728385616, 0.8584544759, 0.8584544759, 0.8584544759, 0.8584544759, 0.8584544759, + 0.8584544759, 0.83014537108, 0.76817138485, 0.74292272379, 0.7597551645, 0.74292272379, + 0.74292272379, 0.7467482785, 0.7597551645, 0.7467482785, 0.7467482785, 0.82096403979, + 0.79571537873, 0.83320581484, 0.83320581484, 0.83320581484, 0.83320581484, 0.83320581484, + 0.77199693956, 0.83320581484, 0.79495026779, 0.79495026779, 0.79495026779, 0.79495026779, + 0.85233358837, 0.79724560061, 0.82096403979, 0.75363427697, 0.7895944912, 0.75363427697, + 0.75363427697, 0.75363427697, 0.75363427697, 0.84315225708, 0.73527161438, 0.78347360367, + 0.7895944912, 0.78347360367, 0.78347360367, 0.7727620505, 0.80489671002, 0.7727620505, + 0.7727620505, 0.78653404744, 0.75669472073, 0.8064269319, 0.8064269319, 0.8064269319, + 0.8064269319, 0.8064269319, 0.8026013772, 0.80719204285, 0.75516449885, 0.7895944912, + 0.75516449885, 0.75516449885, 0.84621270084, 0.80566182096, 0.84621270084, + ], + tops: [ + 1, 1.08110175976, 1, 1, 1.1545524101, 1.09563886764, 1.07498087223, 1, 1.14078041316, + 1.14078041316, 1, 1, 1, 1, 1, 1.08110175976, 1.0168324407, 1.00612088753, 1.0168324407, + 1.0168324407, 1, 1, 1, 1, 1.0168324407, 1.0168324407, 1, 1, 1, 1, 1, 1.08110175976, + 1.0986993114, 1, 1, 1.01377199694, 1, 1, 1, 1.0168324407, 1, 1, 1, 1, 1, 1, 1, 1.0168324407, + 1, 1.0168324407, 1, 1.0168324407, 1, 1, 1, 1, 1, 1, 1, 1.1155317521, 1.08110175976, + 1.1155317521, 1, 1, 1, 1, 1.08110175976, 1, 1.08110175976, 1, 1.09563886764, 1, + 1.08110175976, 1.11247130834, 1.11247130834, 1.08110175976, 1.08110175976, 1, 1, 1, 1, 1, 1, + 1, 1.026013772, 1, 1, 1, 1, 1, 1, 1.1155317521, 1.2532517215, 1.1155317521, 1, 1, 1, + 1.14384085692, 1.0168324407, 1, 1, 1.2532517215, 1.09563886764, 1, 1.0168324407, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.08110175976, 1, 1, 1, 1, 1, 1.0856924254, 1.0856924254, + 1.09563886764, 1, 1.27850038256, 1.27850038256, 1.27850038256, 1.29762815608, 1.29303749044, + 1.33205814843, 1, 1.01377199694, 1.27850038256, 1.27850038256, 1.27850038256, 1.29303749044, + 1.27850038256, 1.27850038256, 1.27850038256, 1.29303749044, 1, 1.29762815608, 1.27850038256, + 1.27850038256, 1.27850038256, 1.29762815608, 1.29303749044, 1, 1.16449885233, 1.27850038256, + 1.27850038256, 1.27850038256, 1.29303749044, 1.27850038256, 1, 1.09563886764, 1.08110175976, + 1.08110175976, 1.08110175976, 1.09640397858, 1.09410864575, 1.18745218057, 1, 1, + 1.08110175976, 1.08110175976, 1.08110175976, 1.09410864575, 1.08110175976, 1.08110175976, + 1.08110175976, 1.09410864575, 1.08110175976, 1.09640397858, 1.08110175976, 1.08110175976, + 1.08110175976, 1.09640397858, 1.09410864575, 1, 1, 1.08110175976, 1.08110175976, + 1.08110175976, 1.09410864575, 1.08110175976, 1.08110175976, 1.09410864575, + ], + bottoms: [ + 0, -0.01759755164, 0, 0, -0.18974751339, -0.01377199694, -0.01759755164, 0, -0.32134659526, + -0.32134659526, 0, 0, -0.26931905126, 0, -0.01759755164, -0.16449885233, -0.01759755164, 0, + 0, -0.01530221882, 0, -0.01530221882, -0.01759755164, 0, -0.01759755164, 0, -0.01759755164, + -0.26931905126, -0.01759755164, 0, -0.01759755164, -0.01759755164, -0.32134659526, 0, 0, + -0.01377199694, 0, 0, 0, -0.01759755164, 0, 0, -0.01530221882, 0, 0, 0, 0, -0.01759755164, + 0, -0.28997704667, 0, -0.01759755164, 0, -0.01759755164, 0, 0, 0, 0, 0, -0.30374904361, + -0.16449885233, -0.30374904361, 0, -0.31369548585, 0, -0.01759755164, -0.01377199694, + -0.01377199694, -0.01759755164, -0.01759755164, 0, -0.32134659526, 0, 0, -0.32134659526, 0, + 0, 0, 0, -0.01759755164, -0.30374904361, -0.30374904361, 0, -0.01759755164, -0.01759755164, + -0.01759755164, 0, 0, 0, -0.32134659526, 0, -0.30374904361, -0.31369548585, -0.30374904361, + 0, 0, -0.30374904361, -0.19127773527, 0, 0, 0, -0.31369548585, -0.1805661821, 0, + -0.01759755164, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.30374904361, -0.1805661821, 0, + -0.22570772762, 0, 0, 0, 0, 0, 0, -0.30374904361, 0, 0, 0, 0, 0, 0, 0, -0.22570772762, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, + -0.01759755164, 0, -0.16449885233, -0.01759755164, -0.01759755164, -0.01759755164, + -0.01759755164, 0, 0, -0.01224177506, -0.01759755164, -0.01759755164, -0.01759755164, + -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, -0.22570772762, + -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, 0, 0, 0, 0, -0.01759755164, + 0, -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, 0, + -0.16449885233, -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, + -0.32134659526, -0.30374904361, -0.32134659526, + ], + }, }, "Courier New": { below: 0.52564102564, @@ -1163,6 +2848,267 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.41965811966, 0.22735042735, 0.15982905983, 0.19487179487, 0.15982905983, 0.21709401709, + 0.41111111111, 0.51709401709, 0.25726495726, 0.19316239316, 0.12307692308, 0.25555555556, + 0.15897435897, 0.39401709402, 0.19658119658, 0.19572649573, 0.19487179487, 0.14615384615, + 0.16666666667, 0.18290598291, 0.16752136752, 0.23418803419, 0.18034188034, 0.19743589744, + 0.23504273504, 0.39401709402, 0.26666666667, 0.08376068376, 0.08632478632, 0.1264957265, + 0.23504273504, 0.18376068376, 0.01452991453, 0.07435897436, 0.10854700855, 0.13504273504, + 0.07521367521, 0.1358974359, 0.1094017094, 0.09145299145, 0.19572649573, 0.14615384615, + 0.07606837607, 0.1094017094, 0.02051282051, 0.03931623932, 0.08888888889, 0.15299145299, + 0.08888888889, 0.07521367521, 0.15811965812, 0.12222222222, 0.07094017094, 0.01367521368, + 0.03162393162, 0.06837606838, 0.08461538462, 0.18205128205, 0.48974358974, 0.19401709402, + 0.27008547009, 0.19487179487, 0, 0.37948717949, 0.12307692308, 0.03846153846, 0.14615384615, + 0.10769230769, 0.1094017094, 0.18376068376, 0.10683760684, 0.07264957265, 0.16153846154, + 0.15384615385, 0.16324786325, 0.15982905983, 0.01794871795, 0.09230769231, 0.12393162393, + 0.03846153846, 0.1094017094, 0.14615384615, 0.17692307692, 0.12478632479, 0.07777777778, + 0.05042735043, 0.04786324786, 0.08632478632, 0.12735042735, 0.20256410256, 0.34615384615, + 0.48888888889, 0.3452991453, 0.15982905983, 0, 0.41965811966, 0.19487179487, 0.10598290598, + 0.17606837607, 0.08376068376, 0.48888888889, 0.12222222222, 0.27264957265, 0, 0.25299145299, + 0.08461538462, 0.02051282051, 0.15897435897, 0, 0, 0.28803418803, 0.12307692308, + 0.29145299145, 0.30341880342, 0.37863247863, 0.07692307692, 0.14615384615, 0.60512820513, + 0.37777777778, 0.31965811966, 0.25128205128, 0.10854700855, 0, 0, 0, 0.19658119658, + 0.01452991453, 0.01452991453, 0.01452991453, 0.01452991453, 0.01452991453, 0.01452991453, + 0.01538461539, 0.10854700855, 0.07521367521, 0.07521367521, 0.07521367521, 0.07521367521, + 0.19572649573, 0.19572649573, 0.19572649573, 0.19572649573, 0, 0.03931623932, 0.08888888889, + 0.08888888889, 0.08888888889, 0.08888888889, 0.08888888889, 0.23076923077, 0.06837606838, + 0.07094017094, 0.07094017094, 0.07094017094, 0.07094017094, 0.08461538462, 0.15299145299, + 0.07606837607, 0.12307692308, 0.12307692308, 0.12307692308, 0.12307692308, 0.12307692308, + 0.12307692308, 0.01367521368, 0.14615384615, 0.1094017094, 0.1094017094, 0.1094017094, + 0.1094017094, 0.15897435897, 0.15897435897, 0.15897435898, 0.15897435898, 0.11025641026, + 0.09230769231, 0.12393162393, 0.12393162393, 0.12393162393, 0.12393162393, 0.12393162393, + 0.12307692308, 0.09572649573, 0.07777777778, 0.07777777778, 0.07777777778, 0.07777777778, + 0.12735042735, 0.03846153846, 0.12735042735, + ], + rights: [ + 1.05042735043, 0.63076923077, 0.82136752137, 0.88974358974, 0.8547008547, 0.89230769231, + 0.8735042735, 0.63846153846, 0.80598290598, 0.54615384615, 0.85042735043, 0.92735042735, + 0.61623931624, 0.89145299145, 0.65726495726, 0.85641025641, 0.8547008547, 0.8547008547, + 0.84017094017, 0.87606837607, 0.84017094017, 0.87606837607, 0.89743589744, 0.83931623932, + 0.85384615385, 0.89487179487, 0.65726495726, 0.65641025641, 0.92393162393, 0.96495726496, + 0.96666666667, 0.85726495726, 0.84017094017, 1.03846153846, 0.95128205128, 0.94017094017, + 0.97606837607, 0.91538461538, 0.97435897436, 0.98888888889, 0.97008547009, 0.85555555556, + 1.02478632479, 1.00598290598, 0.95042735043, 1.03931623932, 0.98547008547, 0.9641025641, + 0.95299145299, 0.9641025641, 1.03760683761, 0.89230769231, 0.9264957265, 0.9811965812, + 1.03760683761, 1.01538461538, 0.98461538462, 0.9641025641, 0.8735042735, 0.78376068376, + 0.85384615385, 0.5641025641, 0.85555555556, 1.05042735043, 0.67179487179, 0.94871794872, + 0.94957264957, 0.93931623932, 1.02136752137, 0.91538461538, 0.95213675214, 0.98290598291, + 0.96837606838, 0.89401709402, 0.70427350427, 1.00085470085, 0.89230769231, 1.03846153846, + 0.94957264957, 0.9264957265, 0.94957264957, 1.02051282051, 0.95213675214, 0.8735042735, + 0.92564102564, 0.95128205128, 1, 1.00170940171, 0.96581196581, 1.00512820513, 0.85982905983, + 0.70598290598, 0.56153846154, 0.70512820513, 0.89145299145, 1.05042735043, 0.63076923077, + 0.82393162393, 0.91538461538, 0.8735042735, 0.9641025641, 0.56153846154, 0.92735042735, + 0.77863247863, 1.0452991453, 0.81196581197, 0.94188034188, 0.92735042735, 0.89145299145, + 1.0452991453, 1.0735042735, 0.76239316239, 0.92735042735, 0.72136752137, 0.74273504274, + 0.67094017094, 0.95042735043, 0.91111111111, 0.78034188034, 0.65299145299, 0.72991452991, + 0.79487179487, 0.96581196581, 1.04102564103, 1.06153846154, 1.03675213675, 0.8188034188, + 1.03846153846, 1.03846153846, 1.03846153846, 1.03846153846, 1.03846153846, 1.03846153846, + 1.0358974359, 0.94017094017, 0.91538461538, 0.91538461538, 0.91538461538, 0.91538461538, + 0.85555555556, 0.85555555556, 0.85555555556, 0.85555555556, 0.91538461538, 0.98547008547, + 0.9641025641, 0.9641025641, 0.9641025641, 0.9641025641, 0.9641025641, 0.82051282051, + 0.98205128205, 0.9811965812, 0.9811965812, 0.9811965812, 0.9811965812, 0.9641025641, + 0.95299145299, 0.8811965812, 0.94871794872, 0.94871794872, 0.94871794872, 0.94871794872, + 0.94871794872, 0.94871794872, 1.0188034188, 0.93931623932, 0.91538461538, 0.91538461538, + 0.91538461538, 0.91538461538, 0.89487179487, 0.89487179487, 0.89487179487, 0.89487179487, + 0.91452991453, 0.94957264957, 0.9264957265, 0.9264957265, 0.9264957265, 0.9264957265, + 0.9264957265, 0.92735042735, 0.95897435897, 0.95128205128, 0.95128205128, 0.95128205128, + 0.95128205128, 1.00512820513, 0.94957264957, 1.00512820513, + ], + tops: [ + 1, 1.09829059829, 1, 1.15042735043, 1.16324786325, 1.08974358974, 1, 1, 1.07264957265, + 1.07264957265, 1, 1, 1, 1, 1, 1.18717948718, 1.09829059829, 1.08717948718, 1.09829059829, + 1.09829059829, 1.07264957265, 1.07264957265, 1.09829059829, 1.07264957265, 1.09829059829, + 1.09829059829, 1, 1, 1, 1, 1, 1.02564102564, 1.10854700855, 1, 1, 1.02307692308, 1, 1, 1, + 1.02307692308, 1, 1, 1, 1, 1, 1, 1, 1.02307692308, 1, 1.02307692308, 1, 1.02307692308, 1, 1, + 1, 1, 1, 1, 1, 1.07264957265, 1.18205128205, 1.07264957265, 1, 1, 1, 1, 1.07264957265, 1, + 1.07264957265, 1, 1.07264957265, 1, 1.07264957265, 1.10854700855, 1.10854700855, + 1.07264957265, 1.07264957265, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.07264957265, + 1.07264957265, 1.07264957265, 1, 1, 1, 1.14188034188, 1.02735042735, 1, 1, 1.07264957265, + 1.07264957265, 1, 1.02222222222, 1, 1, 1, 1, 1.02222222222, 1, 1, 1.0547008547, 1, 1, 1, 1, + 1.07264957265, 1, 1, 1, 1, 1, 1.09572649573, 1.09572649573, 1.09829059829, 1, 1.3641025641, + 1.3641025641, 1.35042735043, 1.26068376068, 1.27863247863, 1.37008547009, 1, 1.02307692308, + 1.3641025641, 1.3641025641, 1.34786324786, 1.27863247863, 1.3641025641, 1.3641025641, + 1.34786324786, 1.27863247863, 1, 1.26068376068, 1.3641025641, 1.3641025641, 1.34786324786, + 1.26068376068, 1.27863247863, 1, 1.07008547009, 1.3641025641, 1.3641025641, 1.34786324786, + 1.27863247863, 1.35641025641, 1, 1.07264957265, 1.13504273504, 1.13504273504, 1.11965811966, + 1.03162393162, 1.04957264957, 1.16581196581, 1, 1, 1.1358974359, 1.1358974359, 1.11965811966, + 1.04957264957, 1.12820512821, 1.13504273504, 1.11965811966, 1.04957264957, 1.06837606838, + 1.03162393162, 1.1358974359, 1.1358974359, 1.11965811966, 1.03162393162, 1.04957264957, 1, 1, + 1.1358974359, 1.1358974359, 1.11965811966, 1.04957264957, 1.1358974359, 1.07264957265, + 1.05042735043, + ], + bottoms: [ + 0, -0.02564102564, 0, -0.11111111111, -0.16324786325, -0.02051282051, -0.02820512821, 0, + -0.22222222222, -0.22222222222, 0, 0, -0.25641025641, 0, -0.02564102564, -0.14444444444, + -0.02564102564, 0, 0, -0.02564102564, 0, -0.02564102564, -0.02564102564, -0.00170940171, + -0.02564102564, -0.02564102564, -0.02564102564, -0.18290598291, 0, 0, 0, -0.02564102564, + -0.11111111111, 0, 0, -0.02820512821, 0, 0, 0, -0.02820512821, 0, 0, -0.02820512821, 0, 0, 0, + 0, -0.02820512821, 0, -0.20427350427, 0, -0.02820512821, 0, -0.02820512821, 0, 0, 0, 0, 0, + -0.22136752137, -0.14957264957, -0.22136752137, 0, -0.47948717949, 0, -0.02820512821, + -0.02820512821, -0.02820512821, -0.02820512821, -0.02820512821, 0, -0.32991452991, 0, 0, + -0.32991452991, 0, 0, 0, 0, -0.02820512821, -0.32991452991, -0.32991452991, 0, -0.02820512821, + -0.02820512821, -0.02820512821, 0, -0.00085470085, 0, -0.32991452991, 0, -0.22136752137, + -0.22136752137, -0.22222222222, 0, 0, -0.33247863248, 0, 0, 0, 0, -0.22136752137, + -0.11111111111, 0, -0.02307692308, 0, 0, 0, 0, -0.02307692308, 0, 0, 0, 0, 0, 0, + -0.32991452991, -0.11111111111, 0, -0.28461538462, 0, 0, 0, 0, 0, 0, -0.33504273504, 0, 0, 0, + 0, 0, 0, 0, -0.28461538462, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.02820512821, -0.02820512821, + -0.02820512821, -0.02820512821, -0.02820512821, 0, -0.07179487179, -0.02820512821, + -0.02820512821, -0.02820512821, -0.02820512821, 0, 0, -0.02820512821, -0.02820512821, + -0.02820512821, -0.02820512821, -0.02820512821, -0.02820512821, -0.02820512821, + -0.02820512821, -0.28461538462, -0.02820512821, -0.02820512821, -0.02820512821, + -0.02820512821, 0, 0, 0, 0, -0.0264957265, 0, -0.02820512821, -0.02820512821, -0.02820512821, + -0.02820512821, -0.02820512821, 0, -0.0735042735, -0.02820512821, -0.02820512821, + -0.02820512821, -0.02820512821, -0.32991452991, -0.32991452991, -0.32991452991, + ], + afterStack: 0.19572649573, + bold: { + advances: [ + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + ], + lefts: [ + 0, 0.3660346249, 0.2176422094, 0.10057708162, 0.13685078318, 0.13025556472, 0.18549051937, + 0.39653751031, 0.4460016488, 0.19950535861, 0.13685078318, 0.06760098928, 0.34377576257, + 0.15498763397, 0.38169826876, 0.13932399011, 0.1384995878, 0.13932399011, 0.09068425392, + 0.11129431162, 0.12613355317, 0.1088211047, 0.1780708986, 0.12530915087, 0.13932399011, + 0.17724649629, 0.38004946414, 0.33305853256, 0, 0.03380049464, 0.0692497939, 0.17312448475, + 0.1483924155, 0, 0.02225886232, 0.05276174773, 0.02390766694, 0.02473206925, 0.08244023083, + 0.05358615004, 0.03709810387, 0.1384995878, 0.09068425392, 0.02225886232, 0.05605935697, 0, + 0, 0.03380049464, 0.10057708162, 0.03297609233, 0.02390766694, 0.10469909316, 0.06760098928, + 0.01813685078, 0, 0, 0.01813685078, 0.03544929926, 0.12448474856, 0.42044517725, + 0.14014839242, 0.20857378401, 0.13767518549, 0, 0.3462489695, 0.07337180544, 0, + 0.09398186315, 0.05111294312, 0.05441055235, 0.12283594394, 0.05441055235, 0.02143446002, + 0.10552349547, 0.14509480627, 0.05688375927, 0.10634789777, 0, 0.04204451772, 0.07089859852, + 0, 0.0593569662, 0.0890354493, 0.12448474856, 0.12201154163, 0.02473206925, 0, 0, + 0.03544929926, 0.03544929926, 0.14591920857, 0.28359439406, 0.42291838417, 0.27782357791, + 0.10305028854, 0, 0.3660346249, 0.14014839242, 0.05111294312, 0.11953833471, 0.03544929926, + 0.42291838417, 0.08161582852, 0.24072547403, 0, 0.22506183017, 0.05853256389, 0, + 0.15498763397, 0, 0, 0.24319868096, 0.06760098928, 0.25144270404, 0.26380873866, + 0.3462489695, 0.02390766694, 0.10305028854, 0.5836768343, 0.33718054411, 0.27947238252, + 0.22341302556, 0.08573784007, 0.00164880462, 0, 0, 0.1384995878, 0, 0, 0, 0, 0, 0, 0, + 0.05276174773, 0.02473206925, 0.02473206925, 0.02473206925, 0.02473206925, 0.1384995878, + 0.1384995878, 0.1384995878, 0.1384995878, 0, 0, 0.03380049464, 0.03380049464, 0.03380049464, + 0.03380049464, 0.03380049464, 0.1681780709, 0.01813685078, 0.01813685078, 0.01813685078, + 0.01813685078, 0.01813685078, 0.03544929926, 0.10057708162, 0.02061005771, 0.07337180544, + 0.07337180544, 0.07337180544, 0.07337180544, 0.07337180544, 0.07337180544, 0, 0.09398186315, + 0.05441055235, 0.05441055235, 0.05441055235, 0.05441055235, 0.10552349547, 0.10552349547, + 0.10552349547, 0.10552349547, 0.07502061006, 0.04204451772, 0.07089859852, 0.07089859852, + 0.07089859852, 0.07089859852, 0.07089859852, 0.06760098928, 0.03792250618, 0.02473206925, + 0.02473206925, 0.02473206925, 0.02473206925, 0.03544929926, 0, 0.03544929926, + ], + rights: [ + 1.01319043693, 0.63643858203, 0.78730420445, 0.90849134378, 0.87551525144, 0.88623248145, + 0.92497938994, 0.6141797197, 0.82522671063, 0.57873042045, 0.87304204452, 0.94558944765, + 0.69249793899, 0.86067600989, 0.63561417972, 0.87469084913, 0.87551525144, 0.87633965375, + 0.86067600989, 0.89694971146, 0.85902720528, 0.89694971146, 0.91426215993, 0.85902720528, + 0.87633965375, 0.91508656224, 0.63561417972, 0.71228359439, 0.94558944765, 0.98186314922, + 1.03627370157, 0.87551525144, 0.84006595218, 1.05193734542, 0.96867271228, 0.95630667766, + 0.93239901072, 0.93322341303, 0.99093157461, 1.00412201154, 0.98516075845, 0.87469084913, + 1.03627370157, 1.02143446002, 0.96949711459, 1.05276174773, 1.00082440231, 0.98103874691, + 0.97444352844, 0.98103874691, 1.04863973619, 0.91178895301, 0.94311624073, 0.99752679308, + 1.05193734542, 1.03297609233, 1, 0.98103874691, 0.89365210223, 0.80461665293, 0.87469084913, + 0.59274525969, 0.87469084913, 1.08656224237, 0.66776586974, 0.96949711459, 0.96784830998, + 0.95877988458, 1.03627370157, 0.93157460841, 0.96537510305, 1.00329760923, 0.98598516076, + 0.90601813685, 0.77658697444, 0.9703215169, 0.90684253916, 1.05605935697, 0.96949711459, + 0.94558944765, 0.96702390767, 1.04039571311, 0.96702390767, 0.89365210223, 0.99752679308, + 0.9703215169, 1.0197856554, 1.01648804617, 0.98186314922, 0.98268755153, 0.8812860676, + 0.73124484749, 0.59192085738, 0.72547403133, 0.9109645507, 1.01319043693, 0.63643858203, + 0.84583676834, 0.93239901072, 0.89447650453, 0.98103874691, 0.59192085738, 0.93487221764, + 0.7724649629, 1.01813685078, 0.80791426216, 0.93652102226, 0.94476504534, 0.86067600989, + 1.01813685078, 1.08656224237, 0.76916735367, 0.94558944765, 0.72547403133, 0.74690849134, + 0.66776586974, 0.96949711459, 0.91755976917, 0.79719703215, 0.66199505359, 0.73371805441, + 0.79142621599, 0.96372629843, 1.01236603462, 1.07419620775, 1.00329760923, 0.84089035449, + 1.05193734543, 1.05193734543, 1.05193734542, 1.05193734542, 1.05193734542, 1.05193734542, + 1.05111294312, 0.95630667766, 0.93322341303, 0.93322341303, 0.93322341303, 0.93322341303, + 0.87469084914, 0.87469084914, 0.87469084914, 0.87469084914, 0.93404781533, 1.00082440231, + 0.98103874691, 0.98103874691, 0.98103874691, 0.98103874691, 0.98103874691, 0.84583676834, + 0.99835119538, 0.99752679307, 0.99752679307, 0.99752679307, 0.99752679307, 0.98103874691, + 0.97444352844, 0.89694971146, 0.96949711459, 0.96949711459, 0.96949711459, 0.96949711459, + 0.96949711459, 0.96949711459, 1.03380049464, 0.95877988458, 0.93157460841, 0.93157460841, + 0.93157460841, 0.93157460841, 0.90601813685, 0.90601813685, 0.90601813685, 0.90601813685, + 0.91178895301, 0.96949711459, 0.94558944765, 0.94558944765, 0.94558944765, 0.94558944765, + 0.94558944765, 0.94558944765, 0.96867271228, 0.9703215169, 0.9703215169, 0.9703215169, + 0.9703215169, 0.98268755153, 0.96702390767, 0.98268755153, + ], + tops: [ + 1, 1.09480626546, 1, 1.1582852432, 1.17312448475, 1.0593569662, 1, 1, 1.08408903545, + 1.08408903545, 1, 1, 1, 1, 1, 1.19208573784, 1.09398186315, 1.09398186315, 1.09398186315, + 1.09398186315, 1.06677658697, 1.06677658697, 1.09398186315, 1.06677658697, 1.09398186315, + 1.09398186315, 1, 1, 1, 1, 1, 1.02473206925, 1.09398186315, 1, 1, 1.02473206925, 1, 1, 1, + 1.02473206925, 1, 1, 1, 1, 1, 1, 1, 1.02473206925, 1, 1.02473206925, 1, 1.02473206925, 1, 1, + 1, 1, 1, 1, 1, 1.06677658697, 1.19208573784, 1.06677658697, 1, 1, 1, 1, 1.0692497939, 1, + 1.0692497939, 1, 1.0692497939, 1, 1.0692497939, 1.0692497939, 1.0692497939, 1.0692497939, + 1.0692497939, 1, 1, 1, 1, 1, 1, 1, 1.01401483924, 1, 1, 1, 1, 1, 1, 1.06760098928, + 1.06677658697, 1.06760098928, 1, 1, 1, 1.15663643858, 1.02390766694, 1, 1, 1.06677658697, + 1.07419620775, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.18961253092, 1, 1, 1, 1, 1.06677658697, 1, 1, 1, + 1, 1, 1.09645507007, 1.09645507007, 1.09645507007, 1, 1.38829348722, 1.38829348722, + 1.37015663644, 1.30255564716, 1.32234130256, 1.4056059357, 1, 1.02473206925, 1.38829348722, + 1.38829348722, 1.37015663644, 1.32234130256, 1.38829348722, 1.38829348722, 1.37015663644, + 1.32234130256, 1, 1.30255564716, 1.38829348722, 1.38829348722, 1.37015663644, 1.30255564716, + 1.32234130256, 1, 1.08408903545, 1.38829348722, 1.38829348722, 1.37015663644, 1.32234130256, + 1.38829348722, 1, 1.0692497939, 1.12695795548, 1.12530915087, 1.10717230008, 1.0395713108, + 1.0593569662, 1.15086562242, 1, 1, 1.12695795548, 1.12530915087, 1.10717230008, + 1.0593569662, 1.12695795548, 1.12530915087, 1.10717230008, 1.0593569662, 1.06677658697, + 1.0395713108, 1.12695795548, 1.12530915087, 1.10717230008, 1.0395713108, 1.0593569662, 1, 1, + 1.12695795548, 1.12530915087, 1.10717230008, 1.0593569662, 1.12530915087, 1.0692497939, + 1.0593569662, + ], + bottoms: [ + 0, -0.02473206925, 0, -0.1582852432, -0.21104699093, -0.02473206925, -0.02473206925, 0, + -0.26380873866, -0.26380873866, 0, 0, -0.27122835944, 0, -0.02720527617, -0.19455894476, + -0.02473206925, 0, 0, -0.02473206925, 0, -0.02473206925, -0.02473206925, -0.00164880462, + -0.02473206925, -0.02473206925, -0.0296784831, -0.17889530091, 0, 0, 0, -0.02390766694, + -0.14014839242, 0, 0, -0.02473206925, 0, 0, 0, -0.02473206925, 0, 0, -0.02473206925, 0, 0, + 0, 0, -0.02473206925, 0, -0.24979389942, 0, -0.02473206925, 0, -0.02473206925, 0, 0, 0, 0, + 0, -0.26380873866, -0.18961253092, -0.26380873866, 0, -0.50700741962, 0, -0.02802967848, + -0.02720527617, -0.02802967848, -0.02720527617, -0.02720527617, 0, -0.35284418796, 0, 0, + -0.35284418796, 0, 0, 0, 0, -0.02720527617, -0.35284418796, -0.35284418796, 0, + -0.02720527617, -0.02720527617, -0.02720527617, 0, 0, 0, -0.35284418796, 0, -0.26380873866, + -0.26380873866, -0.26380873866, 0, 0, -0.34872217642, -0.05276174773, 0, 0, 0, + -0.26380873866, -0.14344600165, 0, -0.02390766694, 0, 0, 0, 0, -0.02390766694, 0, 0, 0, 0, + 0, 0, -0.35284418796, -0.14674361088, 0, -0.30255564716, 0, 0, 0, 0, 0, 0, -0.35449299258, + 0, 0, 0, 0, 0, 0, 0, -0.3165704864, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.02473206925, + -0.02473206925, -0.02473206925, -0.02473206925, -0.02473206925, 0, -0.12036273702, + -0.02473206925, -0.02473206925, -0.02473206925, -0.02473206925, 0, 0, -0.02720527617, + -0.02802967848, -0.02802967848, -0.02802967848, -0.02802967848, -0.02802967848, + -0.02802967848, -0.02720527617, -0.30255564716, -0.02720527617, -0.02720527617, + -0.02720527617, -0.02720527617, 0, 0, 0, 0, -0.02885408079, 0, -0.02720527617, + -0.02720527617, -0.02720527617, -0.02720527617, -0.02720527617, 0, -0.12118713932, + -0.02720527617, -0.02720527617, -0.02720527617, -0.02720527617, -0.35284418796, + -0.35284418796, -0.35284418796, + ], + }, }, Georgia: { below: 0.31202223767, @@ -1225,6 +3171,265 @@ export const FONT_METRICS: Readonly> = { -0.00972897846, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01320361362, -0.01320361362, -0.01320361362, ], + lefts: [ + 0, 0.14384989576, 0.08200138985, 0.10701876303, 0.10771369006, 0.07574704656, 0.05211952745, + 0.07505211953, 0.08130646282, 0.04656011119, 0.05976372481, 0.1000694927, 0.06740792217, + 0.05906879778, 0.09798471161, 0.0340514246, 0.07157748436, 0.09103544128, 0.07644197359, + 0.04447533009, 0.0340514246, 0.04100069493, 0.07157748436, 0.06184850591, 0.0722724114, + 0.05837387074, 0.12717164698, 0.09867963864, 0.1341209173, 0.10701876303, 0.1382904795, + 0.07366226546, 0.11674774149, 0, 0.0660180681, 0.05420430855, 0.06532314107, 0.05976372481, + 0.05976372481, 0.05420430855, 0.0681028492, 0.05489923558, 0.00764419736, 0.07088255733, + 0.0681028492, 0.03335649757, 0.01667824878, 0.05559416261, 0.06323835997, 0.05559416261, + 0.0681028492, 0.06532314107, 0.01042390549, 0.05142460042, 0, 0, 0.00903405142, 0, + 0.01876302988, 0.11674774149, 0.06254343294, 0.04656011119, 0.13273106324, 0, 0.22793606671, + 0.05559416261, 0, 0.05003474635, 0.05003474635, 0.05003474635, 0.01667824878, 0.02918693537, + 0.0041695622, 0.0298818624, 0, 0.0041695622, 0.00138985407, 0.03891591383, 0.04239054899, + 0.04864489229, 0.02293259208, 0.05003474635, 0.04239054899, 0.05072967338, 0.00903405142, + 0.02362751911, 0, 0, 0.00833912439, 0, 0.0382209868, 0.05003474635, 0.22307157748, + 0.04656011119, 0.09034051425, 0, 0.14384989576, 0.09798471161, 0.08130646282, 0.11605281445, + 0, 0.22307157748, 0.08408617095, 0.12439193885, 0.05559416261, 0.1084086171, 0.11813759555, + 0.1000694927, 0.05906879778, 0.05559416261, 0, 0.0722724114, 0.10354412787, 0.1021542738, + 0.08825573315, 0.19805420431, 0.08408617095, 0.06879777623, 0.10493398193, 0.21334259903, + 0.15288394719, 0.08061153579, 0.1341209173, 0.09103544128, 0.09103544128, 0.08130646282, + 0.0701876303, 0, 0, 0, 0, 0, 0, 0, 0.05420430855, 0.05976372481, 0.05976372481, 0.05976372481, + 0.05976372481, 0.05489923558, 0.05489923558, 0.05142460042, 0.04586518416, 0.06532314107, + 0.01667824878, 0.05559416261, 0.05559416261, 0.05559416261, 0.05559416261, 0.05559416261, + 0.14454482279, 0.05559416261, 0.05142460042, 0.05142460042, 0.05142460042, 0.05142460042, 0, + 0.06671299514, 0.04100069493, 0.05559416261, 0.05559416261, 0.05559416261, 0.05559416261, + 0.05559416261, 0.05559416261, 0.05628908965, 0.05003474635, 0.05003474635, 0.05003474635, + 0.05003474635, 0.05003474635, 0.02918693537, 0.02988186241, 0, 0, 0.04864489229, + 0.04239054899, 0.04864489229, 0.04864489229, 0.04864489229, 0.04864489229, 0.04864489229, + 0.1000694927, 0.04864489229, 0.02362751911, 0.02362751911, 0.02362751911, 0.02362751911, 0, 0, + 0, + ], + rights: [ + 0.34329395413, 0.33425990271, 0.50382209868, 0.80820013899, 0.76650451703, 1.08756080612, + 1.01042390549, 0.23141070188, 0.4871438499, 0.45239749826, 0.61292564281, 0.81514940931, + 0.29812369701, 0.47324530924, 0.28839471855, 0.60458651842, 0.80194579569, 0.56219596942, + 0.7275886032, 0.71299513551, 0.75330090341, 0.69214732453, 0.74704656011, 0.71507991661, + 0.77623349548, 0.73384294649, 0.31758165393, 0.32939541348, 0.77692842252, 0.80820013899, + 0.78109798471, 0.61084086171, 1.2084781098, 0.98749131341, 0.86726893676, 0.89506601807, + 1.01250868659, 0.89715079917, 0.83321751216, 1.02223766505, 1.08895066018, 0.49895760945, + 0.69909659486, 1.02501737318, 0.8596247394, 1.25503822099, 1.07991660876, 1.00347463516, + 0.82279360667, 1.00347463516, 1.02849200834, 0.74287699792, 0.87004864489, 1.06532314107, + 0.97776233495, 1.40931202224, 1.01250868659, 0.91313412092, 0.84364141765, 0.4871438499, + 0.63307852675, 0.4169562196, 0.78248783878, 0.91869353718, 0.51355107714, 0.69909659486, + 0.74565670605, 0.64280750521, 0.80055594163, 0.65879082696, 0.56011118833, 0.69701181376, + 0.7956914524, 0.38220986796, 0.30993745657, 0.77623349548, 0.37109103544, 1.22237665045, + 0.80681028492, 0.71855455177, 0.76233495483, 0.80194579569, 0.57470465601, 0.56150104239, + 0.47324530924, 0.78457261987, 0.72689367616, 1.07088255733, 0.71021542738, 0.7213342599, + 0.59277275886, 0.56567060459, 0.31132731063, 0.56219596942, 0.82487838777, 0.34329395413, + 0.33425990271, 0.72272411397, 0.80958999305, 0.69840166783, 0.89089645587, 0.31132731063, + 0.62751911049, 0.5872133426, 1.28492008339, 0.64836692147, 0.69284225156, 0.80820013899, + 0.47324530924, 1.28492008339, 0.91869353718, 0.52466990966, 0.81167477415, 0.6254343294, + 0.61153578874, 0.48366921473, 0.78735232801, 0.69492703266, 0.29534398888, 0.49061848506, + 0.54829742877, 0.63099374566, 0.70882557331, 1.38151494093, 1.42043085476, 1.44405837387, + 0.60736622655, 0.98749131341, 0.98749131341, 0.98749131341, 0.98749131341, 0.98749131341, + 0.98749131341, 1.3488533704, 0.89506601807, 0.89715079917, 0.89715079917, 0.89715079917, + 0.89715079917, 0.49895760945, 0.49895760945, 0.50312717165, 0.50868658791, 1.01250868659, + 1.07991660876, 1.00347463516, 1.00347463516, 1.00347463516, 1.00347463516, 1.00347463516, + 0.77067407922, 1.00347463516, 1.06532314107, 1.06532314107, 1.06532314107, 1.06532314107, + 0.91313412092, 0.82626824183, 0.7255038221, 0.69909659486, 0.69909659486, 0.69909659486, + 0.69909659486, 0.69909659486, 0.69909659486, 1.02015288395, 0.64280750521, 0.65879082696, + 0.65879082696, 0.65879082696, 0.65879082696, 0.38220986796, 0.38220986796, 0.38915913829, + 0.39332870049, 0.70465601112, 0.80681028492, 0.71855455177, 0.71855455177, 0.71855455177, + 0.71855455177, 0.71855455177, 0.81514940931, 0.71855455177, 0.78457261988, 0.78457261988, + 0.78457261988, 0.78457261988, 0.7213342599, 0.74496177901, 0.7213342599, + ], + tops: [ + 1, 1.01181375956, 1, 1, 1.05906879778, 1.00972897846, 1.00972897846, 1, 1.06462821404, + 1.06462821404, 1, 1, 1, 1, 1, 1.05837387074, 1, 1, 1, 1, 1, 1, 1.00972897846, 1, + 1.01181375956, 1, 1, 1, 1, 1, 1, 1.00972897846, 1, 1, 1, 1.00764419736, 1, 1, 1, + 1.00764419736, 1, 1, 1, 1, 1, 1, 1, 1.00972897846, 1, 1.00972897846, 1, 1.00833912439, 1, 1, + 1, 1, 1, 1, 1, 1.05559416261, 1.05837387074, 1.05559416261, 1, 1, 1, 1, 1.07574704656, 1, + 1.07574704656, 1, 1.07574704656, 1, 1.07574704656, 1.05281445448, 1.05350938151, + 1.07574704656, 1.07574704656, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.0681028492, + 1.05837387074, 1.0681028492, 1, 1, 1.00486448923, 1, 1.01181375956, 1, 1, 1.05837387074, + 1.00972897846, 1, 1.0319666435, 1, 1, 1, 1, 1.0319666435, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1.0041695622, 1.0041695622, 1.00972897846, 1.00486448923, 1.29812369701, 1.29812369701, + 1.29812369701, 1.28422515636, 1.27936066713, 1.29812369701, 1, 1.00764419736, 1.29812369701, + 1.29812369701, 1.29812369701, 1.28769979152, 1.29812369701, 1.29812369701, 1.29812369701, + 1.28769979152, 1, 1.29117442669, 1.29812369701, 1.29812369701, 1.29812369701, 1.29117442669, + 1.28769979152, 1, 1.02501737318, 1.29812369701, 1.29812369701, 1.29812369701, 1.28769979152, + 1.29812369701, 1, 1.07713690063, 1.06879777623, 1.06879777623, 1.07574704656, 1.03544127867, + 1.03335649757, 1.08339124392, 1, 1, 1.06879777623, 1.06879777623, 1.07157748436, + 1.03335649757, 1.06879777623, 1.06879777623, 1.07157748436, 1.03335649757, 1.08130646282, + 1.03544127867, 1.06879777623, 1.06879777623, 1.07157748436, 1.03544127867, 1.03335649757, 1, + 1, 1.06879777623, 1.06879777623, 1.07157748436, 1.03335649757, 1.06879777623, 1.07574704656, + 1.03335649757, + ], + bottoms: [ + 0, -0.01389854065, 0, 0, -0.20778318277, -0.02223766505, -0.02432244614, 0, -0.22793606671, + -0.22793606671, 0, 0, -0.24600416956, 0, -0.01389854065, -0.29464906185, -0.02223766505, 0, 0, + -0.25364836692, -0.25364836692, -0.25364836692, -0.02223766505, -0.25364836692, + -0.02362751911, -0.25712300208, -0.01389854065, -0.24600416956, 0, 0, 0, -0.01389854065, + -0.21751216122, 0, 0, -0.02362751911, 0, 0, 0, -0.02362751911, 0, 0, -0.02362751911, 0, 0, 0, + -0.00972897846, -0.02362751911, 0, -0.26754690757, 0, -0.02015288395, 0, -0.02362751911, + -0.01250868659, -0.01250868659, 0, 0, 0, -0.21542738013, -0.29464906185, -0.21542738013, 0, + -0.19596942321, 0, -0.01737317582, -0.03683113273, -0.01806810285, -0.01945795691, + -0.01806810285, 0, -0.3085476025, 0, 0, -0.3085476025, 0, 0, 0, 0, -0.02084781098, + -0.3085476025, -0.3085476025, 0, -0.01806810285, -0.01459346769, -0.01737317582, + -0.00625434329, -0.00486448923, 0, -0.3085476025, 0, -0.23141070188, -0.29464906185, + -0.23141070188, 0, 0, -0.02223766505, -0.20778318277, 0, 0, 0, -0.29464906185, -0.17929117443, + 0, -0.19527449618, 0, 0, 0, 0, -0.19527449618, 0, 0, 0, 0, 0, 0, -0.3085476025, + -0.15010423905, 0, -0.3085476025, 0, 0, 0, -0.01389854065, 0, -0.01389854065, -0.01806810285, + 0, 0, 0, 0, 0, 0, 0, -0.3085476025, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00972897846, -0.02362751911, + -0.02362751911, -0.02362751911, -0.02362751911, -0.02362751911, 0, -0.05837387074, + -0.02362751911, -0.02362751911, -0.02362751911, -0.02362751911, 0, 0, -0.00764419736, + -0.01737317582, -0.01737317582, -0.01737317582, -0.01737317582, -0.01737317582, + -0.01737317582, -0.01806810285, -0.3085476025, -0.01806810285, -0.01806810285, -0.01806810285, + -0.01806810285, 0, 0, 0, 0, -0.02084781098, 0, -0.02084781098, -0.02084781098, -0.02084781098, + -0.02084781098, -0.02084781098, 0, -0.05628908965, -0.01737317582, -0.01737317582, + -0.01737317582, -0.01737317582, -0.3085476025, -0.3085476025, -0.3085476025, + ], + afterStack: 0.07157748436, + bold: { + advances: [ + 0.36136205698, 0.53578874218, 0.7255038221, 1.00069492703, 0.91174426685, 1.25156358582, + 1.13759555247, 0.382904795, 0.63585823489, 0.63585823489, 0.68589298124, 1.00069492703, + 0.46699096595, 0.53926337735, 0.46699096595, 0.67129951355, 0.9979152189, 0.69701181376, + 0.8915913829, 0.88881167477, 0.92425295344, 0.85267546908, 0.92216817234, 0.78874218207, + 0.96247394024, 0.92216817234, 0.52258512856, 0.52258512856, 1.00069492703, 1.00069492703, + 1.00069492703, 0.78040305768, 1.37595552467, 1.07922168172, 1.07783182766, 1.01806810285, + 1.18693537179, 1.02640722724, 0.95552466991, 1.14871438499, 1.29951355108, 0.63446838082, + 0.84711605281, 1.16261292564, 0.97567755386, 1.45656706046, 1.19457956915, 1.16678248784, + 0.9979152189, 1.16678248784, 1.13481584434, 0.92355802641, 0.97359277276, 1.18624044475, + 1.08478109798, 1.60319666435, 1.15079916609, 1.04169562196, 0.98123697012, 0.63585823489, + 0.67129951355, 0.63585823489, 1.00069492703, 1.00069492703, 0.71160528145, 0.84781097985, + 0.91869353718, 0.75608061154, 0.94371091035, 0.81375955525, 0.55941626129, 0.82070882557, + 0.96733842946, 0.50312717165, 0.49270326616, 0.89923558026, 0.48992355803, 1.44544822794, + 0.98193189715, 0.90479499653, 0.936066713, 0.92286309937, 0.74009728978, 0.72967338429, + 0.56567060459, 0.96316886727, 0.80681028492, 1.22863099375, 0.83669214732, 0.79986101459, + 0.74774148714, 0.71160528145, 0.55177206393, 0.71160528145, 1.00069492703, 0.36136205698, + 0.53578874218, 0.8617095205, 0.98193189715, 1.00069492703, 1.04239054899, 0.55177206393, + 0.80194579569, 0.71160528145, 1.340514246, 0.78526754691, 0.86865879083, 1.00069492703, + 0.53926337735, 1.340514246, 1.00069492703, 0.59763724809, 1.00069492703, 0.78526754691, + 0.78526754691, 0.71160528145, 0.95066018068, 0.78109798471, 0.4808895066, 0.71160528145, + 0.78526754691, 0.78526754691, 0.86865879083, 1.52466990966, 1.52466990966, 1.52466990966, + 0.78040305768, 1.07922168172, 1.07922168172, 1.07922168172, 1.07922168172, 1.07922168172, + 1.07922168172, 1.52258512856, 1.01806810285, 1.02640722724, 1.02640722724, 1.02640722724, + 1.02640722724, 0.63446838082, 0.63446838082, 0.63446838082, 0.63446838082, 1.18693537179, + 1.19457956915, 1.16678248784, 1.16678248784, 1.16678248784, 1.16678248784, 1.16678248784, + 1.00069492703, 1.16678248784, 1.18624044475, 1.18624044475, 1.18624044475, 1.18624044475, + 1.04169562196, 1.00764419736, 0.936066713, 0.84781097985, 0.84781097985, 0.84781097985, + 0.84781097985, 0.84781097985, 0.84781097985, 1.22029186935, 0.75608061154, 0.81375955525, + 0.81375955525, 0.81375955525, 0.81375955525, 0.50312717165, 0.50312717165, 0.50312717165, + 0.50312717165, 0.90757470466, 0.98193189715, 0.90479499653, 0.90479499653, 0.90479499653, + 0.90479499653, 0.90479499653, 1.00069492703, 0.90479499653, 0.96316886727, 0.96316886727, + 0.96316886727, 0.96316886727, 0.79986101459, 0.91799861015, 0.79986101459, + ], + lefts: [ + 0, 0.13273106324, 0.08339124392, 0.10771369006, 0.07366226546, 0.06323835997, 0.04794996525, + 0.07644197359, 0.07991660876, 0.04725503822, 0.05628908965, 0.11396803336, 0.09520500347, + 0.05906879778, 0.09659485754, 0.01876302988, 0.07157748436, 0.08130646282, 0.07644197359, + 0.0361362057, 0.0340514246, 0.03891591383, 0.07157748436, 0.06184850591, 0.0722724114, + 0.05837387074, 0.12439193885, 0.12300208478, 0.14523974983, 0.12856150104, 0.16052814454, + 0.05489923558, 0.10979847116, 0, 0.04794996525, 0.04933981932, 0.04656011119, 0.04794996525, + 0.04794996525, 0.04933981932, 0.04794996525, 0.04378040306, 0.01181375956, 0.04656011119, + 0.04794996525, 0.02432244614, 0.02015288395, 0.04933981932, 0.04794996525, 0.04933981932, + 0.04794996525, 0.04447533009, 0.00903405142, 0.03961084086, 0, 0, 0.00625434329, 0, + 0.01181375956, 0.12856150104, 0.04725503822, 0.04794996525, 0.14523974983, 0, 0.15149409312, + 0.05489923558, 0, 0.04933981932, 0.04933981932, 0.04933981932, 0.0041695622, 0.01945795691, + 0.0020847811, 0.02293259208, 0, 0.0020847811, 0, 0.0298818624, 0.03057678944, 0.04933981932, + 0.00764419736, 0.04933981932, 0.03057678944, 0.04656011119, 0, 0.01111883252, 0, 0, + 0.0020847811, 0, 0.03057678944, 0.05003474635, 0.21681723419, 0.04794996525, 0.10076441974, + 0, 0.13273106324, 0.09034051425, 0.08617095205, 0.1341209173, 0, 0.21681723419, + 0.08408617095, 0.07296733843, 0.05628908965, 0.09034051425, 0.10284920083, 0.11396803336, + 0.05906879778, 0.05628908965, 0, 0.05976372481, 0.11396803336, 0.12300208478, 0.10076441974, + 0.19527449618, 0.07366226546, 0.05976372481, 0.10354412787, 0.19666435024, 0.19110493398, + 0.06184850591, 0.08339124392, 0.10076441974, 0.10076441974, 0.07991660876, 0.07505211953, 0, + 0, 0, 0, 0, 0, 0, 0.04933981932, 0.04794996525, 0.04794996525, 0.04794996525, 0.04794996525, + 0.04378040306, 0.04378040306, 0.04378040306, 0.03474635163, 0.04656011119, 0.02015288395, + 0.04933981932, 0.04933981932, 0.04933981932, 0.04933981932, 0.04933981932, 0.15357887422, + 0.04933981932, 0.03961084086, 0.03961084086, 0.03961084086, 0.03961084086, 0, 0.04794996525, + 0.02501737318, 0.05489923558, 0.05489923558, 0.05489923558, 0.05489923558, 0.05489923558, + 0.05489923558, 0.05489923558, 0.04933981932, 0.04933981932, 0.04933981932, 0.04933981932, + 0.04933981932, 0.02293259208, 0.02293259208, 0, 0, 0.04933981932, 0.03057678944, + 0.04933981932, 0.04933981932, 0.04933981932, 0.04933981932, 0.04933981932, 0.11396803336, + 0.02432244614, 0.01111883252, 0.01111883252, 0.01111883252, 0.01111883252, 0, 0, 0, + ], + rights: [ + 0.36136205698, 0.40305767894, 0.64211257818, 0.89298123697, 0.83877692842, 1.18832522585, + 1.14384989576, 0.3064628214, 0.5892981237, 0.55663655316, 0.63029881862, 0.88533703961, + 0.3745656706, 0.48019457957, 0.37109103544, 0.62404447533, 0.92633773454, 0.6574009729, + 0.829742877, 0.81723419041, 0.87630298819, 0.79291174427, 0.8637943016, 0.79499652536, + 0.89020152884, 0.85059068798, 0.39888811675, 0.40236275191, 0.84016678249, 0.87213342599, + 0.85545517721, 0.70604586518, 1.27171646977, 1.11813759555, 1.01876302988, 0.99930507297, + 1.13759555247, 0.99166087561, 0.9339819319, 1.14593467686, 1.25156358582, 0.59068797776, + 0.81028492008, 1.2063933287, 0.97567755386, 1.40305767894, 1.18068102849, 1.11744266852, + 0.97220291869, 1.11744266852, 1.17998610146, 0.87074357193, 0.96455872133, 1.18346073662, + 1.11327310632, 1.62960389159, 1.15288394719, 1.08825573315, 0.97081306463, 0.58860319666, + 0.65253648367, 0.50799166088, 0.85684503127, 1.0041695622, 0.5149409312, 0.83460736623, + 0.86935371786, 0.75399583044, 0.93815149409, 0.78735232801, 0.69770674079, 0.81862404448, + 0.94371091035, 0.47949965254, 0.38498957609, 0.9318971508, 0.46490618485, 1.42043085476, + 0.95760945101, 0.85545517721, 0.88672689368, 0.94162612926, 0.73245309243, 0.68450312717, + 0.55733148019, 0.94649061849, 0.83252258513, 1.2383599722, 0.83252258513, 0.8255733148, + 0.71438498958, 0.66435024322, 0.33564975678, 0.66226546213, 0.8999305073, 0.36136205698, + 0.40305767894, 0.81723419041, 0.8999305073, 0.86518415566, 1.05767894371, 0.33564975678, + 0.71785962474, 0.63863794302, 1.28492008339, 0.73314801946, 0.78526754691, 0.87977762335, + 0.48019457957, 1.28492008339, 1.0041695622, 0.53717859625, 0.88533703961, 0.69562195969, + 0.67963863794, 0.55872133426, 0.93467685893, 0.74704656011, 0.37804030577, 0.50590687978, + 0.62890896456, 0.72272411397, 0.76580958999, 1.43710910354, 1.47046560111, 1.46838082001, + 0.72619874913, 1.11813759555, 1.11813759555, 1.11813759555, 1.11813759555, 1.11813759555, + 1.11813759555, 1.48783877693, 0.99930507297, 0.99166087561, 0.99166087561, 0.99166087561, + 0.99166087561, 0.59068797776, 0.59068797776, 0.59068797776, 0.60041695622, 1.13759555247, + 1.18068102849, 1.11744266852, 1.11744266852, 1.11744266852, 1.11744266852, 1.11744266852, + 0.84642112578, 1.11744266852, 1.18346073662, 1.18346073662, 1.18346073662, 1.18346073662, + 1.08825573315, 0.97220291869, 0.88672689368, 0.83460736623, 0.83460736623, 0.83460736623, + 0.83460736623, 0.83460736623, 0.83460736623, 1.19388464211, 0.75399583044, 0.78735232801, + 0.78735232801, 0.78735232801, 0.78735232801, 0.47949965254, 0.47949965254, 0.47949965254, + 0.49965253648, 0.85545517721, 0.95760945101, 0.85545517721, 0.85545517721, 0.85545517721, + 0.85545517721, 0.85545517721, 0.88603196664, 0.87491313412, 0.94649061849, 0.94649061849, + 0.94649061849, 0.94649061849, 0.8255733148, 0.86865879083, 0.8255733148, + ], + tops: [ + 1, 1.00555941626, 1, 1, 1.05906879778, 1.01459346769, 1.01320361362, 1, 1.06462821404, + 1.06462821404, 1, 1, 1, 1, 1, 1.05837387074, 1, 1, 1, 1, 1, 1, 1.01320361362, 1, + 1.01459346769, 1, 1, 1, 1, 1, 1, 1.00903405142, 1, 1, 1, 1.01320361362, 1, 1, 1, + 1.01320361362, 1, 1, 1, 1, 1, 1, 1, 1.01320361362, 1, 1.01320361362, 1, 1.01320361362, 1, 1, + 1, 1, 1, 1, 1, 1.05559416261, 1.05837387074, 1.05559416261, 1, 1, 1, 1, 1.07574704656, 1, + 1.07574704656, 1, 1.07574704656, 1, 1.07574704656, 1.07574704656, 1.07574704656, + 1.07574704656, 1.07574704656, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.0681028492, + 1.05837387074, 1.0681028492, 1, 1, 1.00555941626, 1, 1.01459346769, 1, 1, 1.05837387074, + 1.01042390549, 1, 1.0319666435, 1, 1, 1, 1, 1.0319666435, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1.00694927033, 1.00694927033, 1.01320361362, 1.00903405142, 1.29812369701, + 1.29812369701, 1.29812369701, 1.29812369701, 1.29117442669, 1.29812369701, 1, 1.01320361362, + 1.29812369701, 1.29812369701, 1.29812369701, 1.29812369701, 1.29812369701, 1.29812369701, + 1.29812369701, 1.29812369701, 1, 1.29812369701, 1.29812369701, 1.29812369701, 1.29812369701, + 1.29812369701, 1.29812369701, 1, 1.04864489229, 1.29812369701, 1.29812369701, 1.29812369701, + 1.29812369701, 1.29812369701, 1, 1.07713690063, 1.07574704656, 1.07574704656, 1.07574704656, + 1.04447533009, 1.05420430855, 1.08269631689, 1, 1, 1.07574704656, 1.07574704656, + 1.07574704656, 1.05420430855, 1.07574704656, 1.07574704656, 1.07574704656, 1.05420430855, + 1.07574704656, 1.04447533009, 1.07574704656, 1.07574704656, 1.07574704656, 1.04447533009, + 1.05420430855, 1, 1, 1.07574704656, 1.07574704656, 1.07574704656, 1.05420430855, + 1.07574704656, 1.07574704656, 1.05420430855, + ], + bottoms: [ + 0, -0.02015288395, 0, 0, -0.20778318277, -0.02432244614, -0.02432244614, 0, -0.22793606671, + -0.22793606671, 0, 0, -0.27032661571, 0, -0.02015288395, -0.29464906185, -0.02362751911, 0, + 0, -0.25642807505, -0.25642807505, -0.25642807505, -0.02432244614, -0.25642807505, + -0.02571230021, -0.26059763725, -0.02015288395, -0.27032661571, 0, 0, 0, -0.02015288395, + -0.22446143155, 0, 0, -0.02710215427, 0, 0, 0, -0.02710215427, 0, 0, -0.02710215427, 0, 0, + 0, -0.00555941626, -0.02710215427, 0, -0.28839471855, 0, -0.02710215427, 0, -0.02710215427, + -0.01111883252, -0.01111883252, 0, 0, 0, -0.21542738013, -0.29464906185, -0.21542738013, 0, + -0.20986796386, 0, -0.02223766505, -0.03544127867, -0.02223766505, -0.02223766505, + -0.02223766505, 0, -0.3085476025, 0, 0, -0.3085476025, 0, 0, 0, 0, -0.02223766505, + -0.3085476025, -0.3085476025, 0, -0.02362751911, -0.01876302988, -0.02084781098, + -0.00625434329, -0.00625434329, 0, -0.3085476025, 0, -0.23141070188, -0.29464906185, + -0.23141070188, 0, 0, -0.02015288395, -0.20778318277, 0, 0, 0, -0.29464906185, + -0.16122307158, 0, -0.19527449618, 0, 0, 0, 0, -0.19527449618, 0, 0, 0, 0, 0, 0, + -0.3085476025, -0.15010423905, 0, -0.3085476025, 0, 0, 0, -0.01389854065, 0, -0.01389854065, + -0.02015288395, 0, 0, 0, 0, 0, 0, 0, -0.3085476025, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.00555941626, -0.02710215427, -0.02710215427, -0.02710215427, -0.02710215427, + -0.02710215427, 0, -0.0660180681, -0.02710215427, -0.02710215427, -0.02710215427, + -0.02710215427, 0, 0, -0.00764419736, -0.02223766505, -0.02223766505, -0.02223766505, + -0.02223766505, -0.02223766505, -0.02223766505, -0.02223766505, -0.3085476025, + -0.02223766505, -0.02223766505, -0.02223766505, -0.02223766505, 0, 0, 0, 0, -0.02223766505, + 0, -0.02223766505, -0.02223766505, -0.02223766505, -0.02223766505, -0.02223766505, + -0.00069492703, -0.08130646282, -0.02084781098, -0.02084781098, -0.02084781098, + -0.02084781098, -0.3085476025, -0.3085476025, -0.3085476025, + ], + }, }, "Segoe UI": { below: 0.35843793584, @@ -1282,6 +3487,262 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, -0.01394700139, 0, -0.03138075314, -0.03835425384, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.12552301255, 0.11366806137, 0.0230125523, 0.1129707113, 0.05578800558, 0.0829846583, + 0.11366806137, 0.09762900976, 0.01534170153, 0.0529986053, 0.16178521618, 0.02719665272, + 0.10041841004, 0.07810320781, 0, 0.059972106, 0.1589958159, 0.0760111576, 0.08577405858, + 0.00976290098, 0.11436541144, 0.07740585774, 0.06834030683, 0.06276150628, 0.06555090656, + 0.07810320781, 0.02719665272, 0.18967921897, 0.16178521618, 0.18967921897, 0.09135285914, + 0.11994421199, 0.01534170153, 0.13110181311, 0.06555090656, 0.13110181311, 0.13110181311, + 0.13110181311, 0.06555090656, 0.13110181311, 0.13110181311, 0.01394700139, 0.13110181311, + 0.13110181311, 0.13110181311, 0.13110181311, 0.06555090656, 0.13110181311, 0.06555090656, + 0.13110181311, 0.08437935844, 0.02859135286, 0.11854951186, 0.01255230126, 0.01813110181, + 0.01813110181, 0.01255230126, 0.0230125523, 0.13947001395, 0, 0.0369595537, 0.16039051604, 0, + 0.05718270572, 0.06276150628, 0.11576011158, 0.06694560669, 0.06694560669, 0.06694560669, + 0.0369595537, 0.06694560669, 0.11576011158, 0.10041841004, 0, 0.11576011158, 0.11576011158, + 0.11576011158, 0.11576011158, 0.06694560669, 0.11576011158, 0.06694560669, 0.11576011158, + 0.07252440725, 0.029986053, 0.10041841004, 0.00976290098, 0.01673640167, 0.01813110181, + 0.00976290098, 0.0230125523, 0.06415620642, 0.11994421199, 0.0460251046, 0.14574616457, 0, + 0.12552301255, 0.12831241283, 0.07391910739, 0.06973500697, 0.04741980474, 0.11994421199, + 0.09135285914, 0.08716875872, 0.1129707113, 0.05718270572, 0.06415620642, 0.16178521618, + 0.10041841004, 0.21757322176, 0, 0.07531380753, 0.16178521618, 0.07252440725, 0.089958159, + 0.09414225941, 0.11576011158, 0.05857740586, 0.07810320781, 0.03556485356, 0.05578800558, + 0.05439330544, 0.06276150628, 0.05578800558, 0.05578800558, 0.089958159, 0.09972105997, + 0.01534170154, 0.01534170154, 0.01534170153, 0.01534170153, 0.01534170153, 0.01534170153, + 0.0069735007, 0.06555090656, 0.13110181311, 0.13110181311, 0.13110181311, 0.13110181311, + 0.01882845188, 0.08368200837, 0, 0, 0.01952580195, 0.13110181311, 0.06555090656, + 0.06555090656, 0.06555090656, 0.06555090656, 0.06555090656, 0.18688981869, 0.06555090656, + 0.11854951186, 0.11854951186, 0.11854951186, 0.11854951186, 0.01255230126, 0.13110181311, + 0.11576011158, 0.06276150628, 0.06276150628, 0.06276150628, 0.06276150628, 0.06276150628, + 0.06276150628, 0.06276150628, 0.0669456067, 0.0669456067, 0.0669456067, 0.0669456067, + 0.0669456067, 0, 0.06136680614, 0, 0, 0.0669456067, 0.11576011158, 0.0669456067, 0.0669456067, + 0.0669456067, 0.0669456067, 0.0669456067, 0.16178521618, 0.03417015342, 0.10041841004, + 0.10041841004, 0.10041841004, 0.10041841004, 0.00976290098, 0.11576011158, 0.00976290098, + ], + rights: [ + 0.39121338912, 0.28033472803, 0.44630404463, 0.81311018131, 0.68131101813, 1.11576011158, + 1.11436541144, 0.21478382148, 0.4170153417, 0.33612273361, 0.54393305439, 0.81729428173, + 0.22036262204, 0.48117154812, 0.23430962343, 0.56694560669, 0.71129707113, 0.50488145049, + 0.69316596932, 0.66457461646, 0.72105997211, 0.67573221757, 0.71269177127, 0.70432357043, + 0.71129707113, 0.70013947001, 0.23430962343, 0.23570432357, 0.78940027894, 0.81729428173, + 0.78940027894, 0.56973500697, 1.24686192469, 0.90516039052, 0.74686192469, 0.81171548117, + 0.93584379358, 0.66108786611, 0.63877266388, 0.87866108787, 0.88284518828, 0.24825662483, + 0.3870292887, 0.82705718271, 0.64993026499, 1.15062761506, 0.93723849372, 1.01115760112, + 0.74267782427, 1.09693165969, 0.8479776848, 0.69037656904, 0.72245467225, 0.86262203626, + 0.87447698745, 1.31659693166, 0.82147838215, 0.7810320781, 0.78382147838, 0.39609483961, + 0.55648535565, 0.29288702929, 0.81868898187, 0.59274755927, 0.32845188285, 0.62691771269, + 0.77266387727, 0.60390516039, 0.72524407252, 0.68967921897, 0.46861924686, 0.72524407252, + 0.70850767085, 0.24965132497, 0.24965132497, 0.70850767085, 0.23012552301, 1.12970711297, + 0.70850767085, 0.76987447699, 0.77266387727, 0.72524407252, 0.48814504881, 0.5460251046, + 0.4470013947, 0.69316596932, 0.67712691771, 1.01534170153, 0.63737796374, 0.68410041841, + 0.61366806137, 0.3870292887, 0.22315202232, 0.36820083682, 0.83263598326, 0.39121338912, + 0.28033472803, 0.66387726639, 0.70153417015, 0.72384937238, 0.72663877266, 0.22315202232, + 0.56276150628, 0.49372384937, 1.15829846583, 0.47977684798, 0.66108786611, 0.81729428173, + 0.48117154812, 1.05369595537, 0.59274755927, 0.46164574616, 0.81729428173, 0.45885634589, + 0.45606694561, 0.36541143654, 0.73082287308, 0.58158995816, 0.23430962343, 0.27266387727, + 0.31380753138, 0.559972106, 0.66108786611, 1.18967921897, 1.2189679219, 1.2350069735, + 0.57810320781, 0.90516039052, 0.90516039052, 0.90516039052, 0.90516039052, 0.90516039052, + 0.90516039052, 1.16248256625, 0.81171548117, 0.66108786611, 0.66108786611, 0.66108786611, + 0.66108786611, 0.29009762901, 0.3549511855, 0.39051603905, 0.39609483961, 0.93584379359, + 0.93723849372, 1.01115760112, 1.01115760112, 1.01115760112, 1.01115760112, 1.01115760112, + 0.79079497908, 1.01115760112, 0.86262203626, 0.86262203626, 0.86262203626, 0.86262203626, + 0.7810320781, 0.74267782427, 0.7280334728, 0.62691771269, 0.62691771269, 0.62691771269, + 0.62691771269, 0.62691771269, 0.62691771269, 1.13110181311, 0.60390516039, 0.68967921897, + 0.68967921897, 0.68967921897, 0.68967921897, 0.25732217573, 0.33263598326, 0.36192468619, + 0.36820083682, 0.73082287308, 0.70850767085, 0.76987447699, 0.76987447699, 0.76987447699, + 0.76987447699, 0.76987447699, 0.81729428173, 0.81868898187, 0.69316596932, 0.69316596932, + 0.69316596932, 0.69316596932, 0.68410041841, 0.77266387727, 0.68410041841, + ], + tops: [ + 1, 1, 1, 1, 1.12691771269, 1.01534170153, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.01673640167, 1.02231520223, 1.01673640167, 1.01673640167, 1, 1, 1.01673640167, 1, + 1.01673640167, 1.01673640167, 1, 1, 1, 1, 1, 1.01673640167, 1.01394700139, 1, 1, + 1.01673640167, 1, 1, 1, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1.01673640167, 1, 1.01673640167, + 1, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05718270572, 1, 1.05718270572, + 1, 1.07252440725, 1, 1.05718270572, 1.04393305439, 1.04393305439, 1.05718270572, + 1.05718270572, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.09205020921, 1, 1, 1, 1, 1, + 1.01673640167, 1, 1, 1.09205020921, 1.03974895397, 1, 1.0230125523, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.01534170153, 1.01534170153, 1.01394700139, 1, 1.32078103208, + 1.32078103208, 1.32287308229, 1.25732217573, 1.22873082287, 1.21408647141, 1, 1.01673640167, + 1.32078103208, 1.32008368201, 1.32426778243, 1.22942817294, 1.32078103208, 1.32078103208, + 1.32426778243, 1.22942817294, 1, 1.25732217573, 1.32078103208, 1.32078103208, 1.32357043236, + 1.25662482566, 1.22733612273, 1, 1.03974895397, 1.32078103208, 1.32008368201, 1.32426778243, + 1.23012552301, 1.32078103208, 1, 1.07252440725, 1.07810320781, 1.07810320781, 1.08089260809, + 1.01673640167, 1, 1.09065550907, 1, 1, 1.07810320781, 1.07810320781, 1.08089260809, 1, + 1.07810320781, 1.07810320781, 1.08089260809, 1, 1.06276150628, 1.01673640167, 1.07810320781, + 1.07810320781, 1.08089260809, 1.01673640167, 1, 1, 1, 1.07810320781, 1.07810320781, + 1.08089260809, 1, 1.07810320781, 1.05718270572, 1, + ], + bottoms: [ + 0, -0.01255230126, 0, 0, -0.14574616457, -0.01534170153, -0.0160390516, 0, -0.22733612273, + -0.22733612273, 0, 0, -0.18410041841, 0, -0.01534170153, -0.1659693166, -0.01743375174, 0, 0, + -0.01743375174, 0, -0.01743375174, -0.01743375174, 0, -0.0160390516, -0.01743375174, + -0.01534170153, -0.18410041841, 0, 0, 0, -0.01255230126, -0.13110181311, 0, 0, -0.01673640167, + 0, 0, 0, -0.01673640167, 0, 0, -0.01673640167, 0, 0, 0, 0, -0.01673640167, 0, -0.13458856346, + 0, -0.01673640167, 0, -0.01673640167, 0, 0, 0, 0, 0, -0.22733612273, -0.16736401674, + -0.22733612273, 0, -0.20711297071, 0, -0.01673640167, -0.01673640167, -0.01673640167, + -0.01673640167, -0.01673640167, 0, -0.33612273361, 0, 0, -0.33612273361, 0, 0, 0, 0, + -0.01673640167, -0.32845188285, -0.32845188285, 0, -0.01673640167, -0.01534170153, + -0.01673640167, 0, 0, 0, -0.33612273361, 0, -0.22733612273, -0.33612273361, -0.22733612273, 0, + 0, -0.28312412831, -0.03417015342, 0, 0, 0, -0.33612273361, -0.0460251046, 0, -0.0230125523, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.27615062761, 0, 0, -0.30125523013, 0, 0, 0, 0, 0, 0, + -0.29986052999, 0, 0, 0, 0, 0, 0, 0, -0.30125523013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, 0, + -0.03556485356, -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, 0, 0, + -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, + -0.01673640167, -0.01673640167, -0.01673640167, -0.30125523013, -0.01673640167, + -0.01673640167, -0.01673640167, -0.01673640167, 0, 0, 0, 0, -0.01534170153, 0, -0.01673640167, + -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, 0, -0.05718270572, + -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, -0.33612273361, + -0.32845188285, -0.33612273361, + ], + afterStack: 0.05857740586, + bold: { + advances: [ + 0.3940027894, 0.46722454672, 0.70432357043, 0.84588563459, 0.82147838215, 1.23849372385, + 1.21338912134, 0.41841004184, 0.52719665272, 0.52719665272, 0.64993026499, 1.00976290098, + 0.3870292887, 0.57740585774, 0.3870292887, 0.63319386332, 0.82147838215, 0.82147838215, + 0.82147838215, 0.82147838215, 0.82147838215, 0.82147838215, 0.82147838215, 0.82147838215, + 0.82147838215, 0.82147838215, 0.3870292887, 0.3870292887, 1.00976290098, 1.00976290098, + 1.00976290098, 0.62552301255, 1.36262203626, 1.00418410042, 0.91562064156, 0.89121338912, + 1.0529986053, 0.76011157601, 0.74267782427, 1.01534170153, 1.09414225941, 0.45258019526, + 0.6359832636, 0.92677824268, 0.73012552301, 1.36680613668, 1.12831241283, 1.0829846583, + 0.87726638773, 1.0829846583, 0.93235704324, 0.80055788006, 0.83682008368, 1.03277545328, + 0.95258019526, 1.43514644351, 0.93584379358, 0.86680613668, 0.86680613668, 0.52719665272, + 0.62273361227, 0.52719665272, 1.00976290098, 0.59274755927, 0.44839609484, 0.76847977685, + 0.88563458856, 0.68549511855, 0.88423988842, 0.77266387727, 0.54741980474, 0.88423988842, + 0.85983263598, 0.40585774059, 0.40585774059, 0.79846582985, 0.40585774059, 1.30822873082, + 0.8640167364, 0.87308228731, 0.88563458856, 0.88423988842, 0.56834030683, 0.62831241283, + 0.55578800558, 0.8640167364, 0.77405857741, 1.13877266388, 0.78870292887, 0.76847977685, + 0.68410041841, 0.52719665272, 0.46582984658, 0.52719665272, 1.00976290098, 0.3940027894, + 0.46722454672, 0.82147838215, 0.82147838215, 0.79428172943, 0.82147838215, 0.46582984658, + 0.69316596932, 0.65969316597, 1.24825662483, 0.58577405858, 0.82984658298, 1.00976290098, + 0.57740585774, 1.24825662483, 0.59274755927, 0.54253835425, 1.00976290098, 0.57740585774, + 0.57740585774, 0.43305439331, 0.87517433752, 0.72733612273, 0.3870292887, 0.30753138075, + 0.56276150628, 0.65132496513, 0.82984658298, 1.35983263598, 1.37866108787, 1.39818688982, + 0.62552301255, 1.00418410042, 1.00418410042, 1.00418410042, 1.00418410042, 1.00418410042, + 1.00418410042, 1.33542538354, 0.89121338912, 0.76011157601, 0.76011157601, 0.76011157601, + 0.76011157601, 0.45258019526, 0.45258019526, 0.45258019526, 0.45258019526, 1.0529986053, + 1.12831241283, 1.08228730823, 1.08228730823, 1.08228730823, 1.08228730823, 1.08228730823, + 1.00976290098, 1.0829846583, 1.03277545328, 1.03277545328, 1.03277545328, 1.03277545328, + 0.86680613668, 0.87726638773, 0.89679218968, 0.76847977685, 0.76847977685, 0.76847977685, + 0.76847977685, 0.76847977685, 0.76847977685, 1.18270571827, 0.68549511855, 0.77266387727, + 0.77266387727, 0.77266387727, 0.77266387727, 0.40585774059, 0.40585774059, 0.40585774059, + 0.40585774059, 0.84728033473, 0.8640167364, 0.87238493724, 0.87238493724, 0.87238493724, + 0.87238493724, 0.87238493724, 1.00976290098, 0.87308228731, 0.8640167364, 0.8640167364, + 0.8640167364, 0.8640167364, 0.76847977685, 0.88563458856, 0.76847977685, + ], + lefts: [ + 0, 0.1059972106, 0.13319386332, 0.02580195258, 0.08577405858, 0.06276150628, 0.05230125523, + 0.1220362622, 0.11018131102, 0.01255230126, 0.04881450488, 0.1659693166, 0.02719665272, + 0.09972105997, 0.06415620642, 0, 0.04811715481, 0.14783821478, 0.05788005579, 0.08158995816, + 0.02719665272, 0.0990237099, 0.06973500697, 0.06694560669, 0.05578800558, 0.05439330544, + 0.06415620642, 0.02719665272, 0.17991631799, 0.1659693166, 0.17991631799, 0.04323570432, + 0.09414225941, 0.0069735007, 0.11436541144, 0.05160390516, 0.11436541144, 0.11436541144, + 0.11436541144, 0.05160390516, 0.11436541144, 0.11436541144, 0.0230125523, 0.11436541144, + 0.11436541144, 0.11436541144, 0.11436541144, 0.05160390516, 0.11436541144, 0.05160390516, + 0.11436541144, 0.06415620642, 0.02161785216, 0.10251046025, 0.0069735007, 0.01255230126, + 0.00418410042, 0, 0.02859135286, 0.15132496513, 0, 0.04881450488, 0.14156206416, 0, + 0.03835425384, 0.03974895398, 0.09274755927, 0.05020920502, 0.05020920502, 0.05020920502, + 0.03138075314, 0.05020920502, 0.09274755927, 0.07740585774, 0, 0.09274755927, 0.09274755927, + 0.09274755927, 0.09274755927, 0.05020920502, 0.09274755927, 0.05020920502, 0.09274755927, + 0.0460251046, 0.02859135286, 0.08158995816, 0.00278940028, 0.01115760112, 0.00557880056, 0, + 0.01743375174, 0.07391910739, 0.14574616457, 0.05857740586, 0.1359832636, 0, 0.1059972106, + 0.11854951186, 0.09972105997, 0.03556485356, 0.02859135286, 0.14574616457, 0.09135285914, + 0.059972106, 0.09135285914, 0.05020920502, 0.0369595537, 0.1659693166, 0.09972105997, + 0.19735006973, 0, 0.08019525802, 0.1659693166, 0.08158995816, 0.09135285914, 0.03835425384, + 0.09274755927, 0.06415620642, 0.06415620642, 0.03556485356, 0.08926080893, 0.04881450488, + 0.0369595537, 0.05788005579, 0.05788005579, 0.09135285914, 0.0369595537, 0.0069735007, + 0.0069735007, 0.0069735007, 0.0069735007, 0.0069735007, 0.0069735007, 0, 0.05160390516, + 0.11436541144, 0.11436541144, 0.11436541144, 0.11436541144, 0, 0.07670850767, 0, 0, 0, + 0.11436541144, 0.05160390516, 0.05160390516, 0.05160390516, 0.05160390516, 0.05160390516, + 0.16875871688, 0.05160390516, 0.10251046025, 0.10251046025, 0.10251046025, 0.10251046025, 0, + 0.11436541144, 0.09274755928, 0.03974895398, 0.03974895398, 0.03974895398, 0.03974895398, + 0.03974895398, 0.03974895398, 0.03974895398, 0.05020920502, 0.05020920502, 0.05020920502, + 0.05020920502, 0.05020920502, 0, 0.04951185495, 0, 0, 0.05020920502, 0.09274755928, + 0.05020920502, 0.05020920502, 0.05020920502, 0.05020920502, 0.05020920502, 0.1659693166, + 0.02719665272, 0.08158995816, 0.08158995816, 0.08158995816, 0.08158995816, 0, 0.09274755928, + 0, + ], + rights: [ + 0.3940027894, 0.36122733612, 0.57112970711, 0.82008368201, 0.75523012552, 1.17573221757, + 1.19037656904, 0.28940027894, 0.51534170153, 0.41841004184, 0.60251046025, 0.84518828452, + 0.30125523013, 0.48117154812, 0.32287308229, 0.64993026499, 0.77336122734, 0.58019525802, + 0.72454672245, 0.7189679219, 0.78382147838, 0.72733612273, 0.77405857741, 0.76290097629, + 0.76569037657, 0.7580195258, 0.32287308229, 0.32566248257, 0.83124128312, 0.84518828452, + 0.83124128312, 0.59762900976, 1.27126917713, 0.99372384937, 0.86541143654, 0.83124128312, + 1.00139470014, 0.71408647141, 0.69246861925, 0.93514644351, 0.97977684798, 0.33960948396, + 0.53138075314, 0.94560669456, 0.70990237099, 1.25383542538, 1.01394700139, 1.03138075314, + 0.84518828452, 1.1290097629, 0.95327754533, 0.75034867504, 0.81659693166, 0.92956764296, + 0.9470013947, 1.42259414226, 0.9309623431, 0.86820083682, 0.8340306834, 0.47838214784, + 0.67015341702, 0.37726638773, 0.8709902371, 0.59274755927, 0.41562064156, 0.68688981869, + 0.83542538354, 0.63389121339, 0.79149232915, 0.73430962343, 0.55857740586, 0.79288702929, + 0.77824267782, 0.33124128312, 0.33124128312, 0.80822873082, 0.31311018131, 1.22663877266, + 0.78242677824, 0.82287308229, 0.83542538354, 0.79149232915, 0.55857740586, 0.59414225941, + 0.52440725244, 0.77126917713, 0.77266387727, 1.12691771269, 0.78242677824, 0.77266387727, + 0.65829846583, 0.470013947, 0.32147838215, 0.4539748954, 0.87517433752, 0.3940027894, + 0.36122733612, 0.70013947001, 0.77684797768, 0.7580195258, 0.80683403068, 0.32147838215, + 0.62831241283, 0.59414225941, 1.15829846583, 0.51534170153, 0.79288702929, 0.84518828452, + 0.48117154812, 1.05090655509, 0.59274755927, 0.4769874477, 0.84518828452, 0.50278940028, + 0.49860529986, 0.41562064156, 0.80962343096, 0.65969316597, 0.32287308229, 0.31868898187, + 0.38284518828, 0.59832635983, 0.79288702929, 1.28661087866, 1.28521617852, 1.31938633194, + 0.59135285914, 0.99372384937, 0.99372384937, 0.99372384937, 0.99372384937, 0.99372384937, + 0.99372384937, 1.28940027894, 0.83124128312, 0.71408647141, 0.71408647141, 0.71408647141, + 0.71408647141, 0.3709902371, 0.4539748954, 0.48186889819, 0.49721059972, 1.00139470014, + 1.0139470014, 1.03138075314, 1.03138075314, 1.03138075314, 1.03138075314, 1.03138075314, + 0.84379358438, 1.03138075314, 0.92956764296, 0.92956764296, 0.92956764296, 0.92956764296, + 0.86820083682, 0.84518828452, 0.85564853557, 0.68688981869, 0.68688981869, 0.68688981869, + 0.68688981869, 0.68688981869, 0.68688981869, 1.14365411437, 0.63389121339, 0.73430962343, + 0.73430962343, 0.73430962343, 0.73430962343, 0.35843793584, 0.42677824268, 0.45815899582, + 0.47419804742, 0.79707112971, 0.78242677824, 0.82287308229, 0.82287308229, 0.82287308229, + 0.82287308229, 0.82287308229, 0.84518828452, 0.8410041841, 0.77126917713, 0.77126917713, + 0.77126917713, 0.77126917713, 0.77266387727, 0.83542538354, 0.77266387727, + ], + tops: [ + 1, 1, 1, 1, 1.12970711297, 1.01394700139, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.01673640167, 1.02231520223, 1.01673640167, 1.01673640167, 1, 1, 1.01673640167, 1, + 1.01673640167, 1.01673640167, 1, 1, 1, 1, 1, 1.01673640167, 1.01255230126, 1, 1, + 1.01673640167, 1, 1, 1, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1.01673640167, 1, 1.01673640167, + 1, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05718270572, 1, 1.05718270572, + 1, 1.07391910739, 1, 1.05718270572, 1.05369595537, 1.05369595537, 1.05718270572, + 1.05718270572, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.09274755927, 1, 1, 1, 1, 1, + 1.01673640167, 1, 1, 1.09274755927, 1.03974895397, 1, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.01394700139, 1.01394700139, 1.01394700139, 1, 1.3179916318, + 1.3179916318, 1.31938633194, 1.30962343096, 1.28382147838, 1.23849372385, 1, 1.01673640167, + 1.3179916318, 1.3179916318, 1.31938633194, 1.28382147838, 1.3179916318, 1.3179916318, + 1.31938633194, 1.28382147838, 1, 1.30962343096, 1.3179916318, 1.3179916318, 1.31938633194, + 1.30962343096, 1.28382147838, 1, 1.03835425384, 1.3179916318, 1.3179916318, 1.31938633194, + 1.28382147838, 1.2949790795, 1, 1.07391910739, 1.05230125523, 1.05230125523, 1.05369595537, + 1.04393305439, 1.01813110181, 1.13110181311, 1, 1, 1.05230125523, 1.05230125523, + 1.05369595537, 1.01813110181, 1.05230125523, 1.05230125523, 1.05369595537, 1.01813110181, + 1.08228730823, 1.04393305439, 1.05230125523, 1.05230125523, 1.05369595537, 1.04393305439, + 1.01813110181, 1, 1, 1.05230125523, 1.05230125523, 1.05369595537, 1.01813110181, + 1.05230125523, 1.05718270572, 1.01813110181, + ], + bottoms: [ + 0, -0.0160390516, 0, 0, -0.14574616457, -0.01394700139, -0.0160390516, 0, -0.22733612273, + -0.22733612273, 0, 0, -0.17712691771, 0, -0.01743375174, -0.1659693166, -0.01743375174, 0, + 0, -0.01743375174, 0, -0.01743375174, -0.01743375174, 0, -0.0160390516, -0.01743375174, + -0.01743375174, -0.17712691771, 0, 0, 0, -0.0160390516, -0.13110181311, 0, 0, + -0.01743375174, 0, 0, 0, -0.01743375174, 0, 0, -0.01743375174, 0, 0, 0, 0, -0.01743375174, + 0, -0.13458856346, 0, -0.01743375174, 0, -0.01743375174, 0, 0, 0, 0, 0, -0.22733612273, + -0.1659693166, -0.22733612273, 0, -0.20711297071, 0, -0.01743375174, -0.01743375174, + -0.01743375174, -0.01743375174, -0.01743375174, 0, -0.33542538354, 0, 0, -0.33542538354, 0, + 0, 0, 0, -0.01743375174, -0.32845188285, -0.32845188285, 0, -0.01743375174, -0.01743375174, + -0.01743375174, 0, 0, 0, -0.33542538354, 0, -0.22733612273, -0.33542538354, -0.22733612273, + 0, 0, -0.28451882845, -0.02580195258, 0, 0, 0, -0.33542538354, -0.0460251046, 0, + -0.01743375174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.27545327755, 0, 0, -0.31729428173, 0, 0, + 0, 0, 0, 0, -0.30125523013, 0, 0, 0, 0, 0, 0, 0, -0.31729428173, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, 0, + -0.04253835425, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, 0, 0, + -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, + -0.01743375174, -0.01743375174, -0.01743375174, -0.31729428173, -0.01743375174, + -0.01743375174, -0.01743375174, -0.01743375174, 0, 0, 0, 0, -0.01743375174, 0, + -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, 0, + -0.05439330544, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, + -0.33542538354, -0.32845188285, -0.33542538354, + ], + }, }, Tahoma: { below: 0.28408327737, @@ -1342,6 +3803,262 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, -0.00738750839, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00067159167, 0, -0.0362659503, -0.02552048355, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.15312290128, 0.07656145064, 0.09536601746, 0.07118871726, 0.06850235057, 0.04499664204, + 0.07051712559, 0.0725319006, 0.04969778375, 0.07521826729, 0.10543989255, 0.04969778375, + 0.0604432505, 0.12760241773, 0, 0.0557421088, 0.15177971793, 0.07320349228, 0.06514439221, + 0.02686366689, 0.08327736736, 0.05708529214, 0.06648757555, 0.04969778375, 0.04499664204, + 0.16319677636, 0.08193418402, 0.13498992612, 0.12894560107, 0.14439220954, 0.07320349228, + 0.08865010074, 0, 0.10141034251, 0.04432505037, 0.10141034251, 0.10141034251, 0.10141034251, + 0.04432505037, 0.10141034251, 0.06245802552, 0.00604432505, 0.10141034251, 0.10141034251, + 0.10141034251, 0.10141034251, 0.04432505037, 0.10141034251, 0.04432505037, 0.10141034251, + 0.05171255876, 0, 0.08932169241, 0, 0.01746138348, 0.00537273338, 0, 0.04029550034, + 0.1114842176, 0.03492276696, 0.06581598388, 0.08932169241, 0, 0.16655473472, 0.03895231699, + 0.09133646743, 0.03962390866, 0.03962390866, 0.03962390866, 0.0194761585, 0.03962390866, + 0.09133646743, 0.08529214238, 0, 0.09133646743, 0.09402283412, 0.09133646743, 0.09133646743, + 0.03828072532, 0.09133646743, 0.03962390866, 0.09133646743, 0.04499664204, 0.01410342512, + 0.08596373405, 0.00402955003, 0.02014775017, 0.00671591672, 0.00402955003, 0.03290799194, + 0.04029550034, 0.20685023506, 0.06581598388, 0.08999328408, 0, 0.15312290128, 0.07656145064, + 0.05977165883, 0.0436534587, 0.03760913365, 0.20685023506, 0.079919409, 0.16991269308, + 0.05775688381, 0.07656145064, 0.06917394224, 0.10543989255, 0.0604432505, 0.05775688381, 0, + 0.0678307589, 0.10879785091, 0.12424445937, 0.1235728677, 0.30154466085, 0.09133646743, + 0.03828072532, 0.16319677636, 0.19408999328, 0.16655473472, 0.05708529214, 0.08797850907, + 0.11484217596, 0.11484217596, 0.09402283412, 0.03895231699, 0, 0, 0, 0, 0, 0, 0, + 0.04432505037, 0.10141034251, 0.10141034251, 0.10141034251, 0.10141034251, 0.06245802552, + 0.06245802552, 0.02820685023, 0.05104096709, 0.01611820013, 0.10141034251, 0.04432505037, + 0.04432505037, 0.04432505037, 0.04432505037, 0.04432505037, 0.13969106783, 0.04432505037, + 0.08932169241, 0.08932169241, 0.08932169241, 0.08932169241, 0, 0.10141034251, 0.09133646743, + 0.03895231699, 0.03895231699, 0.03895231699, 0.03895231699, 0.03895231699, 0.03895231699, + 0.03895231699, 0.03962390866, 0.03962390866, 0.03962390866, 0.03962390866, 0.03962390866, 0, + 0.08059100067, 0, 0, 0.03828072532, 0.09133646743, 0.03828072532, 0.03828072532, + 0.03828072532, 0.03828072532, 0.03828072532, 0.10543989255, 0.02753525856, 0.08596373405, + 0.08596373405, 0.08596373405, 0.08596373405, 0.00402955003, 0.09133646743, 0.00402955003, + ], + rights: [ + 0.42981867025, 0.30355943586, 0.47548690396, 0.90530557421, 0.6877098724, 1.27400940228, + 0.97044996642, 0.21961047683, 0.47683008731, 0.45399597045, 0.67629281397, 0.89523169913, + 0.33579583613, 0.43922095366, 0.2881128274, 0.48891873741, 0.69509738079, 0.63935527199, + 0.69039623909, 0.67293485561, 0.7165883143, 0.67897918066, 0.70584284755, 0.70114170584, + 0.70114170584, 0.69375419745, 0.32370718603, 0.3680322364, 0.85627938214, 0.8717259906, + 0.86568166555, 0.6124916051, 1.16789791807, 0.83143049026, 0.7797179315, 0.80322364003, + 0.88985896575, 0.72666218939, 0.6997985225, 0.8522498321, 0.82740094023, 0.45063801209, + 0.47817327065, 0.83008730692, 0.68099395567, 0.95836131632, 0.81665547347, 0.92881128274, + 0.73270651444, 0.9321692411, 0.87575554063, 0.73203492277, 0.8038952317, 0.81262592344, + 0.82605775688, 1.22296843519, 0.79314976494, 0.80120886501, 0.73875083949, 0.46071188717, + 0.5399597045, 0.41504365346, 0.91134989926, 0.76158495635, 0.44996642042, 0.63599731363, + 0.72061786434, 0.61114842176, 0.66890530557, 0.6877098724, 0.48623237072, 0.66890530557, + 0.68099395567, 0.22901276024, 0.29684351914, 0.71323035594, 0.2202820685, 1.06917394224, + 0.68099395568, 0.70852921424, 0.72061786434, 0.66890530557, 0.48891873741, 0.58764271323, + 0.45802552048, 0.6756212223, 0.68099395568, 1.00067159167, 0.67427803895, 0.68099395568, + 0.58428475487, 0.59503022163, 0.31900604433, 0.62055070517, 0.91067830759, 0.42981867025, + 0.30355943586, 0.65480188046, 0.6924110141, 0.70987239758, 0.71121558093, 0.31900604433, + 0.67024848892, 0.58226997985, 1.21961047683, 0.58697112156, 0.70047011417, 0.8885157824, + 0.43922095366, 1.21961047683, 0.76158495635, 0.57958361316, 0.89187374077, 0.58159838818, + 0.56212222968, 0.58495634654, 0.68972464741, 0.65950302216, 0.32370718603, 0.51914036266, + 0.54466084621, 0.62189388852, 0.71927468099, 1.24042981867, 1.30691739422, 1.27803895232, + 0.57824042982, 0.83143049026, 0.83143049026, 0.83143049026, 0.83143049026, 0.83143049026, + 0.83143049026, 1.21020819342, 0.80322364003, 0.72666218939, 0.72666218939, 0.72666218939, + 0.72666218939, 0.45063801209, 0.45063801209, 0.48690396239, 0.46339825386, 0.91739422431, + 0.81665547347, 0.92881128274, 0.92881128274, 0.92881128274, 0.92881128274, 0.92881128274, + 0.86098052384, 0.92881128274, 0.81262592344, 0.81262592344, 0.81262592344, 0.81262592344, + 0.80120886501, 0.73539288113, 0.71725990598, 0.63599731363, 0.63599731363, 0.63599731363, + 0.63599731363, 0.63599731363, 0.63599731363, 1.17461383479, 0.61114842176, 0.6877098724, + 0.6877098724, 0.6877098724, 0.6877098724, 0.28274009402, 0.36400268637, 0.34989926125, + 0.33982538617, 0.70718603089, 0.68099395567, 0.70852921424, 0.70852921424, 0.70852921424, + 0.70852921424, 0.70852921424, 0.89523169913, 0.70920080591, 0.6756212223, 0.6756212223, + 0.6756212223, 0.6756212223, 0.68099395567, 0.72061786434, 0.68099395567, + ], + tops: [ + 1, 1, 1, 1, 1.05842847549, 1.01880456682, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, + 1, 1, 1, 1, 1.04499664204, 1.02014775017, 1.00335795836, 1.02081934184, 1.02081934184, 1, 1, + 1.01880456682, 1, 1.02283411686, 1.02014775017, 1, 1, 1, 1, 1, 1.02014775017, 1.0194761585, 1, + 1, 1.01813297515, 1, 1, 1, 1.01813297515, 1, 1, 1, 1, 1, 1, 1, 1.02081934184, 1, + 1.02081934184, 1, 1.01813297515, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, + 1.04499664204, 1, 1, 1, 1, 1.04499664204, 1, 1.04499664204, 1, 1.05171255876, 1, + 1.04499664204, 1.00671591672, 1.00671591672, 1.04499664204, 1.04499664204, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, 1.04499664204, 1, 1, 1, 1, 1.0194761585, + 1, 1, 1.04499664204, 1.02014775017, 1, 1.02014775017, 1, 1, 1, 1, 1.02014775017, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00268636669, 1.00268636669, 1.01880456682, 1, 1.37609133647, + 1.37609133647, 1.36265950302, 1.319677636, 1.24378777703, 1.33378106111, 1, 1.01813297515, + 1.37609133647, 1.37609133647, 1.37609133647, 1.25721961048, 1.37609133647, 1.37609133647, + 1.37609133647, 1.25721961048, 1, 1.33310946944, 1.37609133647, 1.37609133647, 1.37609133647, + 1.33310946944, 1.25721961048, 1, 1.06178643385, 1.37609133647, 1.37609133647, 1.37609133647, + 1.25721961048, 1.37609133647, 1, 1.05171255876, 1.12558764271, 1.12558764271, 1.12558764271, + 1.09603760913, 1.00671591672, 1.15648085964, 1, 1, 1.12558764271, 1.12558764271, + 1.12558764271, 1.00671591672, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, + 1.05171255876, 1.09603760913, 1.12558764271, 1.12558764271, 1.12558764271, 1.09603760913, + 1.00671591672, 1, 1, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, + 1.12558764271, 1.04499664204, 1.00671591672, + ], + bottoms: [ + 0, 0, 0, 0, -0.24244459369, -0.0194761585, -0.02081934184, 0, -0.27669576897, -0.27669576897, + 0, 0, -0.24848891874, 0, 0, -0.21759570181, -0.02081934184, 0, 0, -0.02081934184, 0, + -0.02081934184, -0.02081934184, 0, -0.02283411686, -0.0194761585, 0, -0.24848891874, 0, 0, 0, + 0, -0.15177971793, 0, 0, -0.01813297515, 0, 0, 0, -0.0194761585, 0, 0, -0.01410342512, 0, 0, + 0, 0, -0.02081934184, 0, -0.26326393553, 0, -0.01813297515, 0, -0.02081934184, 0, 0, 0, 0, 0, + -0.26326393553, -0.21759570181, -0.26326393553, 0, -0.20147750168, 0, -0.02081934184, + -0.02081934184, -0.01678979181, -0.02081934184, -0.01746138348, 0, -0.28408327737, 0, 0, + -0.28408327737, 0, 0, 0, 0, -0.02081934184, -0.27669576897, -0.27669576897, 0, -0.01813297515, + -0.01477501679, -0.02081934184, 0, 0, 0, -0.27669576897, 0, -0.26326393553, -0.26326393553, + -0.26326393553, 0, 0, 0, -0.24244459369, 0, 0, 0, -0.26326393553, -0.25856279382, 0, + -0.14103425118, 0, 0, 0, 0, -0.14103425118, 0, 0, 0, 0, 0, 0, -0.27669576897, -0.24378777703, + 0, -0.28408327737, 0, 0, 0, 0, 0, 0, -0.02014775017, 0, 0, 0, 0, 0, 0, 0, -0.28408327737, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, + -0.02081934184, 0, -0.07790463398, -0.02081934184, -0.02081934184, -0.02081934184, + -0.02081934184, 0, 0, -0.01611820013, -0.02081934184, -0.02081934184, -0.02081934184, + -0.02081934184, -0.02081934184, -0.02081934184, -0.0194761585, -0.28408327737, -0.01746138348, + -0.01746138348, -0.01746138348, -0.01746138348, 0, 0, 0, 0, -0.02081934184, 0, -0.02081934184, + -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, -0.09872397582, + -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.27669576897, + -0.27669576897, -0.27669576897, + ], + afterStack: 0.0557421088, + bold: { + advances: [ + 0.40295500336, 0.47145735393, 0.67293485561, 1.12558764271, 0.87575554063, 1.64875755541, + 1.07454667562, 0.37877770316, 0.6245802552, 0.6245802552, 0.87575554063, 1.12558764271, + 0.42981867025, 0.59301544661, 0.42981867025, 0.79382135662, 0.87575554063, 0.87575554063, + 0.87575554063, 0.87575554063, 0.87575554063, 0.87575554063, 0.87575554063, 0.87575554063, + 0.87575554063, 0.87575554063, 0.49966420416, 0.49966420416, 1.12558764271, 1.12558764271, + 1.12558764271, 0.77904633983, 1.26527871054, 0.94157152451, 0.94358629953, 0.91806581598, + 1.04163868368, 0.84620550705, 0.79919408999, 1.02484889187, 1.05104096709, 0.66487575554, + 0.68838146407, 0.95768972465, 0.78710543989, 1.22834116857, 1.05977165883, 1.05910006716, + 0.90396239087, 1.05910006716, 0.99865681666, 0.87105439893, 0.84217595702, 1.01611820013, + 0.92813969107, 1.41370047011, 0.94157152451, 0.92209536602, 0.85627938214, 0.6245802552, + 0.79382135662, 0.6245802552, 1.12558764271, 0.87575554063, 0.75083948959, 0.82337139019, + 0.86903962391, 0.72531900604, 0.86568166555, 0.81665547347, 0.52585627938, 0.86568166555, + 0.88045668234, 0.41504365346, 0.49899261249, 0.82874412357, 0.41504365346, 1.31161853593, + 0.88045668234, 0.84889187374, 0.86568166555, 0.86568166555, 0.59637340497, 0.70785762257, + 0.5715245131, 0.88045668234, 0.79583613163, 1.22364002686, 0.83143049026, 0.7918065816, + 0.72330423103, 0.85695097381, 0.87575554063, 0.85695097381, 1.12558764271, 0.40295500336, + 0.47145735393, 0.87575554063, 0.87575554063, 0.87575554063, 0.87575554063, 0.87575554063, + 0.87575554063, 0.75083948959, 1.27736736064, 0.69845533915, 0.96709200806, 1.12558764271, + 0.59301544661, 1.27736736064, 0.87575554063, 0.71457353929, 1.12558764271, 0.74143720618, + 0.74143720618, 0.75083948959, 0.89523169913, 0.87575554063, 0.49966420416, 0.75083948959, + 0.74143720618, 0.74143720618, 0.96709200806, 1.55137676293, 1.55137676293, 1.55137676293, + 0.77904633983, 0.94157152451, 0.94157152451, 0.94157152451, 0.94157152451, 0.94157152451, + 0.94157152451, 1.35997313633, 0.91806581598, 0.84620550705, 0.84620550705, 0.84620550705, + 0.84620550705, 0.66487575554, 0.66487575554, 0.66487575554, 0.66487575554, 1.06447280054, + 1.05977165883, 1.05910006716, 1.05910006716, 1.05910006716, 1.05910006716, 1.05910006716, + 1.12558764271, 1.05910006716, 1.01611820013, 1.01611820013, 1.01611820013, 1.01611820013, + 0.92209536602, 0.90664875756, 0.88784419073, 0.82337139019, 0.82337139019, 0.82337139019, + 0.82337139019, 0.82337139019, 0.82337139019, 1.28878441907, 0.72531900604, 0.81665547347, + 0.81665547347, 0.81665547347, 0.81665547347, 0.41504365346, 0.41504365346, 0.41504365346, + 0.41504365346, 0.8522498321, 0.88045668234, 0.84889187374, 0.84889187374, 0.84889187374, + 0.84889187374, 0.84889187374, 1.12558764271, 0.84889187374, 0.88045668234, 0.88045668234, + 0.88045668234, 0.88045668234, 0.7918065816, 0.86568166555, 0.7918065816, + ], + lefts: [ + 0, 0.10208193418, 0.08529214238, 0.08394895903, 0.06447280054, 0.07186030893, 0.05708529214, + 0.079919409, 0.07387508395, 0.05305574211, 0.08596373405, 0.13028878442, 0, 0.07387508395, + 0.09603760913, 0.07924781733, 0.05238415044, 0.13096037609, 0.10141034251, 0.06917394224, + 0.03022162525, 0.08059100067, 0.06581598388, 0.07857622565, 0.04231027535, 0.04566823371, + 0.13096037609, 0.0315648086, 0.12155809268, 0.15043653459, 0.14170584285, 0.07454667562, + 0.07924781733, 0, 0.10342511753, 0.04499664204, 0.10342511753, 0.10342511753, 0.10342511753, + 0.04499664204, 0.10342511753, 0.06312961719, 0.00402955003, 0.10342511753, 0.10342511753, + 0.10342511753, 0.10342511753, 0.04499664204, 0.10342511753, 0.04499664204, 0.10342511753, + 0.04902619208, 0, 0.08932169241, 0, 0.02014775017, 0, 0, 0.0362659503, 0.1114842176, + 0.13028878442, 0.09066487576, 0.1161853593, 0, 0.18132975151, 0.03357958361, 0.08999328408, + 0.03492276696, 0.0362659503, 0.03492276696, 0.01410342512, 0.0362659503, 0.08999328408, + 0.08327736736, 0, 0.08999328408, 0.08999328408, 0.08999328408, 0.08999328408, 0.03492276696, + 0.08999328408, 0.0362659503, 0.08999328408, 0.03962390866, 0.01410342512, 0.08394895903, 0, + 0.01007387508, 0, 0, 0.03223640027, 0.03760913365, 0.34318334453, 0.0920080591, + 0.09066487576, 0, 0.10208193418, 0.10073875084, 0.08059100067, 0.07656145064, 0.01410342512, + 0.34318334453, 0.07118871726, 0.11551376763, 0.05775688381, 0.0483546004, 0.08596373405, + 0.13028878442, 0.07387508395, 0.05775688381, 0, 0.08462055071, 0.13028878442, 0.11887172599, + 0.11484217596, 0.22901276024, 0.08999328408, 0.04432505037, 0.13096037609, 0.19274680994, + 0.15312290128, 0.06648757555, 0.12222968435, 0.10946944258, 0.09603760913, 0.09469442579, + 0.05104096709, 0, 0, 0, 0, 0, 0, 0, 0.04499664204, 0.10342511753, 0.10342511753, + 0.10342511753, 0.10342511753, 0.06312961719, 0.06312961719, 0.05104096709, 0.06312961719, + 0.0120886501, 0.10342511753, 0.04499664204, 0.04499664204, 0.04499664204, 0.04499664204, + 0.04499664204, 0.159838818, 0.04499664204, 0.08932169241, 0.08932169241, 0.08932169241, + 0.08932169241, 0, 0.10342511753, 0.08999328408, 0.03357958361, 0.03357958361, 0.03357958361, + 0.03357958361, 0.03357958361, 0.03357958361, 0.03357958361, 0.03492276696, 0.03492276696, + 0.03492276696, 0.03492276696, 0.03492276696, 0.00067159167, 0.06447280054, 0, 0, + 0.03492276696, 0.08999328408, 0.03492276696, 0.03492276696, 0.03492276696, 0.03492276696, + 0.03492276696, 0.13028878442, 0.03492276696, 0.08394895903, 0.08394895903, 0.08394895903, + 0.08394895903, 0, 0.08999328408, 0, + ], + rights: [ + 0.40295500336, 0.36937541974, 0.58697112156, 1.04163868368, 0.82337139019, 1.57555406313, + 1.11349899261, 0.29885829416, 0.57085292142, 0.55003357958, 0.76091336467, 0.99529885829, + 0.37474815312, 0.51914036266, 0.33378106111, 0.67024848892, 0.82337139019, 0.7918065816, + 0.83613163197, 0.81128274009, 0.8475486904, 0.81329751511, 0.83008730692, 0.81396910678, + 0.83344526528, 0.80993955675, 0.36870382807, 0.40967092008, 0.98388179987, 0.97515110813, + 1.00402955003, 0.72800537273, 1.17595701813, 0.94560107455, 0.90329079919, 0.87374076561, + 0.99664204164, 0.7797179315, 0.77300201478, 0.93888515782, 0.94761584956, 0.60174613835, + 0.59771658831, 0.97985224983, 0.77098723976, 1.12491605104, 0.96037609134, 1.01410342512, + 0.87306917394, 1.01410342512, 1.02820685024, 0.84620550705, 0.84217595702, 0.92679650772, + 0.93888515782, 1.39355271995, 0.94963062458, 0.93485560779, 0.82941571525, 0.53324378778, + 0.72128945601, 0.51242444594, 1.00940228341, 0.88650100739, 0.54264607119, 0.73942243116, + 0.82941571525, 0.70382807253, 0.77568838146, 0.78576225655, 0.57219610477, 0.77568838146, + 0.7965077233, 0.3317662861, 0.40899932841, 0.84486232371, 0.32505036938, 1.2276695769, + 0.7965077233, 0.81396910678, 0.82941571525, 0.77568838146, 0.59637340497, 0.68569509738, + 0.56548018805, 0.79046339825, 0.79583613163, 1.21356615178, 0.83411685695, 0.79382135662, + 0.69173942243, 0.76494291471, 0.53190060443, 0.81934184016, 1.03760913365, 0.40295500336, + 0.36937541974, 0.77635997314, 0.81061114842, 0.7965077233, 0.86165211551, 0.53190060443, + 0.80859637341, 0.63129617193, 1.21961047683, 0.61316319678, 0.84486232371, 0.98858294157, + 0.51914036266, 1.21961047683, 0.88650100739, 0.62995298858, 0.99529885829, 0.65010073875, + 0.63331094694, 0.59032907992, 0.80523841504, 0.78777703156, 0.36870382807, 0.56077904634, + 0.61584956347, 0.68972464741, 0.88112827401, 1.46272666219, 1.48891873741, 1.51645399597, + 0.7044996642, 0.94560107455, 0.94560107455, 0.94560107455, 0.94560107455, 0.94560107455, + 0.94560107455, 1.29281396911, 0.87374076561, 0.7797179315, 0.7797179315, 0.7797179315, + 0.7797179315, 0.60174613835, 0.60174613835, 0.61719274681, 0.60174613835, 1.0194761585, + 0.96037609134, 1.01410342512, 1.01410342512, 1.01410342512, 1.01410342512, 1.01410342512, + 0.9684351914, 1.01410342512, 0.92679650772, 0.92679650772, 0.92679650772, 0.92679650772, + 0.93485560779, 0.87306917394, 0.85157824043, 0.73942243116, 0.73942243116, 0.73942243116, + 0.73942243116, 0.73942243116, 0.73942243116, 1.25856279382, 0.70382807253, 0.78576225655, + 0.78576225655, 0.78576225655, 0.78576225655, 0.36198791135, 0.42578912022, 0.44257891202, + 0.44190732035, 0.81396910678, 0.7965077233, 0.81396910678, 0.81396910678, 0.81396910678, + 0.81396910678, 0.81396910678, 0.99529885829, 0.81396910678, 0.79046339825, 0.79046339825, + 0.79046339825, 0.79046339825, 0.79382135661, 0.82941571524, 0.79382135661, + ], + tops: [ + 1, 1, 1, 1, 1.05842847549, 1.0194761585, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, + 1, 1, 1, 1, 1.04499664204, 1.02014775017, 1.00268636669, 1.0194761585, 1.02081934184, 1, 1, + 1.01880456682, 1, 1.02283411686, 1.02014775017, 1, 1, 1, 1, 1, 1.02014775017, 1.0194761585, + 1, 1, 1.0194761585, 1, 1, 1, 1.0194761585, 1, 1, 1, 1, 1, 1, 1, 1.02081934184, 1, + 1.02081934184, 1, 1.01813297515, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, + 1.04499664204, 1, 1, 1, 1, 1.04499664204, 1, 1.04499664204, 1, 1.05171255876, 1, + 1.04499664204, 1.04499664204, 1.04499664204, 1.04499664204, 1.04499664204, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, 1.04499664204, 1, 1, 1, 1, + 1.0194761585, 1, 1, 1.04499664204, 1.02081934184, 1, 1.02081934184, 1, 1, 1, 1, + 1.02081934184, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00604432505, 1.00604432505, + 1.02014775017, 1, 1.37609133647, 1.37609133647, 1.36937541974, 1.32706514439, 1.2955003358, + 1.29952988583, 1, 1.0194761585, 1.37609133647, 1.37609133647, 1.37609133647, 1.2955003358, + 1.37609133647, 1.37609133647, 1.37609133647, 1.2955003358, 1, 1.33378106111, 1.37609133647, + 1.37609133647, 1.37609133647, 1.33378106111, 1.2955003358, 1, 1.06917394224, 1.37609133647, + 1.37609133647, 1.37609133647, 1.2955003358, 1.36937541974, 1, 1.05171255876, 1.12558764271, + 1.12558764271, 1.12558764271, 1.08327736736, 1.04499664204, 1.14976494291, 1, 1, + 1.12558764271, 1.12558764271, 1.12558764271, 1.04499664204, 1.12558764271, 1.12558764271, + 1.12558764271, 1.04499664204, 1.0557421088, 1.08327736736, 1.12558764271, 1.12558764271, + 1.12558764271, 1.08327736736, 1.04499664204, 1, 1, 1.12558764271, 1.12558764271, + 1.12558764271, 1.04499664204, 1.12558764271, 1.04499664204, 1.04499664204, + ], + bottoms: [ + 0, 0, 0, 0, -0.24244459369, -0.02081934184, -0.02081934184, 0, -0.27669576897, + -0.27669576897, 0, 0, -0.24848891874, 0, 0, -0.21759570181, -0.02081934184, 0, 0, + -0.02081934184, -0.00268636669, -0.02081934184, -0.02081934184, 0, -0.02283411686, + -0.0194761585, 0, -0.24848891874, 0, 0, 0, 0, -0.15379449295, 0, 0, -0.0194761585, 0, 0, 0, + -0.02081934184, 0, 0, -0.01544660846, 0, 0, 0, 0, -0.02081934184, 0, -0.28408327737, 0, + -0.01813297515, 0, -0.02081934184, 0, 0, 0, 0, 0, -0.26326393553, -0.21759570181, + -0.26326393553, 0, -0.23169912693, 0, -0.02014775017, -0.01477501679, -0.02014775017, + -0.02081934184, -0.02014775017, 0, -0.28408327737, 0, 0, -0.28408327737, 0, 0, 0, 0, + -0.02350570853, -0.27669576897, -0.27669576897, 0, -0.02081934184, -0.01477501679, + -0.02081934184, 0, 0, 0, -0.27669576897, 0, -0.26326393553, -0.26326393553, -0.26326393553, + 0, 0, 0, -0.24244459369, 0, 0, 0, -0.26326393553, -0.26326393553, 0, -0.14103425118, 0, 0, + 0, 0, -0.14103425118, 0, 0, 0, 0, 0, 0, -0.27669576897, -0.24378777703, 0, -0.28408327737, + 0, 0, 0, 0, 0, 0, -0.02014775017, 0, 0, 0, 0, 0, 0, 0, -0.28408327737, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, + -0.08462055071, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, 0, + -0.00940228341, -0.02014775017, -0.02014775017, -0.02014775017, -0.02014775017, + -0.02014775017, -0.02014775017, -0.02014775017, -0.28408327737, -0.02014775017, + -0.02014775017, -0.02014775017, -0.02014775017, 0, 0, 0, 0, -0.02350570853, 0, + -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, 0, + -0.10879785091, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, + -0.27669576897, -0.27669576897, -0.27669576897, + ], + }, }, "Times New Roman": { below: 0.31939437635, @@ -1399,6 +4116,261 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00504686373, 0, ], + lefts: [ + 0, 0.16438356164, 0.09589041096, 0.02667627974, 0.07786589762, 0.05191059841, 0.05407354001, + 0.05839942322, 0.06056236482, 0.03316510454, 0.10454217736, 0.02667627974, 0.07930785869, + 0.05984138428, 0.10454217736, 0.0021629416, 0.05335255948, 0.17303532805, 0.03172314348, + 0.05984138428, 0.02307137707, 0.07065609229, 0.06344628695, 0.05479452055, 0.08940158616, + 0.05839942322, 0.1268925739, 0.10237923576, 0.02667627974, 0.02667627974, 0.02667627974, + 0.06633020908, 0.06993511175, 0.01153568854, 0.02451333814, 0.05335255948, 0.02523431867, + 0.03028118241, 0.02379235761, 0.05191059841, 0.02523431867, 0.03677000721, 0.03028118241, + 0.02451333814, 0.02956020187, 0.02451333814, 0, 0.05191059841, 0.02451333814, 0.05191059841, + 0.02523431867, 0.09228550829, 0.04470079308, 0.00793078587, 0.0129776496, 0.01946647441, + 0.010814708, 0.01369863014, 0.01874549387, 0.12112472963, 0.0021629416, 0.05407354001, + 0.02667627974, 0, 0.08507570296, 0.05263157895, 0, 0.05046863735, 0.04902667628, + 0.05479452055, 0.05695746215, 0.04397981255, 0.00937274694, 0.04325883201, 0, 0.01225666907, + 0.04397981255, 0.01225666907, 0.0086517664, 0.04974765681, 0, 0.04902667628, 0.00937274694, + 0.07209805335, 0.01441961067, 0.00144196107, 0.01225666907, 0.00937274694, 0.01946647441, + 0.0086517664, 0.02956020187, 0.20403749099, 0.1160778659, 0.12761355443, 0.01441961067, 0, + 0.16438356164, 0.09300648882, 0.04397981255, 0.01946647441, 0.00144196107, 0.1160778659, + 0.11247296323, 0.04109589041, 0.04974765681, 0, 0.04614275415, 0.02595529921, 0.05984138428, + 0.04974765681, 0, 0.07065609229, 0.00576784427, 0.01441961067, 0.03172314348, 0.17015140591, + 0.09661139149, 0, 0.17015140591, 0.13482335977, 0.09805335256, 0.02090843547, 0.04614275415, + 0.09661139149, 0.09661139149, 0.03028118241, 0.06416726748, 0.01153568854, 0.01153568854, + 0.01153568854, 0.01153568854, 0.01153568854, 0.01153568854, 0, 0.05335255948, 0.03028118241, + 0.03028118241, 0.03028118241, 0.03028118241, 0.03677000721, 0.03677000721, 0.03677000721, + 0.03677000721, 0.02523431867, 0, 0.05191059841, 0.05191059841, 0.05191059841, 0.05191059841, + 0.05191059841, 0.11896178803, 0.05263157895, 0.00793078587, 0.00793078587, 0.00793078587, + 0.00793078587, 0.01369863014, 0.02595529921, 0.02523431867, 0.05263157895, 0.05263157895, + 0.05263157895, 0.05263157895, 0.05263157895, 0.05263157895, 0.05263157895, 0.05046863735, + 0.05479452055, 0.05479452055, 0.05479452055, 0.05479452055, 0.04325883201, 0.04325883201, + 0.00937274694, 0.00144196107, 0.04902667628, 0.0086517664, 0.04974765681, 0.04974765681, + 0.04974765681, 0.04974765681, 0.04974765681, 0.01658255227, 0.02811824081, 0.00144196107, + 0.00144196107, 0.00144196107, 0.00144196107, 0.0086517664, 0, 0.0086517664, + ], + rights: [ + 0.36914203317, 0.32732516222, 0.50468637347, 0.71160778659, 0.66402307138, 1.17880317231, + 1.10382119683, 0.20331651045, 0.45854361932, 0.43114635905, 0.6344628695, 0.80389329488, + 0.29416005768, 0.43258832012, 0.2645998558, 0.41384282624, 0.68565248738, 0.55803893295, + 0.67700072098, 0.61571737563, 0.68709444845, 0.6409516943, 0.68132660418, 0.67267483778, + 0.65320836337, 0.67483777938, 0.28839221341, 0.31723143475, 0.80245133381, 0.80461427541, + 0.80245133381, 0.59625090123, 1.32372025955, 1.04974765681, 0.90410958904, 0.93366979092, + 1.01009372747, 0.86806056236, 0.76063446287, 1.04542177361, 1.03604902668, 0.45565969719, + 0.56596971882, 1.07858687815, 0.87022350397, 1.28190338861, 1.04542177361, 1.00937274694, + 0.76928622927, 1.01009372747, 0.9978370584, 0.741888969, 0.86517664023, 1.05046863735, + 1.04830569575, 1.38211968277, 1.04902667628, 1.04470079308, 0.86085075703, 0.43835616438, + 0.41312184571, 0.37130497477, 0.66546503244, 0.75126171593, 0.32227829849, 0.65248738284, + 0.68709444845, 0.60706560923, 0.741888969, 0.61355443403, 0.64167267484, 0.71160778659, + 0.72891131939, 0.3741888969, 0.28767123288, 0.74693583273, 0.37995674117, 1.1420331651, + 0.73179524153, 0.68709444845, 0.68781542898, 0.73828406633, 0.5010814708, 0.52271088681, + 0.41240086518, 0.73612112473, 0.72458543619, 1.05263157895, 0.72025955299, 0.72963229993, + 0.63157894737, 0.60634462869, 0.17591925018, 0.52992069214, 0.78370583994, 0.36914203317, + 0.32732516222, 0.64888248017, 0.70439798125, 0.71737563086, 0.7375630858, 0.17591925018, + 0.6258111031, 0.45133381399, 1.07281903389, 0.40519105984, 0.69214131218, 0.80461427541, + 0.43258832012, 1.07281903389, 0.75126171593, 0.5140591204, 0.78370583994, 0.41456380678, + 0.37707281903, 0.40735400144, 0.78875270368, 0.67123287671, 0.32155731795, 0.35760634463, + 0.34390771449, 0.44051910598, 0.69214131218, 1.08219178082, 1.07714491709, 1.08219178082, + 0.59408795962, 1.04974765681, 1.04974765681, 1.04974765681, 1.04974765681, 1.04974765681, + 1.04974765681, 1.27180966114, 0.93366979092, 0.86806056236, 0.86806056236, 0.86806056236, + 0.86806056236, 0.45565969719, 0.45565969719, 0.45565969719, 0.45565969719, 1.00937274694, + 1.04542177361, 1.00937274694, 1.00937274694, 1.00937274694, 1.00937274694, 1.00937274694, + 0.71088680606, 1.01009372747, 1.05046863735, 1.05046863735, 1.05046863735, 1.05046863735, + 1.04470079308, 0.76423936554, 0.69069935112, 0.65248738284, 0.65248738284, 0.65248738284, + 0.65248738284, 0.65248738284, 0.65248738284, 0.94015861572, 0.60706560923, 0.61355443403, + 0.61355443403, 0.61355443403, 0.61355443403, 0.3741888969, 0.3741888969, 0.41528478731, + 0.41167988464, 0.68421052632, 0.73179524153, 0.68709444845, 0.68709444845, 0.68709444845, + 0.68709444845, 0.68709444845, 0.79379956741, 0.71016582552, 0.73612112473, 0.73612112473, + 0.73612112473, 0.73612112473, 0.72963229993, 0.68781542898, 0.72963229993, + ], + tops: [ + 1, 1, 1, 1, 1.05984138428, 1, 1, 1, 1.02523431867, 1.02523431867, 1, 1, 1, 1, 1, + 1.02523431867, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.02523431867, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.02523431867, 1, 1, 1, 1, + 1, 1.02523431867, 1, 1.02523431867, 1, 1.02379235761, 1, 1.02523431867, 1.02523431867, + 1.02595529921, 1.02523431867, 1.02523431867, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.02523431867, 1.02523431867, 1.02523431867, 1, 1, 1, 1, 1, 1, 1, 1.02523431867, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.29560201875, 1.29560201875, + 1.29271809661, 1.2429704398, 1.23143475126, 1.22638788753, 1, 1, 1.29560201875, 1.29560201875, + 1.29271809661, 1.23143475126, 1.29560201875, 1.29560201875, 1.29271809661, 1.23143475126, 1, + 1.2429704398, 1.29560201875, 1.29560201875, 1.29271809661, 1.2429704398, 1.23143475126, 1, + 1.00937274694, 1.29560201875, 1.29560201875, 1.29271809661, 1.23143475126, 1.29560201875, 1, + 1.02523431867, 1.0021629416, 1.0021629416, 1, 1, 1, 1.02811824081, 1, 1, 1.0021629416, + 1.0021629416, 1, 1, 1.0021629416, 1.0021629416, 1, 1, 1.02523431867, 1, 1.0021629416, + 1.0021629416, 1, 1, 1, 1, 1, 1.0021629416, 1.0021629416, 1, 1, 1.0021629416, 1.02523431867, 1, + ], + bottoms: [ + 0, -0.02018745494, 0, -0.02018745494, -0.11247296323, -0.04037490988, -0.02235039654, 0, + -0.31578947368, -0.31578947368, 0, 0, -0.24585436193, 0, -0.02018745494, -0.02018745494, + -0.0173035328, 0, 0, -0.0173035328, 0, -0.0173035328, -0.0173035328, -0.02018745494, + -0.0173035328, -0.02018745494, -0.02018745494, -0.24585436193, 0, 0, 0, -0.01946647441, + -0.31867339582, 0, 0, -0.02235039654, 0, 0, 0, -0.02235039654, 0, 0, -0.02235039654, 0, 0, 0, + -0.01586157174, -0.02235039654, 0, -0.28911319394, 0, -0.02235039654, 0, -0.02307137707, + -0.02235039654, -0.02235039654, 0, 0, 0, -0.29271809661, -0.02018745494, -0.29343907714, 0, + -0.31867339582, 0, -0.01369863014, -0.02018745494, -0.02018745494, -0.02018745494, + -0.02018745494, 0, -0.31867339582, 0, 0, -0.31867339582, 0, 0, 0, 0, -0.02018745494, + -0.31578947368, -0.31578947368, 0, -0.02018745494, -0.010814708, -0.02018745494, + -0.02018745494, -0.02018745494, 0, -0.31867339582, 0, -0.31867339582, -0.31867339582, + -0.31867339582, 0, 0, -0.31867339582, -0.27325162221, -0.0173035328, 0, 0, -0.31867339582, + -0.28839221341, 0, -0.02235039654, 0, -0.00576784427, 0, 0, -0.02235039654, 0, 0, 0, 0, 0, 0, + -0.31867339582, -0.31867339582, 0, -0.28118240807, 0, 0, -0.00576784427, -0.03893294881, + -0.03893294881, -0.03893294881, -0.31867339582, 0, 0, 0, 0, 0, 0, 0, -0.28118240807, 0, 0, 0, + 0, 0, 0, 0, 0, 0, -0.01586157174, -0.02235039654, -0.02235039654, -0.02235039654, + -0.02235039654, -0.02235039654, 0, -0.03388608508, -0.02307137707, -0.02307137707, + -0.02307137707, -0.02307137707, 0, 0, -0.00937274694, -0.01369863014, -0.01369863014, + -0.01369863014, -0.01369863014, -0.01369863014, -0.01369863014, -0.02018745494, + -0.28118240807, -0.02018745494, -0.02018745494, -0.02018745494, -0.02018745494, 0, 0, 0, 0, + -0.02018745494, 0, -0.02018745494, -0.02018745494, -0.02018745494, -0.02018745494, + -0.02018745494, 0, -0.04830569575, -0.02018745494, -0.02018745494, -0.02018745494, + -0.02018745494, -0.31867339582, -0.31506849315, -0.31867339582, + ], + afterStack: 0.05263157895, + bold: { + advances: [ + 0.36994219653, 0.49277456647, 0.82153179191, 0.73988439306, 0.73988439306, 1.47976878613, + 1.23265895954, 0.41112716763, 0.49277456647, 0.49277456647, 0.73988439306, 0.84320809249, + 0.36994219653, 0.49277456647, 0.36994219653, 0.41112716763, 0.73988439306, 0.73988439306, + 0.73988439306, 0.73988439306, 0.73988439306, 0.73988439306, 0.73988439306, 0.73988439306, + 0.73988439306, 0.73988439306, 0.49277456647, 0.49277456647, 0.84320809249, 0.84320809249, + 0.84320809249, 0.73988439306, 1.37644508671, 1.0686416185, 0.98699421965, 1.0686416185, + 1.0686416185, 0.98699421965, 0.9039017341, 1.15101156069, 1.15101156069, 0.57586705202, + 0.73988439306, 1.15101156069, 0.98699421965, 1.39667630058, 1.0686416185, 1.15101156069, + 0.9039017341, 1.15101156069, 1.0686416185, 0.82297687861, 0.98699421965, 1.0686416185, + 1.0686416185, 1.47976878613, 1.0686416185, 1.0686416185, 0.98699421965, 0.49277456647, + 0.41112716763, 0.49277456647, 0.8598265896, 0.73988439306, 0.49277456647, 0.73988439306, + 0.82297687861, 0.65679190751, 0.82297687861, 0.65679190751, 0.49277456647, 0.73988439306, + 0.82297687861, 0.41112716763, 0.49277456647, 0.82297687861, 0.41112716763, 1.23265895954, + 0.82297687861, 0.73988439306, 0.82297687861, 0.82297687861, 0.65679190751, 0.57586705202, + 0.49277456647, 0.82297687861, 0.73988439306, 1.0686416185, 0.73988439306, 0.73988439306, + 0.65679190751, 0.58309248555, 0.32586705202, 0.58309248555, 0.76950867052, 0.36994219653, + 0.49277456647, 0.73988439306, 0.73988439306, 0.73988439306, 0.73988439306, 0.32586705202, + 0.73988439306, 0.49277456647, 1.10549132948, 0.4436416185, 0.73988439306, 0.84320809249, + 0.49277456647, 1.10549132948, 0.73988439306, 0.59176300578, 0.81213872832, 0.4436416185, + 0.4436416185, 0.49277456647, 0.85260115607, 0.79913294798, 0.49349710983, 0.49277456647, + 0.4436416185, 0.48843930636, 0.73988439306, 1.1098265896, 1.1098265896, 1.1098265896, + 0.73988439306, 1.0686416185, 1.0686416185, 1.0686416185, 1.0686416185, 1.0686416185, + 1.0686416185, 1.47976878613, 1.0686416185, 0.98699421965, 0.98699421965, 0.98699421965, + 0.98699421965, 0.57586705202, 0.57586705202, 0.57586705202, 0.57586705202, 1.0686416185, + 1.0686416185, 1.15101156069, 1.15101156069, 1.15101156069, 1.15101156069, 1.15101156069, + 0.84320809249, 1.15101156069, 1.0686416185, 1.0686416185, 1.0686416185, 1.0686416185, + 1.0686416185, 0.9039017341, 0.82297687861, 0.73988439306, 0.73988439306, 0.73988439306, + 0.73988439306, 0.73988439306, 0.73988439306, 1.0686416185, 0.65679190751, 0.65679190752, + 0.65679190752, 0.65679190752, 0.65679190752, 0.41112716763, 0.41112716763, 0.41112716763, + 0.41112716763, 0.73988439306, 0.82297687861, 0.73988439306, 0.73988439306, 0.73988439306, + 0.73988439306, 0.73988439306, 0.81213872832, 0.73988439306, 0.82297687861, 0.82297687861, + 0.82297687861, 0.82297687861, 0.73988439306, 0.82297687861, 0.73988439306, + ], + lefts: [ + 0, 0.12644508671, 0.12716763006, 0.0289017341, 0.05708092486, 0.10260115607, 0.05924855491, + 0.10115606936, 0.05924855491, 0.01806358382, 0.0823699422, 0.0289017341, 0.04768786127, + 0.03612716763, 0.06502890173, 0.00144508671, 0.05346820809, 0.0975433526, 0.03612716763, + 0.02384393064, 0.03684971098, 0.04985549133, 0.0549132948, 0.04985549133, 0.05202312139, + 0.04552023121, 0.12644508671, 0.1098265896, 0.02962427746, 0.0289017341, 0.02962427746, + 0.09031791908, 0.06647398844, 0.01156069364, 0.03106936416, 0.05852601156, 0.01950867052, + 0.02962427746, 0.03323699422, 0.05997109827, 0.03106936416, 0.02962427746, 0.01589595376, + 0.03323699422, 0.0274566474, 0.02962427746, 0.02095375723, 0.05780346821, 0.03757225434, + 0.05780346821, 0.0274566474, 0.07658959538, 0.05346820809, 0.03468208092, 0.01156069364, + 0.01300578035, 0.01011560694, 0.01300578035, 0.02384393064, 0.15462427746, 0.00144508671, + 0.04841040462, 0.10621387283, 0, 0.0274566474, 0.06647398844, 0.03106936416, 0.0563583815, + 0.05708092486, 0.05708092486, 0.04768786127, 0.05563583815, 0.05057803468, 0.03034682081, 0, + 0.04913294798, 0.03106936416, 0.0549132948, 0.05057803468, 0.05346820809, 0.02817919075, + 0.0563583815, 0.05419075145, 0.05852601156, 0.0274566474, 0.04552023121, 0.0137283237, + 0.01228323699, 0.03395953757, 0.01228323699, 0.0151734104, 0.11921965318, 0.11488439306, + 0.06575144509, 0.00867052023, 0, 0.12644508671, 0.09248554913, 0.02528901734, 0.0151734104, + 0, 0.11488439306, 0.06647398844, 0.01589595376, 0.0426300578, 0.03323699422, 0.02601156069, + 0.02962427746, 0.03612716763, 0.0426300578, 0, 0.0426300578, 0.01083815029, 0.01734104046, + 0.01083815029, 0.16473988439, 0.05708092486, 0.00072254335, 0.15101156069, 0.10476878613, + 0.05346820809, 0.04046242775, 0.0274566474, 0.05202312139, 0.05202312139, 0.00939306358, + 0.08309248555, 0.01156069364, 0.01156069364, 0.01156069364, 0.01156069364, 0.01156069364, + 0.01156069364, 0, 0.05852601156, 0.02962427746, 0.02962427746, 0.02962427746, 0.02962427746, + 0.02962427746, 0.02962427746, 0.02962427746, 0.02962427746, 0.02528901734, 0.02095375723, + 0.05780346821, 0.05780346821, 0.05780346821, 0.05780346821, 0.05780346821, 0.1112716763, + 0.05852601156, 0.03468208092, 0.03468208092, 0.03468208092, 0.03468208092, 0.01300578035, + 0.02962427746, 0.04190751445, 0.06647398844, 0.06647398844, 0.06647398844, 0.06647398844, + 0.06647398844, 0.06647398844, 0.06502890173, 0.0563583815, 0.05708092486, 0.05708092486, + 0.05708092486, 0.05708092486, 0, 0.03034682081, 0, 0, 0.05346820809, 0.05057803468, + 0.05346820809, 0.05346820809, 0.05346820809, 0.05346820809, 0.05346820809, 0.01156069364, + 0.04913294798, 0.04552023121, 0.04552023121, 0.04552023121, 0.04552023121, 0.01228323699, + 0.02817919075, 0.01228323699, + ], + rights: [ + 0.36994219653, 0.36705202312, 0.68930635838, 0.71026011561, 0.69291907514, 1.37716763006, + 1.16835260116, 0.31430635838, 0.47543352601, 0.43424855491, 0.65751445087, 0.8186416185, + 0.32153179191, 0.4573699422, 0.30563583815, 0.41546242775, 0.68569364162, 0.62644508671, + 0.6676300578, 0.65462427746, 0.6799132948, 0.68424855491, 0.6950867052, 0.70447976879, + 0.68786127168, 0.68713872832, 0.36705202312, 0.38367052023, 0.8186416185, 0.81936416185, + 0.8186416185, 0.65679190751, 1.34393063584, 1.05202312139, 0.93497109827, 0.98771676301, + 1.00650289017, 0.92052023121, 0.8598265896, 1.13583815029, 1.12427745665, 0.54190751445, + 0.73121387283, 1.1676300578, 0.93424855491, 1.36994219653, 1.03395953757, 1.09826589595, + 0.85910404624, 1.09898843931, 1.08164739884, 0.7637283237, 0.93352601156, 1.04335260116, + 1.05346820809, 1.46676300578, 1.05852601156, 1.05202312139, 0.96098265896, 0.4450867052, + 0.41546242775, 0.33887283237, 0.75433526012, 0.75361271676, 0.32875722543, 0.71531791908, + 0.75939306358, 0.62355491329, 0.78973988439, 0.62210982659, 0.60260115607, 0.71315028902, + 0.78034682081, 0.39523121387, 0.36777456647, 0.83670520231, 0.39595375723, 1.19436416185, + 0.77962427746, 0.68713872832, 0.75867052023, 0.79335260116, 0.63439306358, 0.52312138728, + 0.47832369942, 0.77528901734, 0.72687861272, 1.05346820809, 0.71604046243, 0.72615606936, + 0.63294797688, 0.52023121387, 0.2088150289, 0.46676300578, 0.79552023121, 0.36994219653, + 0.36705202312, 0.65895953757, 0.70953757225, 0.72687861272, 0.73843930636, 0.2088150289, + 0.67341040462, 0.47832369942, 1.06791907514, 0.45520231214, 0.71315028902, 0.8200867052, + 0.4573699422, 1.06791907514, 0.75361271676, 0.5426300578, 0.80130057803, 0.40823699422, + 0.40028901734, 0.46604046243, 0.82731213873, 0.80130057803, 0.34176300578, 0.35043352601, + 0.38439306358, 0.45231213873, 0.71459537572, 1.08020231214, 1.07297687861, 1.08020231214, + 0.64956647399, 1.05202312139, 1.05202312139, 1.05202312139, 1.05202312139, 1.05202312139, + 1.05202312139, 1.41329479769, 0.98771676301, 0.92052023121, 0.92052023121, 0.92052023121, + 0.92052023121, 0.54190751445, 0.54190751445, 0.54190751445, 0.54190751445, 1.01228323699, + 1.03395953757, 1.09826589595, 1.09826589595, 1.09826589595, 1.09826589595, 1.09826589595, + 0.73699421965, 1.0975433526, 1.04335260116, 1.04335260116, 1.04335260116, 1.04335260116, + 1.05202312139, 0.85332369942, 0.74927745665, 0.71531791908, 0.71531791908, 0.71531791908, + 0.71531791908, 0.71531791908, 0.71531791908, 1.02601156069, 0.6235549133, 0.62210982659, + 0.62210982659, 0.62210982659, 0.62210982659, 0.39523121387, 0.42774566474, 0.43858381503, + 0.44075144509, 0.68713872832, 0.77962427746, 0.68713872832, 0.68713872832, 0.68713872832, + 0.68713872832, 0.68713872832, 0.80130057803, 0.69147398844, 0.77528901734, 0.77528901734, + 0.77528901734, 0.77528901734, 0.72615606936, 0.75867052023, 0.72615606936, + ], + tops: [ + 1, 1.00216763006, 1, 1, 1.00650289017, 1.00216763006, 1.00216763006, 1, 1.00216763006, + 1.00216763006, 1, 1, 1, 1, 1, 1.00216763006, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.00216763006, 1.00216763006, 1, 1, 1.00216763006, 1, 1, 1, 1.00289017341, 1, 1, 1, 1, 1, 1, + 1, 1.00216763006, 1, 1.00216763006, 1, 1.00216763006, 1, 1, 1, 1, 1, 1, 1, 1, 1.00216763006, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00216763006, 1, 1, 1.00289017341, 1.00216763006, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00216763006, 1.00216763006, 1.00361271676, 1, 1, 1, 1, + 1.00578034682, 1, 1, 1.00216763006, 1.00216763006, 1, 1.00216763006, 1, 1, 1, 1, + 1.00216763006, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.31430635838, + 1.31430635838, 1.31430635838, 1.26734104046, 1.26878612717, 1.24421965318, 1, 1.00216763006, + 1.31430635838, 1.31430635838, 1.31430635838, 1.26878612717, 1.31430635838, 1.31430635838, + 1.31430635838, 1.26878612717, 1, 1.26878612717, 1.31430635838, 1.31430635838, 1.31430635838, + 1.26878612717, 1.26878612717, 1, 1.02601156069, 1.31430635838, 1.31430635838, 1.31430635838, + 1.26878612717, 1.31430635838, 1, 1.00216763006, 1.01300578035, 1.01300578035, 1.03106936416, + 1, 1, 1.03829479769, 1, 1, 1.01300578035, 1.01300578035, 1.03106936416, 1, 1.01300578035, + 1.01300578035, 1.03106936416, 1, 1.00216763006, 1, 1.01300578035, 1.01300578035, + 1.03106936416, 1, 1, 1, 1, 1.01300578035, 1.01300578035, 1.03106936416, 1, 1.01300578035, + 1.00216763006, 1, + ], + bottoms: [ + 0, -0.01950867052, 0, -0.02023121387, -0.09971098266, -0.0411849711, -0.02239884393, 0, + -0.29624277457, -0.29624277457, 0, 0, -0.25939306358, 0, -0.01806358382, -0.02239884393, + -0.02023121387, 0, 0, -0.02095375723, 0, -0.02023121387, -0.02023121387, -0.02023121387, + -0.02023121387, -0.02023121387, -0.01806358382, -0.25939306358, 0, 0, 0, -0.01950867052, + -0.31936416185, 0, 0, -0.02239884393, 0, 0, 0, -0.02312138728, 0, 0, -0.02239884393, 0, 0, + 0, -0.02239884393, -0.02239884393, 0, -0.26734104046, 0, -0.02312138728, 0, -0.02312138728, + -0.02239884393, -0.02239884393, 0, 0, 0, -0.27023121387, -0.02239884393, -0.27023121387, 0, + -0.31936416185, 0, -0.00939306358, -0.02023121387, -0.02023121387, -0.02023121387, + -0.02023121387, 0, -0.31936416185, 0, 0, -0.31936416185, 0, 0, 0, 0, -0.02023121387, + -0.31647398844, -0.31647398844, 0, -0.02023121387, -0.00939306358, -0.02023121387, + -0.02023121387, -0.02023121387, 0, -0.31936416185, 0, -0.29985549133, -0.31936416185, + -0.29913294798, 0, 0, -0.31936416185, -0.27239884393, -0.02023121387, 0, 0, -0.31936416185, + -0.31936416185, 0, -0.02239884393, 0, 0, 0, 0, -0.02239884393, 0, 0, 0, 0, 0, 0, + -0.3186416185, -0.31936416185, 0, -0.2789017341, 0, 0, 0, -0.0426300578, -0.0426300578, + -0.0426300578, -0.31936416185, 0, 0, 0, 0, 0, 0, 0, -0.2789017341, 0, 0, 0, 0, 0, 0, 0, 0, + 0, -0.02239884393, -0.02239884393, -0.02239884393, -0.02239884393, -0.02239884393, + -0.02239884393, 0, -0.05563583815, -0.02312138728, -0.02312138728, -0.02312138728, + -0.02312138728, 0, 0, -0.00722543353, -0.00939306358, -0.00939306358, -0.00939306358, + -0.00939306358, -0.00939306358, -0.00939306358, -0.02023121387, -0.2789017341, + -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, 0, 0, 0, 0, -0.02023121387, + 0, -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, 0, + -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, + -0.31936416185, -0.31936416185, -0.31936416185, + ], + }, }, "Trebuchet MS": { below: 0.3063973064, @@ -1456,6 +4428,268 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.04713804714, -0.0404040404, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.15757575758, 0.04848484848, 0.02491582492, 0.09158249158, 0.04107744108, 0.09562289562, + 0.04848484848, 0.12996632997, 0.12996632997, 0.03232323232, 0.08215488215, 0.1164983165, + 0.10707070707, 0.13737373737, 0.12727272727, 0.0430976431, 0.13468013468, 0.03973063973, + 0.0734006734, 0.01683501683, 0.08754208754, 0.05656565657, 0.05656565657, 0.05993265993, + 0.04983164983, 0.13737373737, 0.1164983165, 0.10101010101, 0.08215488215, 0.10101010101, + 0.02693602694, 0.06734006734, 0.00269360269, 0.10101010101, 0.05387205387, 0.10101010101, + 0.10101010101, 0.10101010101, 0.05387205387, 0.10101010101, 0.12457912458, 0.032996633, + 0.10101010101, 0.10101010101, 0.01346801347, 0.10101010101, 0.05387205387, 0.10101010101, + 0.05387205387, 0.10774410774, 0.05387205387, 0.01212121212, 0.10101010101, 0.00875420875, + 0.00875420875, 0.00875420875, 0.00875420875, 0.06734006734, 0.13602693603, 0, 0.05858585859, + 0.10033670034, 0, 0.22424242424, 0.05387205387, 0.09090909091, 0.04377104377, 0.05050505051, + 0.04377104377, 0.04377104377, 0.05387205387, 0.09090909091, 0.05387205387, 0.01212121212, + 0.09090909091, 0.10101010101, 0.09090909091, 0.09090909091, 0.04377104377, 0.09090909091, + 0.05050505051, 0.10101010101, 0.04377104377, 0.0531986532, 0.08417508418, 0.00808080808, + 0.0101010101, 0.00808080808, 0.00808080808, 0.02693602694, 0.02558922559, 0.31111111111, + 0.02558922559, 0.1063973064, 0, 0.15757575758, 0.12996632997, 0.08888888889, 0.03771043771, + 0.02626262626, 0.31784511785, 0.05723905724, 0.12727272727, 0.07070707071, 0.05858585859, + 0.08686868687, 0.08215488215, 0.10707070707, 0.07070707071, 0, 0.19932659933, 0.08215488216, + 0.10909090909, 0.12457912458, 0.25454545455, 0.09090909091, 0.07946127946, 0.13804713805, + 0.2228956229, 0.16902356902, 0.04444444444, 0.1138047138, 0.05454545455, 0.06801346801, + 0.08417508418, 0.02693602694, 0.00269360269, 0.00269360269, 0.00269360269, 0.00269360269, + 0.00269360269, 0.00269360269, 0.01144781145, 0.05387205387, 0.10101010101, 0.10101010101, + 0.10101010101, 0.10101010101, 0.06936026936, 0.12457912458, 0, 0, 0.0101010101, 0.10101010101, + 0.05387205387, 0.05387205387, 0.05387205387, 0.05387205387, 0.05387205387, 0.08282828283, + 0.04511784512, 0.10101010101, 0.10101010101, 0.10101010101, 0.10101010101, 0.00875420875, + 0.10101010101, 0.09090909091, 0.05387205387, 0.05387205387, 0.05387205387, 0.05387205387, + 0.05387205387, 0.05387205387, 0.05387205387, 0.04377104377, 0.04377104377, 0.04377104377, + 0.04377104377, 0.04377104377, 0.04175084175, 0.05387205387, 0, 0, 0.04107744108, + 0.09090909091, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, + 0.08215488216, 0.04107744108, 0.08417508418, 0.08417508418, 0.08417508418, 0.08417508418, + 0.00808080808, 0.09090909091, 0.00808080808, + ], + rights: [ + 0.41548821549, 0.3595959596, 0.39461279461, 0.73131313131, 0.64713804714, 0.7797979798, + 0.90841750842, 0.17239057239, 0.41616161616, 0.41616161616, 0.45993265993, 0.64646464646, + 0.3468013468, 0.39528619529, 0.33939393939, 0.59191919192, 0.68215488215, 0.47003367003, + 0.65252525253, 0.63367003367, 0.6936026936, 0.64713804714, 0.66599326599, 0.6962962963, + 0.66666666667, 0.65925925926, 0.33939393939, 0.3468013468, 0.59865319865, 0.64646464646, + 0.59865319865, 0.46464646465, 0.99528619529, 0.81077441077, 0.7265993266, 0.77104377104, + 0.79191919192, 0.69023569024, 0.71043771044, 0.83164983165, 0.80134680135, 0.25925925926, + 0.55622895623, 0.79393939394, 0.68148148148, 0.97171717172, 0.77912457912, 0.87542087542, + 0.71515151515, 1.02356902357, 0.80269360269, 0.60875420875, 0.78855218855, 0.79326599327, + 0.80134680135, 1.16632996633, 0.75892255892, 0.77777777778, 0.69158249158, 0.44781144781, + 0.44107744108, 0.37037037037, 0.59932659933, 0.72525252525, 0.47070707071, 0.67070707071, + 0.71784511785, 0.63905723906, 0.67609427609, 0.70841750842, 0.5164983165, 0.65185185185, + 0.6632996633, 0.30235690236, 0.3696969697, 0.69562289562, 0.3494949495, 1.05387205387, + 0.66262626263, 0.6962962963, 0.71919191919, 0.68080808081, 0.53602693603, 0.51447811448, + 0.51447811448, 0.67003367003, 0.66734006734, 1.01616161616, 0.68282828283, 0.67205387205, + 0.62760942761, 0.47609427609, 0.40942760943, 0.47609427609, 0.60875420875, 0.41548821549, + 0.3595959596, 0.60606060606, 0.68754208754, 0.68484848485, 0.76902356902, 0.41616161616, + 0.57239057239, 0.59730639731, 0.97912457912, 0.46195286195, 0.59461279461, 0.64646464646, + 0.39528619529, 0.97912457912, 0.72525252525, 0.48417508418, 0.64646464646, 0.48754208754, + 0.46127946128, 0.50101010101, 0.6632996633, 0.62760942761, 0.34006734007, 0.42558922559, + 0.38316498317, 0.46531986532, 0.62154882155, 1.00269360269, 1.0531986532, 1.0228956229, + 0.46464646465, 0.81077441078, 0.81077441078, 0.81077441077, 0.81077441077, 0.81077441077, + 0.81077441077, 1.1468013468, 0.77104377104, 0.69023569024, 0.69023569024, 0.69023569024, + 0.69023569024, 0.31582491583, 0.38855218855, 0.42424242424, 0.44915824916, 0.79191919192, + 0.77912457912, 0.87542087542, 0.87542087542, 0.87542087542, 0.87542087542, 0.87542087542, + 0.64713804714, 0.86666666667, 0.79326599327, 0.79326599327, 0.79326599327, 0.79326599327, + 0.77777777778, 0.71582491582, 0.69966329966, 0.67070707071, 0.67070707071, 0.67070707071, + 0.67070707071, 0.67070707071, 0.67070707071, 1.15218855219, 0.63905723906, 0.70841750842, + 0.70841750842, 0.70841750842, 0.70841750842, 0.28821548822, 0.36363636364, 0.43097643098, + 0.42962962963, 0.6936026936, 0.66262626263, 0.6962962963, 0.6962962963, 0.6962962963, + 0.6962962963, 0.6962962963, 0.64646464646, 0.6936026936, 0.67003367003, 0.67003367003, + 0.67003367003, 0.67003367003, 0.67205387205, 0.71919191919, 0.67205387205, + ], + tops: [ + 1, 1.00404040404, 1, 1.00134680135, 1.10572390572, 1.00404040404, 1.00404040404, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1.00404040404, 1, 1.00404040404, 1.00404040404, 1, 1, 1.00404040404, 1, + 1.00404040404, 1.00404040404, 1, 1, 1, 1, 1, 1.00404040404, 1, 1, 1, 1.00336700337, 1, 1, 1, + 1.00336700337, 1, 1, 1, 1, 1, 1, 1, 1.00404040404, 1, 1.00404040404, 1, 1.00336700337, 1, 1, + 1, 1, 1, 1, 1, 1.01683501683, 1, 1.01683501683, 1, 1, 1, 1, 1.01683501683, 1, 1.01683501683, + 1, 1.01683501683, 1, 1.01683501683, 1, 1, 1.01683501683, 1.01683501683, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1.01144781145, 1, 1.01144781145, 1, 1, 1, 1, 1.00404040404, 1, 1, 1, + 1.00336700337, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00269360269, 1, 1, 1, 1, 1, + 1.00404040404, 1.00404040404, 1.00404040404, 1, 1.29158249158, 1.29158249158, 1.29494949495, + 1.20673400673, 1.22087542088, 1.22154882155, 1, 1.00336700337, 1.29158249158, 1.29158249158, + 1.29494949495, 1.22087542088, 1.29158249158, 1.29158249158, 1.29494949495, 1.22087542088, 1, + 1.20673400673, 1.29158249158, 1.29158249158, 1.29494949495, 1.20673400673, 1.22087542088, 1, + 1.00404040404, 1.29158249158, 1.29158249158, 1.29494949495, 1.22087542088, 1.29158249158, 1, + 1.01683501683, 1.08956228956, 1.08956228956, 1.09292929293, 1.00471380471, 1.01885521886, + 1.14747474747, 1, 1, 1.08956228956, 1.08956228956, 1.09292929293, 1.01885521886, + 1.08956228956, 1.08956228956, 1.09292929293, 1.01885521886, 1.01683501683, 1.00471380471, + 1.08956228956, 1.08956228956, 1.09292929293, 1.00471380471, 1.01885521886, 1, 1, + 1.08956228956, 1.08956228956, 1.09292929293, 1.01885521886, 1.08956228956, 1.01683501683, + 1.01885521886, + ], + bottoms: [ + 0, -0.01346801347, 0, -0.01346801347, -0.16565656566, -0.01346801347, -0.01346801347, 0, + -0.28821548822, -0.28821548822, 0, 0, -0.24444444444, 0, -0.01346801347, 0, -0.01346801347, 0, + 0, -0.01346801347, 0, -0.01346801347, -0.01683501684, 0, -0.01346801347, -0.01683501684, + -0.01346801347, -0.24444444444, 0, 0, 0, -0.01346801347, -0.09023569024, 0, 0, -0.01683501683, + 0, 0, 0, -0.01683501683, 0, 0, -0.01346801347, 0, 0, -0.01346801347, -0.01346801347, + -0.01683501684, 0, -0.20404040404, 0, -0.01683501683, 0, -0.01683501683, -0.01346801347, + -0.01346801347, 0, 0, 0, -0.28282828283, 0, -0.28282828283, 0, -0.17104377104, 0, + -0.01346801347, -0.01346801347, -0.01346801347, -0.01279461279, -0.01346801347, 0, + -0.28282828283, 0, 0, -0.28282828283, 0, -0.01346801347, 0, 0, -0.01346801347, -0.28282828283, + -0.28282828283, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, + -0.01346801347, 0, -0.28282828283, 0, -0.28282828283, -0.18585858586, -0.28282828283, 0, 0, + -0.28282828283, -0.10235690236, 0, 0, 0, -0.18585858586, -0.01548821549, 0, -0.00942760943, 0, + 0, 0, 0, -0.00942760943, 0, 0, -0.01346801347, 0, 0, 0, -0.28282828283, -0.16835016835, 0, + -0.3063973064, 0, 0, 0, -0.02356902357, -0.02356902357, -0.02356902357, -0.28282828283, 0, 0, + 0, 0, 0, 0, 0, -0.3063973064, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01346801347, -0.01683501683, + -0.01683501683, -0.01683501684, -0.01683501684, -0.01683501684, 0, -0.01683501684, + -0.01683501683, -0.01683501683, -0.01683501684, -0.01683501684, 0, 0, -0.01346801347, + -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, + -0.01346801347, -0.01346801347, -0.3063973064, -0.01346801347, -0.01346801347, -0.01346801347, + -0.01346801347, 0, 0, 0, 0, -0.01346801347, 0, -0.01346801347, -0.01346801347, -0.01346801347, + -0.01346801347, -0.01346801347, 0, -0.01346801347, -0.01346801347, -0.01346801347, + -0.01346801347, -0.01346801347, -0.28282828283, -0.28282828283, -0.28282828283, + ], + afterStack: 0.04107744108, + bold: { + advances: [ + 0.41548821549, 0.5063973064, 0.50572390572, 0.80808080808, 0.80808080808, 0.94343434343, + 0.97373737374, 0.3164983165, 0.5063973064, 0.5063973064, 0.59595959596, 0.80808080808, + 0.5063973064, 0.5063973064, 0.5063973064, 0.53804713805, 0.80808080808, 0.80808080808, + 0.80808080808, 0.80808080808, 0.80808080808, 0.80808080808, 0.80808080808, 0.80808080808, + 0.80808080808, 0.80808080808, 0.5063973064, 0.5063973064, 0.80808080808, 0.80808080808, + 0.80808080808, 0.60404040404, 1.06262626263, 0.8734006734, 0.82087542088, 0.84377104377, + 0.8861952862, 0.78451178451, 0.80471380471, 0.92592592593, 0.94276094276, 0.38383838384, + 0.73468013468, 0.85117845118, 0.76228956229, 1.02760942761, 0.92053872054, 0.9696969697, + 0.80942760943, 0.97777777778, 0.84242424242, 0.70505050505, 0.84377104377, 0.93468013468, + 0.85723905724, 1.21885521886, 0.82828282828, 0.84579124579, 0.77239057239, 0.55420875421, + 0.49023569024, 0.55420875421, 0.80808080808, 0.80808080808, 0.80808080808, 0.73468013468, + 0.80202020202, 0.70572390572, 0.80067340067, 0.79259259259, 0.50976430976, 0.69225589226, + 0.81750841751, 0.41144781145, 0.50572390572, 0.75555555556, 0.40673400673, 1.18518518519, + 0.81414141414, 0.78047138047, 0.80336700337, 0.80538720539, 0.58922558923, 0.59393939394, + 0.5468013468, 0.81481481481, 0.72727272727, 1.08080808081, 0.76161616162, 0.73602693603, + 0.72861952862, 0.59797979798, 0.80808080808, 0.59797979798, 0.80808080808, 0.41548821549, + 0.5063973064, 0.80808080808, 0.72323232323, 0.80808080808, 0.78653198653, 0.80808080808, + 0.62558922559, 0.80808080808, 0.98316498316, 0.59191919192, 0.80808080808, 0.80808080808, + 0.5063973064, 0.98316498316, 0.80808080808, 0.80808080808, 0.80808080808, 0.62222222222, + 0.62558922559, 0.80808080808, 0.75420875421, 0.72323232323, 0.5063973064, 0.80808080808, + 0.62222222222, 0.59191919192, 0.80808080808, 1.12323232323, 1.12323232323, 1.12323232323, + 0.60404040404, 0.8734006734, 0.8734006734, 0.8734006734, 0.8734006734, 0.8734006734, + 0.8734006734, 1.28956228956, 0.84377104377, 0.78451178451, 0.78451178451, 0.78451178451, + 0.78451178451, 0.38383838384, 0.38383838384, 0.38383838384, 0.38383838384, 0.8861952862, + 0.92053872054, 0.9696969697, 0.9696969697, 0.9696969697, 0.9696969697, 0.9696969697, + 0.80808080808, 0.94276094276, 0.93468013468, 0.93468013468, 0.93468013468, 0.93468013468, + 0.84579124579, 0.76902356902, 0.75353535353, 0.73468013468, 0.73468013468, 0.73468013468, + 0.73468013468, 0.73468013468, 0.73468013468, 1.1898989899, 0.70572390572, 0.79259259259, + 0.79259259259, 0.79259259259, 0.79259259259, 0.41144781145, 0.41144781145, 0.41144781145, + 0.41144781145, 0.78047138047, 0.81414141414, 0.78047138047, 0.78047138047, 0.78047138047, + 0.78047138047, 0.78047138047, 0.80808080808, 0.78047138047, 0.81481481481, 0.81481481481, + 0.81481481481, 0.81481481481, 0.73602693603, 0.80336700337, 0.73602693603, + ], + lefts: [ + 0, 0.1468013468, 0.04713804714, 0.04377104377, 0.10437710438, 0.02087542088, 0.07542087542, + 0.08080808081, 0.10976430976, 0.10976430976, 0.02356902357, 0.11043771044, 0.08888888889, + 0.0734006734, 0.11717171717, 0.01077441077, 0.05050505051, 0.18249158249, 0.0936026936, + 0.0962962963, 0.04511784512, 0.11111111111, 0.08888888889, 0.09494949495, 0.07878787879, + 0.07811447811, 0.11717171717, 0.08888888889, 0.12929292929, 0.12053872054, 0.17845117845, + 0.06936026936, 0.04713804714, 0.00336700337, 0.10101010101, 0.05387205387, 0.10101010101, + 0.10101010101, 0.10101010101, 0.05387205387, 0.10101010101, 0.10437710438, 0.01144781145, + 0.10101010101, 0.10101010101, 0.01346801347, 0.10101010101, 0.05387205387, 0.10101010101, + 0.05387205387, 0.10101010101, 0.05387205387, 0.01346801347, 0.10101010101, 0.00336700337, + 0.00336700337, 0.00336700337, 0.00336700337, 0.05387205387, 0.10101010101, 0, 0.10101010101, + 0.1265993266, 0, 0.24915824916, 0.04377104377, 0.07744107744, 0.04377104377, 0.05723905724, + 0.04377104377, 0.02356902357, 0.03367003367, 0.09090909091, 0.04377104377, 0, 0.09090909091, + 0.11986531987, 0.09090909091, 0.09090909091, 0.04377104377, 0.07744107744, 0.05723905724, + 0.09090909091, 0.04377104377, 0.032996633, 0.09090909091, 0.00336700337, 0.00875420875, + 0.00336700337, 0.00336700337, 0.04377104377, 0.05454545455, 0.34006734007, 0.05454545455, + 0.12121212121, 0, 0.1468013468, 0.15084175084, 0.06868686869, 0.04579124579, 0, + 0.33939393939, 0.03703703704, 0.09764309764, 0.05050505051, 0.09966329966, 0.06666666667, + 0.11043771044, 0.0734006734, 0.05050505051, 0, 0.26060606061, 0.11043771044, 0.07609427609, + 0.09898989899, 0.27003367003, 0.06060606061, 0.07946127946, 0.13804713805, 0.28552188552, + 0.14882154882, 0.07070707071, 0.0936026936, 0.06195286195, 0.05723905724, 0.04242424242, + 0.06936026936, 0.00336700337, 0.00336700337, 0.00336700337, 0.00336700337, 0.00336700337, + 0.00336700337, 0.00134680135, 0.05387205387, 0.10101010101, 0.10101010101, 0.10101010101, + 0.10101010101, 0.0101010101, 0.10437710438, 0, 0, 0.01750841751, 0.10101010101, + 0.05387205387, 0.05387205387, 0.05387205387, 0.05387205387, 0.05387205387, 0.10303030303, + 0.0404040404, 0.10101010101, 0.10101010101, 0.10101010101, 0.10101010101, 0.00336700337, + 0.08080808081, 0.07070707071, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, + 0.04377104377, 0.04377104377, 0.03367003367, 0.04377104377, 0.04377104377, 0.04377104377, + 0.04377104377, 0.04377104377, 0.04377104377, 0.04713804714, 0, 0, 0.04377104377, + 0.09090909091, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, + 0.11043771044, 0.04377104377, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, + 0.00336700337, 0.07744107744, 0.00336700337, + ], + rights: [ + 0.41548821549, 0.367003367, 0.47003367003, 0.79057239057, 0.70168350168, 0.90774410774, + 0.89764309764, 0.24781144781, 0.43636363636, 0.43636363636, 0.55286195286, 0.71515151515, + 0.367003367, 0.42962962963, 0.3595959596, 0.53333333333, 0.7569023569, 0.55824915825, + 0.75084175084, 0.70235690236, 0.76228956229, 0.71582491582, 0.73872053872, 0.77508417508, + 0.72592592593, 0.72794612795, 0.3595959596, 0.367003367, 0.66734006734, 0.72525252525, + 0.7164983165, 0.55286195286, 1.01548821549, 0.87003367003, 0.767003367, 0.80336700337, + 0.83232323232, 0.73063973064, 0.75084175084, 0.87205387205, 0.84175084175, 0.27946127946, + 0.64377104377, 0.87003367003, 0.72188552189, 1.02087542088, 0.81952861953, 0.91582491582, + 0.75555555556, 1.03636363636, 0.85925925926, 0.65117845118, 0.8303030303, 0.83367003367, + 0.85387205387, 1.21548821549, 0.82491582492, 0.84242424242, 0.71851851852, 0.4531986532, + 0.49494949495, 0.4531986532, 0.67946127946, 0.81279461279, 0.54276094276, 0.70168350168, + 0.74478114478, 0.66195286195, 0.72323232323, 0.74882154882, 0.54276094276, 0.67205387205, + 0.7265993266, 0.32053872054, 0.39797979798, 0.75218855219, 0.36767676768, 1.09427609428, + 0.72323232323, 0.7367003367, 0.74612794613, 0.72794612795, 0.57912457912, 0.55016835017, + 0.50707070707, 0.72390572391, 0.72390572391, 1.07205387205, 0.75824915825, 0.72592592593, + 0.68484848485, 0.54545454545, 0.47878787879, 0.54545454545, 0.67407407407, 0.41548821549, + 0.367003367, 0.62962962963, 0.7138047138, 0.75016835017, 0.81279461279, 0.47811447811, + 0.59259259259, 0.70707070707, 0.99932659933, 0.51245791246, 0.67542087542, 0.71515151515, + 0.42962962963, 0.99932659933, 0.81279461279, 0.58585858586, 0.71515151515, 0.50774410774, + 0.48148148148, 0.55016835017, 0.6936026936, 0.62760942761, 0.38047138047, 0.55084175084, + 0.40336700337, 0.5063973064, 0.70235690236, 1.05791245791, 1.08282828283, 1.08148148148, + 0.55286195286, 0.87003367003, 0.87003367003, 0.87003367003, 0.87003367003, 0.87003367003, + 0.87003367003, 1.24915824916, 0.80336700337, 0.73063973064, 0.73063973064, 0.73063973064, + 0.73063973064, 0.3037037037, 0.38451178451, 0.47205387205, 0.51178451178, 0.83232323232, + 0.81952861953, 0.91582491582, 0.91582491582, 0.91582491582, 0.91582491582, 0.91582491582, + 0.72457912458, 0.90235690236, 0.83367003367, 0.83367003367, 0.83367003367, 0.83367003367, + 0.84242424242, 0.73535353535, 0.71986531987, 0.70168350168, 0.70168350168, 0.70168350168, + 0.70168350168, 0.70168350168, 0.70168350168, 1.16632996633, 0.66195286195, 0.74882154882, + 0.74882154882, 0.74882154882, 0.74882154882, 0.33737373737, 0.37171717172, 0.49898989899, + 0.50505050505, 0.7367003367, 0.72323232323, 0.7367003367, 0.7367003367, 0.7367003367, + 0.7367003367, 0.7367003367, 0.71515151515, 0.7367003367, 0.72390572391, 0.72390572391, + 0.72390572391, 0.72390572391, 0.72592592593, 0.74612794613, 0.72592592593, + ], + tops: [ + 1, 1.00404040404, 1, 1.00134680135, 1.11515151515, 1.00404040404, 1.00404040404, 1, + 1.00606060606, 1.00606060606, 1, 1, 1, 1, 1, 1, 1.00404040404, 1, 1.00404040404, + 1.00404040404, 1, 1, 1.00606060606, 1, 1.00404040404, 1.00404040404, 1, 1, 1, 1, 1, + 1.00404040404, 1, 1, 1, 1.00336700337, 1, 1, 1, 1.00336700337, 1, 1, 1, 1, 1, 1, 1, + 1.00404040404, 1, 1.00404040404, 1, 1.00336700337, 1, 1, 1, 1, 1, 1, 1, 1.01683501683, 1, + 1.01683501683, 1, 1, 1, 1, 1.0303030303, 1, 1.0303030303, 1, 1.01683501683, 1, 1.0303030303, + 1.00067340067, 1.00067340067, 1.0303030303, 1.0303030303, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1.01683501683, 1.01683501683, 1.01683501683, 1, 1, 1, 1, 1.00404040404, 1, 1, + 1.01683501683, 1.00336700337, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00269360269, 1, 1, + 1, 1, 1, 1.01548821549, 1.01548821549, 1.02356902357, 1, 1.26464646465, 1.26464646465, + 1.27946127946, 1.2202020202, 1.25925925926, 1.20740740741, 1, 1.00336700337, 1.26464646465, + 1.26464646465, 1.27946127946, 1.25925925926, 1.26464646465, 1.26464646465, 1.27946127946, + 1.25925925926, 1, 1.2202020202, 1.26464646465, 1.26464646465, 1.27946127946, 1.2202020202, + 1.25925925926, 1, 1.00404040404, 1.26464646465, 1.26464646465, 1.27946127946, 1.25925925926, + 1.26464646465, 1, 1.01683501683, 1.01548821549, 1.01548821549, 1.0303030303, 1, + 1.0101010101, 1.10303030303, 1, 1, 1.01548821549, 1.01548821549, 1.0303030303, 1.0101010101, + 1.01548821549, 1.01548821549, 1.0303030303, 1.0101010101, 1.02154882155, 1, 1.01548821549, + 1.01548821549, 1.0303030303, 1, 1.0101010101, 1, 1, 1.01548821549, 1.01548821549, + 1.0303030303, 1.0101010101, 1.01548821549, 1.0303030303, 1.0101010101, + ], + bottoms: [ + 0, -0.01346801347, 0, -0.01346801347, -0.15824915825, -0.01346801347, -0.01346801347, 0, + -0.3063973064, -0.3063973064, 0, 0, -0.25185185185, 0, -0.03367003367, 0, -0.01346801347, 0, + 0, -0.01346801347, 0, -0.01346801347, -0.01346801347, 0, -0.01346801347, -0.01885521886, + -0.03367003367, -0.25185185185, 0, 0, 0, -0.01346801347, -0.09023569024, 0, 0, + -0.01683501683, 0, 0, 0, -0.01683501683, 0, 0, -0.01346801347, 0, 0, -0.01346801347, + -0.01346801347, -0.01683501684, 0, -0.2101010101, 0, -0.01683501683, 0, -0.01683501683, + -0.01346801347, -0.01346801347, 0, 0, 0, -0.28282828283, 0, -0.28282828283, 0, + -0.22491582492, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, + -0.01346801347, 0, -0.28282828283, 0, 0, -0.28282828283, 0, -0.01346801347, 0, 0, + -0.01346801347, -0.28282828283, -0.28282828283, 0, -0.01346801347, -0.01346801347, + -0.01346801347, -0.01346801347, -0.01346801347, 0, -0.28282828283, 0, -0.28282828283, + -0.28282828283, -0.28282828283, 0, 0, -0.28282828283, 0, 0, 0, 0, -0.28282828283, + -0.01548821549, 0, -0.02962962963, 0, 0, 0, 0, -0.02962962963, 0, 0, 0, 0, 0, 0, + -0.28282828283, -0.16835016835, 0, -0.2936026936, 0, 0, 0, -0.02356902357, -0.02356902357, + -0.02356902357, -0.28282828283, 0, 0, 0, 0, 0, 0, 0, -0.2936026936, 0, 0, 0, 0, 0, 0, 0, 0, + 0, -0.01346801347, -0.01683501683, -0.01683501683, -0.01683501684, -0.01683501684, + -0.01683501684, 0, -0.01683501684, -0.01683501683, -0.01683501683, -0.01683501684, + -0.01683501684, 0, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, + -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.2936026936, + -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, 0, 0, 0, 0, -0.01346801347, + 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, 0, + -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, + -0.28282828283, -0.28282828283, -0.28282828283, + ], + }, }, Verdana: { below: 0.28878441907, @@ -1512,5 +4746,265 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01410342512, 0, -0.00738750839, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], + lefts: [ + 0, 0.19543317663, 0.11282740094, 0.13096037609, 0.1040967092, 0.10006715917, 0.07723304231, + 0.11014103425, 0.12155809268, 0.09872397582, 0.11215580927, 0.14103425118, 0.09872397582, + 0.10275352586, 0.16991269308, 0, 0.0920080591, 0.18670248489, 0.10812625923, 0.11215580927, + 0.05171255876, 0.12558764271, 0.0920080591, 0.10342511753, 0.08193418402, 0.07588985897, + 0.2323707186, 0.15446608462, 0.17058428475, 0.1645399597, 0.17998656817, 0.10745466756, + 0.11820013432, 0.01746138348, 0.13431833445, 0.07723304231, 0.13431833445, 0.13431833445, + 0.13431833445, 0.07723304231, 0.13431833445, 0.0920080591, 0.02955003358, 0.13767629281, + 0.13431833445, 0.13431833445, 0.13431833445, 0.07723304231, 0.13431833445, 0.07723304231, + 0.13431833445, 0.08999328408, 0, 0.11954331766, 0.01746138348, 0.06178643385, 0.04566823371, + 0.00402955003, 0.08462055071, 0.16051040967, 0.04701141706, 0.11484217596, 0.12491605104, 0, + 0.22834116857, 0.06984553392, 0.12424445937, 0.07051712559, 0.0725319006, 0.07118871726, + 0.04566823371, 0.0725319006, 0.12424445937, 0.11752854265, 0, 0.12961719275, 0.12558764271, + 0.12424445937, 0.12424445937, 0.07118871726, 0.12424445937, 0.0725319006, 0.12424445937, + 0.07387508395, 0.04163868368, 0.11887172599, 0.04096709201, 0.05775688381, 0.04029550034, + 0.04096709201, 0.06245802552, 0.1161853593, 0.25386165212, 0.12558764271, 0.12558764271, 0, + 0.19543317663, 0.10678307589, 0.0920080591, 0.09267965077, 0.0725319006, 0.25386165212, + 0.11551376763, 0.2323707186, 0.10678307589, 0.10141034251, 0.1114842176, 0.14103425118, + 0.10275352586, 0.10678307589, 0, 0.10342511753, 0.14439220954, 0.13901947616, 0.13901947616, + 0.36333109469, 0.12760241773, 0.0920080591, 0.16991269308, 0.23707186031, 0.19543317663, + 0.08126259234, 0.11685695097, 0.11484217596, 0.11484217596, 0.09402283412, 0.07588985897, + 0.01746138348, 0.01746138348, 0.01746138348, 0.01746138348, 0.01746138348, 0.01746138348, + 0.00940228341, 0.07723304231, 0.13431833445, 0.13431833445, 0.13431833445, 0.13431833445, + 0.0920080591, 0.0920080591, 0.06245802552, 0.08462055071, 0.00940228341, 0.13431833445, + 0.07723304231, 0.07723304231, 0.07723304231, 0.07723304231, 0.07521826729, 0.19543317663, + 0.07723304231, 0.11954331766, 0.11954331766, 0.11954331766, 0.11954331766, 0.00402955003, + 0.13431833445, 0.12424445937, 0.06984553392, 0.06984553392, 0.06984553392, 0.06984553392, + 0.06984553392, 0.06984553392, 0.06984553392, 0.07051712559, 0.07118871726, 0.07118871726, + 0.07118871726, 0.07118871726, 0, 0.10745466756, 0, 0.00335795836, 0.07118871726, + 0.12424445937, 0.07118871726, 0.07118871726, 0.07118871726, 0.07118871726, 0.07118871726, + 0.14103425117, 0.06245802552, 0.11887172599, 0.11887172599, 0.11887172599, 0.11887172599, + 0.04096709201, 0.12424445937, 0.04096709201, + ], + rights: [ + 0.48354600403, 0.34586971122, 0.51846877099, 0.99462726662, 0.77904633983, 1.3801208865, + 1.04432505037, 0.25923438549, 0.52585627938, 0.50302216253, 0.76359973136, 0.98455339154, + 0.38616521155, 0.52182672935, 0.33042310275, 0.57756883815, 0.78374748153, 0.72800537273, + 0.78509066488, 0.77098723976, 0.80792478173, 0.77703156481, 0.79986568167, 0.78777703156, + 0.79247817327, 0.78374748153, 0.39288112827, 0.44190732035, 0.94560107455, 0.96104768301, + 0.95500335796, 0.67494963062, 1.25587642713, 0.92276695769, 0.8885157824, 0.90664875756, + 0.97918065816, 0.79314976494, 0.77300201477, 0.9684351914, 0.89926124916, 0.48690396239, + 0.50100738751, 0.93821356615, 0.76695768972, 1.02484889187, 0.89724647414, 1.00604432505, + 0.78844862324, 1.02619207522, 0.96171927468, 0.86098052384, 0.8475486904, 0.88717259906, + 0.92276695769, 1.29818670248, 0.89724647414, 0.84217595702, 0.86501007388, 0.50973807925, + 0.64472800537, 0.46406984553, 1.00067159167, 0.87709872398, 0.51175285426, 0.70718603089, + 0.7844190732, 0.67897918066, 0.73270651444, 0.75218267293, 0.5278710544, 0.73270651444, + 0.75151108126, 0.25990597717, 0.35795836132, 0.80523841504, 0.2518468771, 1.21893888516, + 0.75151108126, 0.76359973136, 0.7844190732, 0.73270651444, 0.59234385494, 0.66017461383, + 0.51376762928, 0.74613834788, 0.77300201477, 1.0678307589, 0.77367360645, 0.77300201477, + 0.6682337139, 0.74748153123, 0.37071860309, 0.75688381464, 1, 0.48354600403, 0.34586971122, + 0.75218267293, 0.78106111484, 0.7844190732, 0.79986568167, 0.37071860309, 0.75755540631, + 0.64338482203, 1.26863666891, 0.63398253862, 0.76964405641, 0.97783747482, 0.52182672935, + 1.26863666891, 0.87709872398, 0.64204163868, 0.98119543318, 0.64942914708, 0.64204163868, + 0.64674278039, 0.75486903962, 0.74278038952, 0.33042310275, 0.59100067159, 0.61383478845, + 0.66890530557, 0.77501678979, 1.24714573539, 1.31296171927, 1.28475486904, 0.64338482203, + 0.92276695769, 0.92276695769, 0.92276695769, 0.92276695769, 0.92276695769, 0.92276695769, + 1.27669576897, 0.90664875756, 0.79314976494, 0.79314976494, 0.79314976494, 0.79314976494, + 0.48690396239, 0.48690396239, 0.52115513768, 0.49563465413, 0.98589657488, 0.89724647414, + 1.00604432505, 1.00604432505, 1.00604432505, 1.00604432505, 1.00402955003, 0.93015446609, + 1.00604432505, 0.88717259906, 0.88717259906, 0.88717259906, 0.88717259906, 0.84217595702, + 0.78844862324, 0.78240429819, 0.70718603089, 0.70718603089, 0.70718603089, 0.70718603089, + 0.70718603089, 0.70718603089, 1.24580255205, 0.67897918066, 0.75218267294, 0.75218267294, + 0.75218267294, 0.75218267294, 0.26930826058, 0.39086635326, 0.38415043654, 0.37407656145, + 0.76359973136, 0.75151108126, 0.76359973136, 0.76359973136, 0.76359973136, 0.76359973136, + 0.76359973136, 0.98455339154, 0.76359973136, 0.74613834789, 0.74613834789, 0.74613834789, + 0.74613834788, 0.77300201478, 0.7844190732, 0.77300201478, + ], + tops: [ + 1, 1, 1, 1, 1.05842847549, 1.01880456682, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, + 1, 1, 1, 1, 1.04499664204, 1.02014775017, 1.00335795836, 1.02081934184, 1.02081934184, 1, 1, + 1.01880456682, 1, 1.02283411686, 1.02014775017, 1, 1, 1, 1, 1, 1.02014775017, 1.02014775017, + 1, 1, 1.01813297515, 1, 1, 1, 1.01813297515, 1, 1, 1, 1, 1, 1, 1, 1.02081934184, 1, + 1.02081934184, 1, 1.01813297515, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, + 1.04499664204, 1, 1, 1, 1, 1.04499664204, 1, 1.04499664204, 1, 1.05171255876, 1, + 1.04499664204, 1.00671591672, 1.00671591672, 1.04499664204, 1.04499664204, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, 1.04499664204, 1, 1, 1, 1, 1.0194761585, + 1, 1, 1.04499664204, 1.02014775017, 1, 1.02081934184, 1, 1, 1, 1, 1.02081934184, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00268636669, 1.00268636669, 1.01880456682, 1, 1.37609133647, + 1.37609133647, 1.37609133647, 1.33781061115, 1.25721961048, 1.37609133647, 1, 1.01813297515, + 1.37609133647, 1.37609133647, 1.37609133647, 1.25721961048, 1.37609133647, 1.37609133647, + 1.37609133647, 1.25721961048, 1, 1.33781061115, 1.37609133647, 1.37609133647, 1.37609133647, + 1.33781061115, 1.25721961048, 1, 1.08193418402, 1.37609133647, 1.37609133647, 1.37609133647, + 1.25721961048, 1.37609133647, 1, 1.05171255876, 1.12558764271, 1.12558764271, 1.12558764271, + 1.08730691739, 1.00671591672, 1.32236400269, 1, 1, 1.12558764271, 1.12558764271, + 1.12558764271, 1.00671591672, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, + 1.05171255876, 1.08730691739, 1.12558764271, 1.12558764271, 1.12558764271, 1.08730691739, + 1.00671591672, 1, 1, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, + 1.12558764271, 1.04499664204, 1.00671591672, + ], + bottoms: [ + 0, 0, 0, 0, -0.24244459369, -0.0194761585, -0.02081934184, 0, -0.27669576897, -0.27669576897, + 0, 0, -0.24848891874, 0, 0, -0.20416386837, -0.02081934184, 0, 0, -0.02081934184, 0, + -0.02081934184, -0.02081934184, 0, -0.02283411686, -0.0194761585, 0, -0.24848891874, 0, 0, 0, + 0, -0.15177971793, 0, 0, -0.01813297515, 0, 0, 0, -0.0194761585, 0, 0, -0.01410342512, 0, 0, + 0, 0, -0.02081934184, 0, -0.2639355272, 0, -0.01813297515, 0, -0.02081934184, 0, 0, 0, 0, 0, + -0.26326393553, -0.20416386837, -0.26326393553, 0, -0.20147750168, 0, -0.02081934184, + -0.02081934184, -0.01678979181, -0.02081934184, -0.01746138348, 0, -0.28408327737, 0, 0, + -0.28408327737, 0, 0, 0, 0, -0.02081934184, -0.27669576897, -0.27669576897, 0, -0.01813297515, + -0.01477501679, -0.02081934184, 0, 0, 0, -0.27669576897, 0, -0.26326393553, -0.26326393553, + -0.26326393553, 0, 0, 0, -0.24244459369, 0, 0, 0, -0.26326393553, -0.25856279382, 0, + -0.14103425118, 0, 0, 0, 0, -0.14103425118, 0, 0, 0, 0, 0, 0, -0.27669576897, -0.24378777703, + 0, -0.28408327737, 0, 0, 0, 0, 0, 0, -0.02014775017, 0, 0, 0, 0, 0, 0, 0, -0.28408327737, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, + -0.02081934184, 0, -0.09805238415, -0.02081934184, -0.02081934184, -0.02081934184, + -0.02081934184, 0, 0, -0.01611820013, -0.02081934184, -0.02081934184, -0.02081934184, + -0.02081934184, -0.02081934184, -0.02081934184, -0.0194761585, -0.28408327737, -0.01746138348, + -0.01746138348, -0.01746138348, -0.01746138348, 0, 0, 0, 0, -0.02081934184, 0, -0.02081934184, + -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, -0.09939556749, + -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.27669576897, + -0.27669576897, -0.27669576897, + ], + afterStack: 0.09066487576, + bold: { + advances: [ + 0.47011417058, 0.55339153794, 0.80792478173, 1.19274680994, 0.97783747482, 1.74949630625, + 1.18603089322, 0.45668233714, 0.74748153123, 0.74748153123, 0.97783747482, 1.19274680994, + 0.49697783747, 0.66017461383, 0.49697783747, 0.94828744124, 0.97783747482, 0.97783747482, + 0.97783747482, 0.97783747482, 0.97783747482, 0.97783747482, 0.97783747482, 0.97783747482, + 0.97783747482, 0.97783747482, 0.55339153794, 0.55339153795, 1.19274680994, 1.19274680994, + 1.19274680994, 0.84822028207, 1.32572196105, 1.0678307589, 1.04768300873, 0.99529885829, + 1.14170584285, 0.9395567495, 0.89456010745, 1.11551376763, 1.15177971793, 0.75083948959, + 0.76359973136, 1.0604432505, 0.8764271323, 1.30355943586, 1.1645399597, 1.16924110141, + 1.00805910007, 1.16924110141, 1.07588985897, 0.97716588314, 0.93754197448, 1.11685695097, + 1.05036937542, 1.5520483546, 1.05036937542, 1.01343183345, 0.9516453996, 0.74748153123, + 0.94828744124, 0.74748153123, 1.19274680994, 0.97783747482, 0.97783747482, 0.91873740766, + 0.96171927468, 0.80926796508, 0.96171927468, 0.91336467428, 0.58092679651, 0.96171927468, + 0.97985224983, 0.47011417058, 0.55406312962, 0.92276695769, 0.47011417058, 1.45533915379, + 0.97985224983, 0.9442578912, 0.96171927468, 0.96171927468, 0.68368032236, 0.8159838818, + 0.62659503022, 0.97985224983, 0.89388851578, 1.34721289456, 0.920080591, 0.89523169913, + 0.82068502351, 0.97783747482, 0.74748153123, 0.97783747482, 1.19274680994, 0.47011417058, + 0.55339153794, 0.97783747482, 0.97783747482, 0.97783747482, 0.97783747482, 0.74748153123, + 0.97783747482, 0.97783747482, 1.32572196105, 0.82202820685, 1.16856950974, 1.19274680994, + 0.66017461383, 1.32572196105, 0.97783747482, 0.80792478173, 1.19274680994, 0.82202820685, + 0.82202820685, 0.97783747482, 0.99194089993, 0.97783747482, 0.49697783747, 0.97783747482, + 0.82202820685, 0.82202820685, 1.16856950974, 1.62525184688, 1.62525184688, 1.62525184688, + 0.84822028207, 1.0678307589, 1.0678307589, 1.0678307589, 1.0678307589, 1.0678307589, + 1.0678307589, 1.50436534587, 0.99529885829, 0.9395567495, 0.9395567495, 0.9395567495, + 0.9395567495, 0.75083948959, 0.75083948959, 0.75083948959, 0.75083948959, 1.14170584285, + 1.1645399597, 1.16924110141, 1.16924110141, 1.16924110141, 1.16924110141, 1.16924110141, + 1.19274680994, 1.16924110141, 1.11685695097, 1.11685695097, 1.11685695097, 1.11685695097, + 1.01343183345, 1.01074546676, 0.9805238415, 0.91873740766, 0.91873740766, 0.91873740766, + 0.91873740766, 0.91873740766, 0.91873740766, 1.40026863667, 0.80926796508, 0.91336467428, + 0.91336467428, 0.91336467428, 0.91336467428, 0.47011417058, 0.47011417058, 0.47011417058, + 0.47011417058, 0.93418401612, 0.97985224983, 0.9442578912, 0.9442578912, 0.9442578912, + 0.9442578912, 0.9442578912, 1.19274680994, 0.9442578912, 0.97985224983, 0.97985224983, + 0.97985224983, 0.97985224983, 0.89523169913, 0.96171927468, 0.89523169913, + ], + lefts: [ + 0, 0.13633310947, 0.11215580927, 0.10006715917, 0.08999328408, 0.09603760913, 0.08126259234, + 0.11215580927, 0.12961719275, 0.1114842176, 0.13700470114, 0.14640698455, 0.02350570853, + 0.07387508395, 0.12290127602, 0.08260577569, 0.07521826729, 0.17864338482, 0.12424445937, + 0.09402283412, 0.05641370047, 0.11014103425, 0.08999328408, 0.10476830087, 0.06648757555, + 0.06984553392, 0.15110812626, 0.05171255876, 0.13700470114, 0.16722632639, 0.15849563465, + 0.09872397582, 0.09738079248, 0.01611820013, 0.12760241773, 0.06917394224, 0.12760241773, + 0.12760241773, 0.12760241773, 0.06917394224, 0.12760241773, 0.08260577569, 0.02820685024, + 0.12760241773, 0.12760241773, 0.12760241773, 0.12760241773, 0.06917394224, 0.12760241773, + 0.06917394224, 0.12760241773, 0.07320349228, 0.02753525856, 0.11349899261, 0.01611820013, + 0.04432505037, 0.01611820013, 0.00604432505, 0.0604432505, 0.16655473472, 0.12693082606, + 0.13297515111, 0.13230355944, 0, 0.25117528543, 0.05775688381, 0.11417058428, 0.05910006716, + 0.0604432505, 0.05910006716, 0.02887844191, 0.0604432505, 0.11417058428, 0.10745466756, 0, + 0.11417058428, 0.11417058428, 0.11349899261, 0.11417058428, 0.05910006716, 0.11417058428, + 0.0604432505, 0.11417058428, 0.06380120887, 0.02887844191, 0.10812625923, 0.02014775017, + 0.03022162525, 0.01746138348, 0.02014775017, 0.05641370047, 0.10208193418, 0.2760241773, + 0.13498992612, 0.10543989255, 0, 0.13633310947, 0.12625923439, 0.10342511753, 0.11349899261, + 0.03492276696, 0.2760241773, 0.10141034251, 0.20886501007, 0.08193418402, 0.10208193418, + 0.14573539288, 0.14506380121, 0.07387508395, 0.08193418402, 0, 0.12088650101, 0.14640698455, + 0.15446608462, 0.15043653459, 0.32572196105, 0.11417058428, 0.09066487576, 0.12290127602, + 0.29147078576, 0.18737407656, 0.08529214238, 0.19744795165, 0.13364674278, 0.12021490934, + 0.11887172599, 0.07521826729, 0.01611820013, 0.01611820013, 0.01611820013, 0.01611820013, + 0.01611820013, 0.01611820013, 0.00268636669, 0.06917394224, 0.12760241773, 0.12760241773, + 0.12760241773, 0.12760241773, 0.08260577569, 0.08260577569, 0.07588985897, 0.08260577569, + 0.01880456682, 0.12760241773, 0.06917394224, 0.06917394224, 0.06917394224, 0.06917394224, + 0.06917394224, 0.17730020148, 0.06917394224, 0.11349899261, 0.11349899261, 0.11349899261, + 0.11349899261, 0.00604432505, 0.12760241773, 0.11417058428, 0.05775688382, 0.05775688382, + 0.05775688382, 0.05775688382, 0.05775688382, 0.05775688382, 0.05775688382, 0.05910006716, + 0.05910006716, 0.05910006716, 0.05910006716, 0.05910006716, 0, 0.07051712559, 0, 0, + 0.05910006716, 0.11417058428, 0.05910006716, 0.05910006716, 0.05910006716, 0.05910006716, + 0.05910006716, 0.14640698455, 0.05910006716, 0.10812625923, 0.10812625923, 0.10812625923, + 0.10812625923, 0.02014775017, 0.11417058428, 0.02014775017, + ], + rights: [ + 0.47011417058, 0.41705842848, 0.69576897246, 1.09066487576, 0.89993284083, 1.65345869711, + 1.21020819342, 0.34452652787, 0.63599731363, 0.61786433848, 0.84083277367, 1.04633982539, + 0.41504365346, 0.58629952989, 0.37407656145, 0.82135661518, 0.90261920752, 0.84620550705, + 0.90933512424, 0.88314304903, 0.92343854936, 0.88784419073, 0.9079919409, 0.8885157824, + 0.91134989926, 0.88784419073, 0.40228341169, 0.44325050369, 1.03425117529, 1.02552048355, + 1.0557421088, 0.77300201477, 1.2276695769, 1.05171255876, 0.98321020819, 0.93351242445, + 1.0725319006, 0.85090664876, 0.84419073203, 1.0120886501, 1.0241773002, 0.6682337139, + 0.64875755541, 1.06111484218, 0.84889187374, 1.17595701813, 1.03693754197, 1.10006715917, + 0.95298858294, 1.10006715917, 1.09066487576, 0.92813969107, 0.91000671592, 1.00335795836, + 1.03425117529, 1.50772330423, 1.03425117529, 1.0073875084, 0.90060443251, 0.61517797179, + 0.86568166555, 0.58159838818, 1.06111484218, 0.98858294157, 0.65278710544, 0.81061114842, + 0.90127602418, 0.76359973136, 0.8475486904, 0.85695097381, 0.60308932169, 0.8475486904, + 0.8717259906, 0.36333109469, 0.440564137, 0.91470785762, 0.35661517797, 1.34586971122, + 0.8717259906, 0.88515782404, 0.90127602418, 0.8475486904, 0.66084620551, 0.76964405641, + 0.59637340497, 0.86568166555, 0.87374076561, 1.31699126931, 0.90261920752, 0.87508394896, + 0.76494291471, 0.84284754869, 0.47145735393, 0.87575554063, 1.08999328408, 0.47011417058, + 0.41705842848, 0.85359301545, 0.88985896575, 0.86165211551, 0.94291470786, 0.47145735393, + 0.8764271323, 0.76897246474, 1.24378777703, 0.69039623909, 0.97112155809, 1.03760913365, + 0.58629952989, 1.24378777703, 0.98858294157, 0.6877098724, 1.04633982539, 0.69644056414, + 0.67965077233, 0.72733378106, 0.87777031565, 0.84083277367, 0.37407656145, 0.6756212223, + 0.66218938885, 0.73673606447, 1.02283411686, 1.51914036266, 1.53324378778, 1.5520483546, + 0.74949630625, 1.05171255876, 1.05171255876, 1.05171255876, 1.05171255876, 1.05171255876, + 1.05171255876, 1.41571524513, 0.93351242445, 0.85090664876, 0.85090664876, 0.85090664876, + 0.85090664876, 0.6682337139, 0.6682337139, 0.6756212223, 0.6682337139, 1.07253190061, + 1.03693754198, 1.10006715917, 1.10006715917, 1.10006715917, 1.10006715917, 1.10006715917, + 1.01611820013, 1.10006715917, 1.00335795836, 1.00335795836, 1.00335795836, 1.00335795836, + 1.00738750839, 0.95298858294, 0.92679650772, 0.81061114842, 0.81061114842, 0.81061114842, + 0.81061114842, 0.81061114842, 0.81061114842, 1.3438549362, 0.76359973136, 0.85695097381, + 0.85695097381, 0.85695097381, 0.85695097381, 0.39825386165, 0.4721289456, 0.47884486232, + 0.48287441236, 0.87105439893, 0.8717259906, 0.88515782404, 0.88515782404, 0.88515782404, + 0.88515782404, 0.88515782404, 1.04633982539, 0.88515782404, 0.86568166555, 0.86568166555, + 0.86568166555, 0.86568166555, 0.87508394896, 0.90127602418, 0.87508394896, + ], + tops: [ + 1, 1, 1, 1, 1.05842847549, 1.0194761585, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, + 1, 1, 1, 1, 1.04499664204, 1.02081934184, 1.00268636669, 1.0194761585, 1.02081934184, 1, 1, + 1.01880456682, 1, 1.02283411686, 1.02081934184, 1, 1, 1, 1, 1, 1.02081934184, 1.0194761585, + 1, 1, 1.0194761585, 1, 1, 1, 1.0194761585, 1, 1, 1, 1, 1, 1, 1, 1.02081934184, 1, + 1.02081934184, 1, 1.01813297515, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, + 1.04499664204, 1, 1, 1, 1, 1.04499664204, 1, 1.04499664204, 1, 1.05171255876, 1, + 1.04499664204, 1.04499664204, 1.04499664204, 1.04499664204, 1.04499664204, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.04499664204, 1.04499664204, 1.04499664204, 1, 1, 1, 1, + 1.0194761585, 1, 1, 1.04499664204, 1.02081934184, 1, 1.02081934184, 1, 1, 1, 1, + 1.02081934184, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.00604432505, 1.00604432505, + 1.02081934184, 1, 1.37609133647, 1.37609133647, 1.36937541974, 1.33713901948, 1.2955003358, + 1.29952988583, 1, 1.0194761585, 1.37609133647, 1.37609133647, 1.37609133647, 1.2955003358, + 1.37609133647, 1.37609133647, 1.37609133647, 1.2955003358, 1, 1.33713901948, 1.37609133647, + 1.37609133647, 1.37609133647, 1.33713901948, 1.2955003358, 1, 1.06917394224, 1.37609133647, + 1.37609133647, 1.37609133647, 1.2955003358, 1.37609133647, 1, 1.05171255876, 1.12558764271, + 1.12558764271, 1.12558764271, 1.08663532572, 1.04499664204, 1.15648085964, 1, 1, + 1.12558764271, 1.12558764271, 1.12558764271, 1.04499664204, 1.12558764271, 1.12558764271, + 1.12558764271, 1.04499664204, 1.05708529214, 1.08663532572, 1.12558764271, 1.12558764271, + 1.12558764271, 1.08663532572, 1.04499664204, 1, 1, 1.12558764271, 1.12558764271, + 1.12558764271, 1.04499664204, 1.12558764271, 1.04499664204, 1.04499664204, + ], + bottoms: [ + 0, 0, 0, 0, -0.24244459369, -0.02081934184, -0.02081934184, 0, -0.27669576897, + -0.27669576897, 0, 0, -0.24848891874, 0, 0, -0.21759570181, -0.02081934184, 0, 0, + -0.02081934184, -0.00268636669, -0.02081934184, -0.02081934184, 0, -0.02283411686, + -0.0194761585, 0, -0.24848891874, -0.00470114171, 0, -0.00470114171, 0, -0.15379449295, 0, + 0, -0.0194761585, 0, 0, 0, -0.02081934184, 0, 0, -0.01544660846, 0, 0, 0, 0, -0.02081934184, + 0, -0.28542646071, 0, -0.01813297515, 0, -0.02081934184, 0, 0, 0, 0, 0, -0.26326393553, + -0.21759570181, -0.26326393553, 0, -0.23572867696, 0, -0.02014775017, -0.01477501679, + -0.02014775017, -0.02081934184, -0.02014775017, 0, -0.28408327737, 0, 0, -0.28408327737, 0, + 0, 0, 0, -0.02350570853, -0.27669576897, -0.27669576897, 0, -0.02081934184, -0.01477501679, + -0.02081934184, 0, 0, 0, -0.27669576897, 0, -0.26326393553, -0.26326393553, -0.26326393553, + 0, 0, 0, -0.24244459369, 0, 0, 0, -0.26326393553, -0.26326393553, 0, -0.14103425118, 0, 0, + 0, 0, -0.14103425118, 0, 0, 0, 0, 0, 0, -0.27669576897, -0.24378777703, 0, -0.28408327737, + 0, 0, 0, 0, 0, 0, -0.02014775017, 0, 0, 0, 0, 0, 0, 0, -0.28408327737, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, + -0.09536601746, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, 0, + -0.00940228341, -0.02014775017, -0.02014775017, -0.02014775017, -0.02014775017, + -0.02014775017, -0.02014775017, -0.02014775017, -0.28408327737, -0.02014775017, + -0.02014775017, -0.02014775017, -0.02014775017, 0, 0, 0, 0, -0.02350570853, 0, + -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, 0, + -0.10879785091, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, + -0.27669576897, -0.27669576897, -0.27669576897, + ], + }, }, }; diff --git a/src/fonts.ts b/src/fonts.ts index a9afb23..b9fa786 100644 --- a/src/fonts.ts +++ b/src/fonts.ts @@ -19,6 +19,12 @@ export interface FontInfo { * Roman is taller than its `H`. */ readonly capHeight?: number; + /** + * For a TrueType font, its bold face: the file Windows installs it as, and the top of its own + * capital `A` where it is not the regular face's. The leading CAD app makes the bold face's own + * `A` as tall as the text's height. + */ + readonly bold?: { readonly file: string; readonly capHeight?: number }; } /** @@ -45,55 +51,70 @@ export const FONTS = { pitchAndFamily: 34, family: "Arial, Helvetica, sans-serif", capHeight: 0.716, + bold: { file: "arialbd.ttf" }, }, Calibri: { file: "calibri.ttf", pitchAndFamily: 34, family: "Calibri, Carlito, sans-serif", capHeight: 0.6348, + bold: { file: "calibrib.ttf" }, }, Consolas: { file: "consola.ttf", pitchAndFamily: 49, family: "Consolas, monospace", capHeight: 0.638, + bold: { file: "consolab.ttf" }, }, "Courier New": { file: "cour.ttf", pitchAndFamily: 49, family: '"Courier New", Courier, monospace', capHeight: 0.571, + bold: { file: "courbd.ttf", capHeight: 0.5923 }, + }, + Georgia: { + file: "georgia.ttf", + pitchAndFamily: 18, + family: "Georgia, serif", + capHeight: 0.7026, + bold: { file: "georgiab.ttf" }, }, - Georgia: { file: "georgia.ttf", pitchAndFamily: 18, family: "Georgia, serif", capHeight: 0.7026 }, "Segoe UI": { file: "segoeui.ttf", pitchAndFamily: 34, family: '"Segoe UI", sans-serif', capHeight: 0.7, + bold: { file: "segoeuib.ttf" }, }, Tahoma: { file: "tahoma.ttf", pitchAndFamily: 34, family: "Tahoma, sans-serif", capHeight: 0.727, + bold: { file: "tahomabd.ttf" }, }, "Times New Roman": { file: "times.ttf", pitchAndFamily: 18, family: '"Times New Roman", Times, serif', capHeight: 0.6772, + bold: { file: "timesbd.ttf", capHeight: 0.6758 }, }, "Trebuchet MS": { file: "trebuc.ttf", pitchAndFamily: 34, family: '"Trebuchet MS", sans-serif', capHeight: 0.7251, + bold: { file: "trebucbd.ttf" }, }, Verdana: { file: "verdana.ttf", pitchAndFamily: 34, family: "Verdana, sans-serif", capHeight: 0.727, + bold: { file: "verdanab.ttf" }, }, } as const satisfies Readonly>; @@ -119,6 +140,15 @@ export function fontInfo(name: string): FontInfo | undefined { : undefined; } +/** + * The top of a TrueType font's capital `A` as a share of its size, in its bold face for `bold`, + * which the leading CAD app makes as tall as a text's height. Undefined for an SHX font. + */ +export function capHeightOf(font: string, bold = false): number | undefined { + const info = fontInfo(font); + return (bold ? info?.bold?.capHeight : undefined) ?? info?.capHeight; +} + /** Each font of `FONTS` by its name, its file and its file without the extension, in lower case. */ const FONT_NAMES: ReadonlyMap = new Map( (Object.entries(FONTS) as [Font, FontInfo][]).flatMap(([font, info]) => [ diff --git a/src/format.ts b/src/format.ts index 4167662..8ac5d71 100644 --- a/src/format.ts +++ b/src/format.ts @@ -10,6 +10,17 @@ export function written(value: number): number { return Object.is(rounded, -0) ? 0 : rounded; } +/** + * A number with 15 significant digits and no exponent, which JavaScript writes for a number + * under a millionth. Summed as a whole number, 15 digits stay under 2^53, so the double + * the leading CAD app reads from them can be worked out exactly, where a 16th may move it a unit in + * the last place. + */ +export function fifteenDigits(value: number): string { + const kept = Number(value.toPrecision(15)); + return Math.abs(kept) < 1e-6 ? kept.toFixed(20) : String(kept); +} + /** * An arc angle in degrees as the DXF writers print it: rounded to 6 decimals, * with 0 in place of an angle that rounds up to 360. diff --git a/src/index.ts b/src/index.ts index 4d733e8..1646cd6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -73,10 +73,15 @@ export { type Line, type LinearDimension, type LinearDimensionOptions, + type LineSpacingStyle, type Linetype, type LinetypeChoice, type LinetypeDefinition, type Lineweight, + type Paragraph, + type ParagraphAlign, + type ParagraphOptions, + type ParagraphVerticalAlign, type Point, type Polyline, type PolylineOptions, @@ -104,7 +109,7 @@ export { export { toDXF, type DxfOptions } from "./dxf.ts"; export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; export { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; -export { FONTS, type Font, type FontInfo } from "./fonts.ts"; +export { capHeightOf, FONTS, type Font, type FontInfo } from "./fonts.ts"; export { idHandle } from "./handles.ts"; export { inspectText, @@ -144,8 +149,37 @@ export { export { DrawingError, lint, type Diagnostic, type LintOptions, type LintRule } from "./lint.ts"; export { CENTER, DASHDOT, DASHED, DOT, HIDDEN, LINEWEIGHTS, PHANTOM } from "./linetypes.ts"; export { lineSpacing, measureText, type TextMeasure, type TextToMeasure } from "./measure.ts"; +export { + bold, + parseParagraph, + plain, + PARAGRAPH_NESTING, + stack, + subscript, + superscript, + underline, + type BoldFont, + type ParagraphPiece, + type ParsedParagraph, + type RunFormat, +} from "./paragraph-codes.ts"; +export { + attachmentPlace, + layoutParagraph, + lineSpacingStyleCode, + measureParagraph, + paragraphAttachment, + paragraphDirection, + paragraphInStyle, + type ParagraphLayout, + type ParagraphLine, + type ParagraphMeasure, + type ParagraphRun, + type ParagraphStroke, + type ParagraphToMeasure, +} from "./paragraphs.ts"; export { fromPaper, type PaperScale, type PaperUnit } from "./paper.ts"; -export { pdfFace, svgToPDF, toPDF, type PdfOptions, type PdfSheet } from "./pdf.ts"; +export { boldFontKey, pdfFace, svgToPDF, toPDF, type PdfOptions, type PdfSheet } from "./pdf.ts"; export { PAPERS, PLOT_STYLE_TABLES, @@ -189,6 +223,8 @@ export type { ObliqueAngle, PaperLength, PaperOf, + LineSpacing, + ParagraphValue, Pattern, PolylineWidth, Positive, @@ -199,7 +235,7 @@ export type { WidthFactor, XrefPath, } from "./rules.ts"; -export { XREF_DEPTH } from "./rules.ts"; +export { LINE_SPACING_RANGE, XREF_DEPTH } from "./rules.ts"; export { BUILT_IN_STANDARD, defineStandard, type BuiltInStandard } from "./standard/define.ts"; export type { Box, @@ -228,6 +264,7 @@ export type { export { checkDrawingRead } from "./read/check.ts"; export { readDXF } from "./read/dxf.ts"; export { ReadError } from "./read/groups.ts"; +export { layoutMtext, measureMtext } from "./read/mtext.ts"; export { BLOCK_ITEMS, CENSUS_LIMIT, diff --git a/src/inspect.ts b/src/inspect.ts index 5db48c3..232c822 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -28,6 +28,7 @@ import type { import { written } from "./format.ts"; import { layerKey } from "./layers.ts"; import { inStyle, measurer } from "./measure.ts"; +import { measured, paragraphInStyle, paragraphMeasurer } from "./paragraphs.ts"; import { paperInfo } from "./papers.ts"; import { shown } from "./rules.ts"; import { filled, Strings } from "./shape.ts"; @@ -188,6 +189,9 @@ export function inspectWithin( }; const walk = (cost: number): boolean => spend(cost * WALKED); const { measure, again: readAgain } = measurer(); + const paragraphs = paragraphMeasurer(); + /** The paragraphs, and the layouts of long values, whose lines a place has read. */ + const expanded = new WeakSet(); /** * Whether each value of `LONG` characters or more holds only spaces, read once. One that took * the place of another, as `Strings` keeps them, is read again and paid for by its length, @@ -314,6 +318,38 @@ export function inspectWithin( if (text.value.trim() !== "") keep(text, index, matrix, from, attribute); return; } + if (drawn.kind === "paragraph") { + // Each line of a paragraph that draws a character is a text where its layout puts it. + // Only the first place of a paragraph, of a value not laid out before, is free. Any other + // pays first: by its value's length to lay a long value out again, and by its lines to + // read them again. + const paragraph = paragraphInStyle(drawn, styleOf(drawn, from)); + const again = paragraphs.again(paragraph); + if (again > 0 && !spend(again)) return; + const layout = paragraphs.layout(paragraph); + const repeated = again > 0 || expanded.has(drawn) || expanded.has(layout); + expanded.add(drawn); + expanded.add(layout); + if (repeated && !walk(layout.lines.length)) return; + for (const line of measured(paragraph, layout).lines) { + const placed = matrix ? line.corners.map(place) : line.corners; + const inner = innerBox(placed); + if (!inner) continue; + texts.push({ + entity: index, + attribute, + id, + layer, + value: line.value, + at: placed[0]!, + corners: placed, + inner: inner.corners, + height: inner.height, + box: boxOf(placed), + }); + } + return; + } if (drawn.kind === "text") { const style = styleOf(drawn, from); const { corners } = measure(inStyle(drawn, style)); @@ -346,7 +382,7 @@ export function inspectWithin( } }; const wanted = (e: Exclude): boolean => - e.kind === "text" + e.kind === "text" || e.kind === "paragraph" ? !blank(e.value) : e.kind === "linear-dimension" || e.kind === "aligned-dimension" || @@ -360,7 +396,8 @@ export function inspectWithin( at.index = index; at.space = where; // Most entities are no insert, and are looked at without the walk an insert needs. A long - // value that took the place of another of its length is read again, and paid for. + // text that took the place of another of its length is read again, and paid for; `keep` + // pays for a paragraph's. if (entity.kind !== "insert") { const value: unknown = entity.kind === "text" ? entity.value : undefined; if (typeof value === "string" && value.length >= LONG && readAgain(value)) { @@ -385,7 +422,12 @@ export function inspectWithin( frozen, (drawn, placement) => { // A text is read for each place it is drawn, blank or not, so it is paid for first. - if (drawn.kind === "text" && !step(Math.floor(drawn.value.length / 32))) return; + if ( + (drawn.kind === "text" || drawn.kind === "paragraph") && + !step(Math.floor(drawn.value.length / 32)) + ) { + return; + } if (!wanted(drawn) || hidden(placement.layer)) return; keep(drawn, index, placement.matrix, placement.from, placement.attribute); }, @@ -548,6 +590,7 @@ function looked( const kept = (e: Exclude): boolean => { switch (e.kind) { case "text": + case "paragraph": // A value that is not a string is left for the walk to read as it did. return typeof e.value !== "string" || !blank(e.value); case "polyline": @@ -712,7 +755,9 @@ function looked( function characters(entities: readonly Entity[]): number { let steps = 0; for (const e of entities) { - if (e?.kind === "text" && typeof e.value === "string") steps += Math.floor(e.value.length / 32); + if ((e?.kind === "text" || e?.kind === "paragraph") && typeof e.value === "string") { + steps += Math.floor(e.value.length / 32); + } } return steps; } diff --git a/src/lint.ts b/src/lint.ts index 8498963..2ff9974 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -75,7 +75,8 @@ import { type Check, } from "./shape.ts"; import { layerAuditKey, layerKey, layoutNameKey } from "./layers.ts"; -import { STANDARD_TEXT_STYLE } from "./fonts.ts"; +import { STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; +import { parseParagraph, type ParsedParagraph } from "./paragraph-codes.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; import { arcIsWrittenAsPoint, @@ -132,6 +133,10 @@ import { sizeProblem, textAlignProblem, textProblem, + lineSpacingProblem, + paragraphChoiceProblem, + paragraphProblemIn, + paragraphValueProblem, textStyleNameProblem, textStyleProblem, textWarning, @@ -196,6 +201,7 @@ export type LintRule = | "duplicate-leader-style" | "undefined-leader-style" | "leader" + | "paragraph" | "zero-length" | "standard" | "layer-outside-standard" @@ -433,6 +439,17 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (!found) textChecks.set(value, (found = [textProblem(value), textWarning(value)])); return found; }; + /** What is wrong with a paragraph's value in its style's font, read once for a long one. */ + const paragraphChecks = new Strings>(); + const checkParagraph = (value: string, font: unknown): string | undefined => { + if (value.length < LONG) return paragraphValueProblem(value, font); + let found = paragraphChecks.get(value); + if (!found) { + const { problem, ownDiameter } = parseParagraph(value); + paragraphChecks.set(value, (found = { problem, ownDiameter })); + } + return paragraphProblemIn(found, font); + }; /** The strings of `LONG` characters or more the checks have read. */ const long = new Strings(); /** @@ -466,6 +483,14 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) case "text": cost += long1(e.value) + long1(e.style) + long1(e.align) + long1(e.valign); break; + case "paragraph": + cost += + long1(e.value) + + long1(e.style) + + long1(e.align) + + long1(e.valign) + + long1(e.lineSpacingStyle); + break; case "insert": cost += long1(e.block); break; @@ -1615,6 +1640,37 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) for (const [rule, found] of textProblems(entity)) add(rule, "error", found); if (warning) add("text", "warning", warning); } + if (entity.kind === "paragraph") { + if (r12) { + add("paragraph", "error", R12_ONLY.paragraphs); + return; + } + // A value is checked in its style's font, which decides what `%%c` draws. A style that is + // not found has an error of its own. + const style: unknown = entity.style; + const font = + style === undefined + ? STANDARD_FONT + : typeof style === "string" + ? (stylesByKey.get(layerKey(style))?.font ?? + (isStandardTextStyle(style) ? STANDARD_FONT : undefined)) + : undefined; + const problem = checkParagraph(entity.value, font); + if (problem) add("paragraph", "error", problem); + const { align, valign, lineSpacing, lineSpacingStyle } = entity; + for (const [rule, field, value] of [ + ["text-align", "align", align], + ["text-align", "valign", valign], + ["paragraph", "lineSpacingStyle", lineSpacingStyle], + ] as const) { + const choice = value === undefined ? undefined : paragraphChoiceProblem(field, value); + if (choice) add(rule, "error", choice); + } + const spacing = lineSpacing === undefined ? undefined : lineSpacingProblem(lineSpacing); + if (spacing) add("paragraph", "error", spacing); + const styled = entity.style === undefined ? {} : { style: entity.style }; + for (const [rule, found] of textProblems(styled)) add(rule, "error", found); + } // A shape with a geometry error has no length worth a second message. const collapsed = problems.length === 0 ? zeroLength(entity) : undefined; if (collapsed) add("zero-length", "warning", collapsed); @@ -2051,6 +2107,8 @@ function asText(definition: AttributeDefinition): Text { function costsBoxes(e: Readonly>): boolean { const kind = e.kind; if (kind === "text") return typeof e.value === "string" && e.value.length > KEYED; + // A paragraph's layout reads its value again for each place, as a long text's measure does. + if (kind === "paragraph") return typeof e.value === "string" && e.value.length >= LONG; if (kind === "polyline") { return Array.isArray(e.bulges) || Array.isArray(e.widths) || typeof e.width === "number"; } @@ -2118,6 +2176,11 @@ function geometryProblems(e: Entity): string[] { finite("its position and rotation", ...e.at, e.rotation); size("height", e.height); break; + case "paragraph": + finite("its position and rotation", ...e.at, e.rotation); + size("height", e.height); + if (e.width !== undefined) size("width", e.width); + break; case "insert": { finite("its position and rotation", ...e.at, e.rotation ?? 0); const scale: unknown = e.scale; @@ -2164,6 +2227,7 @@ function zeroLength(e: Entity): string | undefined { : undefined; case "circle": case "text": + case "paragraph": case "insert": case "linear-dimension": case "aligned-dimension": diff --git a/src/measure.ts b/src/measure.ts index b3398cd..849e953 100644 --- a/src/measure.ts +++ b/src/measure.ts @@ -4,6 +4,7 @@ import type { Point, TextAlign, TextVerticalAlign } from "./drawing.ts"; import { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; import { fontInfo, STANDARD_FONT } from "./fonts.ts"; +import { written } from "./format.ts"; import { Strings } from "./shape.ts"; /** A text to measure. A `Text` and its `TextStyle` spread into one object are one. */ @@ -61,7 +62,7 @@ export function drawnValue(value: string): string { } /** Where a character's numbers are in a font's tables, or -1 for one they do not hold. */ -function tableIndex(code: number): number { +export function tableIndex(code: number): number { let before = 0; for (const [first, last] of FONT_METRICS_RANGES) { if (code >= first && code <= last) return before + code - first; @@ -70,7 +71,21 @@ function tableIndex(code: number): number { return -1; } -const UNKNOWN = tableIndex("?".charCodeAt(0)); +/** Where the numbers of "?" are, which stand for a character the tables do not hold. */ +export const UNKNOWN = tableIndex("?".charCodeAt(0)); + +/** + * The numbers of a font, and whether they are its own: a font that is not one of `FONTS` is + * measured in `txt.shx`. + */ +export function fontMetrics(font: string | undefined): { + readonly metrics: FontMetrics; + readonly known: boolean; +} { + const name = font ?? STANDARD_FONT; + const known = fontInfo(name) !== undefined && Object.hasOwn(FONT_METRICS, name); + return { metrics: known ? FONT_METRICS[name]! : FONT_METRICS[STANDARD_FONT]!, known }; +} /** A text before it is turned and moved to its point: X along its baseline, Y up it. */ export interface TextLayout { @@ -82,6 +97,11 @@ export interface TextLayout { * the last one adds or takes off. Its first point is `end - advance` along it from its point. */ readonly advance: number; + /** + * How far its characters' advances alone take it from its first point: what a TrueType font's + * glyphs span as the leading CAD app plots them. + */ + readonly advances: number; /** How far the baseline is above the point. */ readonly baseline: number; /** How far along the text the top of a capital lies from its foot. */ @@ -96,6 +116,8 @@ interface Read { readonly head: number | undefined; /** The advances of the characters and what the last one adds, at height 1. */ readonly width: number; + /** The advances of the characters alone, at height 1. */ + readonly advances: number; /** True when it holds `%%` or a character the font's numbers do not cover. */ readonly odd: boolean; /** True when it starts or ends with a space as it is drawn. */ @@ -119,7 +141,13 @@ function read(value: string, metrics: FontMetrics): Read { width += metrics.advances[index]!; tail = metrics.tails[index]!; } - return { head, width: width + tail, odd, spaced: /^[ \u00a0]|[ \u00a0]$/.test(drawn) }; + return { + head, + width: width + tail, + advances: width, + odd, + spaced: /^[ \u00a0]|[ \u00a0]$/.test(drawn), + }; } /** @@ -137,14 +165,11 @@ function layOut( text: TextToMeasure, reading: (value: string, metrics: FontMetrics) => Read, ): TextLayout { - const font = text.font ?? STANDARD_FONT; - const known: FontMetrics | undefined = - fontInfo(font) && Object.hasOwn(FONT_METRICS, font) ? FONT_METRICS[font] : undefined; - const metrics = known ?? FONT_METRICS[STANDARD_FONT]!; - const { head, width, odd, spaced } = reading(text.value, metrics); + const { metrics, known } = fontMetrics(text.font); + const { head, width, advances, odd, spaced } = reading(text.value, metrics); // A centered or right-justified text placed by a space at either end may plot elsewhere. const approximate = - known === undefined || odd || ((text.align === "center" || text.align === "right") && spaced); + !known || odd || ((text.align === "center" || text.align === "right") && spaced); const along = text.height * (text.widthFactor ?? 1); const [from, to] = [(head ?? 0) * along, width * along]; // The text's first point, which its first character is drawn from. @@ -155,6 +180,7 @@ function layOut( start: first + from, end: first + to, advance: to, + advances: advances * along, baseline: text.valign === "top" ? -text.height @@ -265,7 +291,10 @@ export function measureText(text: TextToMeasure): TextMeasure { /** A text's measure from its layout. */ function placed(text: TextToMeasure, layout: TextLayout): TextMeasure { const { start, end, baseline, lean, descent, approximate } = layout; - const turn = ((text.rotation ?? 0) * Math.PI) / 180; + // Turned by its rotation as the writers write it, group 50 with 6 decimals, which leave a whole + // number as it is. + const rotation = text.rotation ?? 0; + const turn = ((Number.isInteger(rotation) ? rotation : written(rotation)) * Math.PI) / 180; const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; const [x, y] = text.at ?? [0, 0]; const place = (along: number, up: number): Point => [ diff --git a/src/paragraph-codes.ts b/src/paragraph-codes.ts new file mode 100644 index 0000000..a83e9a4 --- /dev/null +++ b/src/paragraph-codes.ts @@ -0,0 +1,543 @@ +// The inline codes of a paragraph's value, as the DXF Reference gives them for MTEXT: what each +// one draws, read in one pass, and what tsdraft refuses to write. The layout and the writers read +// a value through `parseParagraph`. +import { fontInfo, FONTS, type Font } from "./fonts.ts"; + +/** How deep a paragraph's braces may nest. */ +export const PARAGRAPH_NESTING = 16; + +/** The longest name a message quotes whole. */ +const QUOTED = 64; + +export const PARAGRAPH_CONTROL = + "A paragraph's value holds no control characters. paragraph() takes a line feed as a paragraph break and holds it as \\P, and tabs are not laid out yet"; +export const PARAGRAPH_ASTRAL = + "A paragraph cannot hold emoji or other characters above U+FFFF, because the leading CAD app cannot read them from DXF"; +export const PARAGRAPH_PRIVATE_USE = + "A paragraph cannot hold the private-use characters U+E800 to U+E8FF, because the leading CAD app replaces them when it reads DXF"; +export const PARAGRAPH_NEVER_CLOSED = + "A { in the paragraph is never closed by a }. Write \\{ for a brace"; +export const PARAGRAPH_NEVER_OPENED = "A } in the paragraph closes no {. Write \\} for a brace"; +export const PARAGRAPH_TOO_DEEP = `The paragraph's braces nest more than ${PARAGRAPH_NESTING} deep`; +export const PARAGRAPH_TRAILING = + "The paragraph ends with a \\, which starts a code. Write \\\\ for a backslash"; +export const PARAGRAPH_STACK_SEPARATOR = + "The paragraph code \\S stacks two parts, and needs a /, # or ^ between them"; +export const PARAGRAPH_STACK_LINED = + "A stack in underlined or struck-through characters is not laid out yet, so tsdraft refuses it"; +export const PARAGRAPH_SHX_DIAMETER = + "A paragraph's %%c in an SHX font draws a diameter sign of its own, narrower than Ø, which is not laid out yet, so tsdraft refuses it. Set it in a TrueType font, or write Ø"; +export const PARAGRAPH_STACK_PART = + "A stacked part of a paragraph holds digits or capitals, with . , + or - beside them, or only spaces, or nothing: where the tops of other characters stack is not laid out yet, so tsdraft refuses it"; + +/** What each code a paragraph may hold but tsdraft does not lay out yet does. */ +export const PARAGRAPH_NOT_LAID_OUT = { + p: "sets the indents, tab stops and alignment of a paragraph", + H: "sets the height of the characters after it", + W: "sets the width factor of the characters after it", + Q: "sets the oblique angle of the characters after it", + T: "sets the spacing of the characters after it", + A: "sets where the characters after it sit up and down the line", + C: "sets the color of the characters after it", + c: "sets the true color of the characters after it", + N: "starts a new column", + X: "starts the part of a dimension's text below its line", + M: "holds a character of a code page", + m: "holds a character of a code page", + O: "draws a line over the characters after it", +} as const; + +export type NotLaidOutCode = keyof typeof PARAGRAPH_NOT_LAID_OUT; + +export function paragraphNotLaidOut( + code: C, +): `The paragraph code \\${C}, which ${(typeof PARAGRAPH_NOT_LAID_OUT)[C]}, is not laid out yet, so tsdraft refuses it` { + return `The paragraph code \\${code}, which ${PARAGRAPH_NOT_LAID_OUT[code]}, is not laid out yet, so tsdraft refuses it`; +} + +export function paragraphUnknownCode( + code: C, +): `The paragraph code \\${C} is not one tsdraft knows. Write \\\\ for a backslash` { + return `The paragraph code \\${code} is not one tsdraft knows. Write \\\\ for a backslash`; +} + +export function paragraphNoSemicolon( + code: C, +): `The paragraph code \\${C} has no ; to end it` { + return `The paragraph code \\${code} has no ; to end it`; +} + +export function paragraphUnknownFont( + code: C, + name: N, +): `The paragraph code \\${C} names the font "${N}", which is not one of FONTS` { + return `The paragraph code \\${code} names the font "${quoted(name) as N}", which is not one of FONTS`; +} + +export function paragraphItalic( + code: C, +): `The paragraph code \\${C} sets italic, and tsdraft has no widths for italic letters` { + return `The paragraph code \\${code} sets italic, and tsdraft has no widths for italic letters`; +} + +export function paragraphShxBold( + code: C, + name: N, +): `The paragraph code \\${C} sets bold in "${N}", an SHX font, which has no bold` { + return `The paragraph code \\${code} sets bold in "${quoted(name) as N}", an SHX font, which has no bold`; +} + +export function paragraphFontOption( + code: C, + option: O, +): `The paragraph code \\${C} has the option "${O}", which tsdraft does not know: a font takes b0 or b1 for bold, i0, and c and p with a number` { + return `The paragraph code \\${code} has the option "${quoted(option) as O}", which tsdraft does not know: a font takes b0 or b1 for bold, i0, and c and p with a number`; +} + +export function paragraphFontOptionTwice( + code: C, + letter: L, +): `The paragraph code \\${C} gives its option ${L} twice. Give each of b, i, c and p once` { + return `The paragraph code \\${code} gives its option ${letter} twice. Give each of b, i, c and p once`; +} + +/** A name for a message: the first `QUOTED` characters of a long one. */ +function quoted(name: string): string { + return name.length > QUOTED ? `${name.slice(0, QUOTED)}...` : name; +} + +/** The format of a run of a paragraph's characters, which its codes set. */ +export interface RunFormat { + readonly underline: boolean; + readonly overline: boolean; + readonly strikeThrough: boolean; + readonly bold: boolean; + /** The font of `FONTS` a `\f` or `\F` code set, or undefined for the paragraph's own. */ + readonly font: Font | undefined; +} + +/** A piece of a paragraph, in the order it is drawn. */ +export type ParagraphPiece = + /** + * Characters drawn in one format, with no break among them. `diameter` is true when they hold + * a diameter sign written `%%c`, which an SHX font draws as a sign of its own. + */ + | { + readonly kind: "characters"; + readonly value: string; + readonly format: RunFormat; + readonly diameter: boolean; + } + /** Two parts stacked, as a fraction, a superscript or a subscript. */ + | { + readonly kind: "stack"; + readonly top: string; + readonly bottom: string; + /** `/` stacks the parts over a bar, `#` beside a slash, and `^` with no bar. */ + readonly separator: "/" | "#" | "^"; + readonly format: RunFormat; + } + /** A paragraph break, `\P`. */ + | { readonly kind: "break" }; + +export interface ParsedParagraph { + readonly pieces: readonly ParagraphPiece[]; + /** + * The first code or character of the value that tsdraft refuses to write, or undefined. The + * pieces are still read past it: a code it does not lay out draws nothing, and `\N` and `\X` + * break the line. + */ + readonly problem: string | undefined; + /** + * True when it holds a `%%c` in the paragraph's own font, which `paragraphValueProblem` refuses + * when that font is an SHX font. One in an SHX font a `\f` code set is a `problem`. + */ + readonly ownDiameter: boolean; +} + +const PLAIN: RunFormat = { + underline: false, + overline: false, + strikeThrough: false, + bold: false, + font: undefined, +}; + +/** + * What `%%` and the letter after it draw. A paragraph has no other: `%%` before any other + * character is drawn as it is, and so is `%%%`. + */ +const PERCENT_CODES: Readonly> = { + d: "°", + D: "°", + p: "±", + P: "±", + c: "Ø", + C: "Ø", +}; + +/** The codes that switch a line on or off: `\L` underline, `\O` overline, `\K` strike-through. */ +const TOGGLES: Readonly> = { + L: ["underline", true], + l: ["underline", false], + O: ["overline", true], + o: ["overline", false], + K: ["strikeThrough", true], + k: ["strikeThrough", false], +}; + +/** The codes tsdraft does not lay out that end with a `;`. */ +const ENDED = new Set(["p", "H", "W", "Q", "T", "A", "C", "c"]); + +function isHex(code: number): boolean { + return (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102); +} + +/** The value of four hex digits at `at`, or -1 when they are not four hex digits. */ +function hexAt(value: string, at: number): number { + if (at + 4 > value.length) return -1; + for (let k = at; k < at + 4; k++) if (!isHex(value.charCodeAt(k))) return -1; + return parseInt(value.slice(at, at + 4), 16); +} + +/** What is wrong with a character a paragraph holds, or undefined. */ +function characterProblem(code: number): string | undefined { + if (code < 0x20 || code === 0x7f) return PARAGRAPH_CONTROL; + if (code >= 0xd800 && code <= 0xdfff) return PARAGRAPH_ASTRAL; + if (code >= 0xe800 && code <= 0xe8ff) return PARAGRAPH_PRIVATE_USE; + return undefined; +} + +function sameFormat(a: RunFormat, b: RunFormat): boolean { + return ( + a.underline === b.underline && + a.overline === b.overline && + a.strikeThrough === b.strikeThrough && + a.bold === b.bold && + a.font === b.font + ); +} + +/** + * Reads a paragraph's value in one pass, in time and memory in proportion to its length, with a + * stack of its own for its braces that holds at most `PARAGRAPH_NESTING` formats: a brace past + * that is counted and changes nothing. It never throws, and reads any string: what it refuses + * is `problem`, the first it met. + */ +export function parseParagraph(value: string): ParsedParagraph { + const pieces: ParagraphPiece[] = []; + let problem: string | undefined; + const fail = (message: string): void => { + problem ??= message; + }; + const saved: RunFormat[] = []; + let deeper = 0; + let format = PLAIN; + let run = ""; + let diameter = false; + let ownDiameter = false; + const flush = (): void => { + if (diameter) { + if (format.font === undefined) ownDiameter = true; + else if (FONTS[format.font].file.endsWith(".shx")) fail(PARAGRAPH_SHX_DIAMETER); + } + if (run.length > 0) pieces.push({ kind: "characters", value: run, format, diameter }); + run = ""; + diameter = false; + }; + const set = (next: RunFormat): void => { + if (sameFormat(next, format)) return; + flush(); + format = next; + }; + const n = value.length; + let i = 0; + while (i < n) { + const c = value.charCodeAt(i); + const character = value[i]!; + if (character === "\\") { + i = code(i + 1); + continue; + } + if (character === "{") { + if (saved.length < PARAGRAPH_NESTING) saved.push(format); + else { + deeper++; + fail(PARAGRAPH_TOO_DEEP); + } + i++; + continue; + } + if (character === "}") { + if (deeper > 0) deeper--; + else if (saved.length > 0) set(saved.pop()!); + else fail(PARAGRAPH_NEVER_OPENED); + i++; + continue; + } + if (character === "%" && value[i + 1] === "%") { + const drawn = PERCENT_CODES[value[i + 2] ?? ""]; + if (drawn !== undefined) { + run += drawn; + if (drawn === "Ø") diameter = true; + i += 3; + continue; + } + } + const wrong = characterProblem(c); + if (wrong) fail(wrong); + // A pair of surrogates is one character above U+FFFF. + const pair = + c >= 0xd800 && + c <= 0xdbff && + value.charCodeAt(i + 1) >= 0xdc00 && + value.charCodeAt(i + 1) <= 0xdfff; + // A control character draws nothing. + if (!(c < 0x20 || c === 0x7f)) run += pair ? value.slice(i, i + 2) : character; + i += pair ? 2 : 1; + } + flush(); + if (saved.length > 0 || deeper > 0) fail(PARAGRAPH_NEVER_CLOSED); + return { pieces, problem, ownDiameter }; + + /** Reads the code after a backslash at `at`, and gives where the value goes on after it. */ + function code(at: number): number { + if (at >= n) { + fail(PARAGRAPH_TRAILING); + return n; + } + const letter = value[at]!; + switch (letter) { + case "P": + flush(); + pieces.push({ kind: "break" }); + return at + 1; + case "~": + run += "\u00a0"; + return at + 1; + case "\\": + case "{": + case "}": + run += letter; + return at + 1; + case "N": + case "X": + fail(paragraphNotLaidOut(letter)); + flush(); + pieces.push({ kind: "break" }); + return at + 1; + case "f": + case "F": + return font(letter, at + 1); + case "S": + return stack(at + 1); + case "U": + case "u": { + const unicode = value[at + 1] === "+" ? hexAt(value, at + 2) : -1; + if (unicode < 0) break; + const wrong = characterProblem(unicode); + if (wrong) fail(wrong); + else run += String.fromCharCode(unicode); + return at + 6; + } + case "M": + case "m": { + const digit = value.charCodeAt(at + 2); + if (value[at + 1] !== "+" || digit < 49 || digit > 53 || hexAt(value, at + 3) < 0) break; + fail(paragraphNotLaidOut(letter)); + return at + 7; + } + } + const toggle = TOGGLES[letter]; + if (toggle) { + if (letter === "O") fail(paragraphNotLaidOut(letter)); + set({ ...format, [toggle[0]]: toggle[1] }); + return at + 1; + } + if (ENDED.has(letter)) { + const end = value.indexOf(";", at + 1); + if (end < 0) { + fail(paragraphNoSemicolon(letter)); + return n; + } + fail(paragraphNotLaidOut(letter as NotLaidOutCode)); + return end + 1; + } + fail(paragraphUnknownCode(letter)); + return at + 1; + } + + /** Reads a `\f` or `\F` code from after its letter, up to its `;`. */ + function font(letter: "f" | "F", at: number): number { + const end = value.indexOf(";", at); + if (end < 0) { + fail(paragraphNoSemicolon(letter)); + return n; + } + const parts = value.slice(at, end).split("|"); + const name = parts[0]!; + const known = fontInfo(name) ? (name as Font) : undefined; + if (!known) fail(paragraphUnknownFont(letter, name)); + let bold = false; + /** The letters of the options given so far, a bit each. */ + let given = 0; + for (let k = 1; k < parts.length; k++) { + const option = parts[k]!; + if (option === "b1") { + bold = true; + if (known && FONTS[known].file.endsWith(".shx")) fail(paragraphShxBold(letter, name)); + } else if (option === "i1") fail(paragraphItalic(letter)); + else if (option !== "b0" && option !== "i0" && !isNumbered(option)) { + fail(paragraphFontOption(letter, option)); + continue; + } + const bit = OPTION_BITS[option[0] as "b" | "i" | "c" | "p"]; + if (given & bit) fail(paragraphFontOptionTwice(letter, option[0]!)); + given |= bit; + } + set({ ...format, font: known ?? format.font, bold }); + return end + 1; + } + + /** + * Reads a `\S` code from after its letter, up to its first `;` that no backslash escapes. A + * backslash takes the character after it as it is, and the first `/`, `#` or `^` no backslash + * escapes divides the two parts. + */ + function stack(at: number): number { + let top = ""; + let bottom = ""; + let separator: "/" | "#" | "^" | undefined; + let k = at; + while (k < n) { + const character = value[k]!; + if (character === ";") break; + let taken = character; + if (character === "\\" && k + 1 < n) { + taken = value[k + 1]!; + k += 2; + } else if ( + separator === undefined && + (character === "/" || character === "#" || character === "^") + ) { + separator = character; + k++; + continue; + } else if (character === "%" && value[k + 1] === "%" && PERCENT_CODES[value[k + 2] ?? ""]) { + taken = PERCENT_CODES[value[k + 2]!]!; + k += 3; + } else k++; + const wrong = characterProblem(taken.charCodeAt(0)); + if (wrong) fail(wrong); + if (separator === undefined) top += taken; + else bottom += taken; + } + if (k >= n) { + fail(paragraphNoSemicolon("S")); + return n; + } + if (separator === undefined) { + fail(PARAGRAPH_STACK_SEPARATOR); + run += top; + return k + 1; + } + if (format.underline || format.strikeThrough) fail(PARAGRAPH_STACK_LINED); + else if (!stackable(top) || !stackable(bottom)) fail(PARAGRAPH_STACK_PART); + flush(); + pieces.push({ kind: "stack", top, bottom, separator, format }); + return k + 1; + } +} + +/** + * True for a part of a stack whose ink's top and bottom the font tables hold: digits or capitals, + * which reach a capital's height and stand on the baseline, with `.`, `,`, `+` or `-` beside + * them, which reach no higher; or only spaces; or nothing. + */ +function stackable(part: string): boolean { + let spaces = 0; + let tall = false; + for (let k = 0; k < part.length; k++) { + const code = part.charCodeAt(k); + if (code === 32) spaces++; + else if ((code >= 48 && code <= 57) || (code >= 65 && code <= 90)) tall = true; + else if (code !== 46 && code !== 44 && code !== 43 && code !== 45) return false; + } + return spaces === part.length || (tall && spaces === 0); +} + +/** A bit for each letter a font code's option starts with. */ +const OPTION_BITS = { b: 1, i: 2, c: 4, p: 8 } as const; + +/** + * True for a font option of a letter `c` or `p` and one or more digits, which tsdraft passes by. + * `ParagraphFontOption` in `src/rules.ts` is the same grammar. + */ +function isNumbered(option: string): boolean { + if (option.length < 2 || (option[0] !== "c" && option[0] !== "p")) return false; + for (let k = 1; k < option.length; k++) { + const digit = option.charCodeAt(k); + if (digit < 48 || digit > 57) return false; + } + return true; +} + +/** + * Text for a paragraph that draws as it is written: a backslash and a brace escaped, and the + * second percent sign of a `%%d`, `%%p` or `%%c` written as `\U+0025`, so it starts no code. A + * line feed stays a paragraph break. + * + * ```ts + * d.paragraph(`${plain(owner)} SHALL VERIFY`, { at: [0, 0] }); + * ``` + */ +export function plain(text: string): string { + const escaped = text.replace(/[\\{}]/g, (character) => `\\${character}`); + return escaped.replace(/%%(?=[dDpPcC])/g, "%\\U+0025"); +} + +/** Text underlined. */ +export function underline(text: string): string { + return `{\\L${text}}`; +} + +/** The fonts of `FONTS` that have a bold face: the TrueType fonts. */ +export type BoldFont = { + [K in Font]: (typeof FONTS)[K] extends { readonly pitchAndFamily: number } ? K : never; +}[Font]; + +/** + * Text in the bold face of a TrueType font of `FONTS`, which it is then set in, and measured by + * the bold face's own widths. + */ +export function bold(text: string, font: BoldFont): string { + return `{\\f${font}|b1;${text}}`; +} + +/** Escapes what would end a part of a stack early. */ +function part(text: string): string { + return text.replace(/[\\;/#^]/g, (character) => `\\${character}`); +} + +/** + * Two parts stacked: over a level bar for `"/"`, the default, beside a slash for `"#"`, and with + * no bar for `"^"`, as a tolerance is written. Each part holds digits or capitals, with `.`, `,`, + * `+` or `-` beside them. + * + * ```ts + * d.paragraph(`3${stack("1", "2")}" GAP`, { at: [0, 0] }); + * ``` + */ +export function stack(top: string, bottom: string, separator: "/" | "#" | "^" = "/"): string { + return `\\S${part(top)}${separator}${part(bottom)};`; +} + +/** Text set above the line, as an exponent is: `\S2^ ;`. It holds digits or capitals. */ +export function superscript(text: string): string { + return `\\S${part(text)}^ ;`; +} + +/** Text set at the foot of the line, under room for a top part, as an index is: `\S^2;`. */ +export function subscript(text: string): string { + return `\\S^${part(text)};`; +} diff --git a/src/paragraphs.ts b/src/paragraphs.ts new file mode 100644 index 0000000..9d1bedb --- /dev/null +++ b/src/paragraphs.ts @@ -0,0 +1,1169 @@ +// Where the leading CAD app sets the lines and the runs of a paragraph, and the box it fills. This +// is the one layout of a paragraph: the extents, `toSVG`, `inspectText`, the writers and the +// reader all take a paragraph's lines and its box from here. +import type { LineSpacingStyle, ParagraphAlign, ParagraphVerticalAlign, Point } from "./drawing.ts"; +import { FONT_METRICS, type FontMetrics } from "./font-metrics.ts"; +import { capHeightOf, fontInfo, STANDARD_FONT } from "./fonts.ts"; +import { fontMetrics, tableIndex, UNKNOWN } from "./measure.ts"; +import { parseParagraph, type ParsedParagraph, type RunFormat } from "./paragraph-codes.ts"; +import { LINE_SPACING_RANGE } from "./rules.ts"; +import { fifteenDigits, written } from "./format.ts"; +import { Strings } from "./shape.ts"; + +// The rules of a paragraph's layout, every one of them, in heights h of the paragraph, read from +// the columns of `src/font-metrics.ts`: +// - A run is characters of one font, face and format. Its characters are set by their advances. +// The next run starts where the last one's advances end, or where its last character's ink +// ends, `rights`, where that is further. +// - A line starts at the left of its first character's ink, `lefts`, and ends at the right of its +// last character's ink, `rights`. It keeps the spaces it starts with, and drops those it ends +// with and those where it wraps. Left alignment puts its start on the point, right its end, and +// center the middle of the two: the width moves no line. +// - A line breaks only at an ASCII space, and only to keep the next word inside the width: the +// word stays when the line's advances up to its first character, from the line's first point, +// plus its ink, from the left of its first character's ink to the right of its last one's, come +// to no more than the width and `SLACK`. In a word that holds a stack, the characters after its +// last stack stand for it, or the stack where it ends the word. A line's first word stays, wider +// than the width or not. +// - At-least spacing gives each line a slot of the factor times A + D + h/3 from its top, and the +// next line its top where the slot ends. A is the most its characters' `tops` or its stacks +// reach above its baseline, and at least h; D is h/3, or 0 where a stack reaches highest. Its +// first line's top is the top of the box, and the box ends below the last baseline by the most +// its last line's characters reach below it, `bottoms`. +// - Exact spacing sets the first baseline h below the top of the box, each next one 5h/3 times +// the factor below it, and the bottom of the box h/3 below the last. +// - The style's width factor scales everything along a line. Its oblique angle moves where a line +// starts by its first character's bottom times the angle's tangent, and where it ends by its A +// times it. It is measured for a TrueType font, and an estimate for an SHX font. +// - An underline runs along a run from its first point to where its advances end, `UNDERLINE_SHX` +// below the baseline in an SHX font and the font's descent, `below`, in a TrueType font; a +// strike-through `STRIKE_THROUGH` above it. An overline, refused, is drawn `OVERLINE` above it. +// - A bold run is in its font's bold face, whose numbers are its own. +// - A stack's top part has its ink's top at the stack's top and its baseline `STACK_GAP` above a +// bar, and the bottom part its ink `STACK_GAP` below the bar and its baseline on the line's. The +// bar is as long as the wider part's ink, from the end of the advances before the stack, and each +// part is centered on it by its ink. `^` sets both parts' ink from that start, with no bar. `#` +// sets the top part's baseline a digit's top above the line's, the top part's ink +// from the start and the bottom part's `SLASH_GAP` after it, and a slash `SLASH_LENGTH` long at +// `SLASH_ANGLE` between the two at the bottom part's top. A part of spaces is as wide as they +// are and reaches neither up nor down, and an empty part has no ink. The next character's first +// point is `afterStack` past the stack's ink. A part's ink is measured from the left of its +// first character's ink as `lefts` holds it, never before its first point. +// - `%%c` in an SHX font is a sign of its own, measured as `Ø`, and an estimate, which `lint` +// refuses. So is a stack in +// a TrueType font but those of `STACKS_MEASURED`, and one whose part of spaces is the wider. +// - A line that ends in a stack and drops the spaces after it is placed by its first point and not +// by the left of its first character's ink, at any attachment. +/** How far past the width a word may reach and stay: the tables' rounding, and no more. */ +const SLACK = 1e-9; +const UNDERLINE_SHX = 0.2; +const STRIKE_THROUGH = 0.5; +const OVERLINE = 1.2; +/** The room a stack leaves between its bar and each part. */ +const STACK_GAP = 1 / 6; +const SLASH_GAP = 1 / 3; +const SLASH_LENGTH = 2; +const SLASH_ANGLE = 55; +/** + * The TrueType fonts whose stacks are measured. In another, a digit or a capital may stand lower + * than its capital A, which the tables do not hold. + */ +const STACKS_MEASURED: ReadonlySet = new Set(["Arial"]); +/** D, and what a slot of at-least spacing holds beyond A and D. */ +const AT_LEAST_BELOW = 1 / 3; +const EXACT_PITCH = 5 / 3; +const EXACT_BELOW = 1 / 3; + +/** A paragraph to lay out. A `Paragraph` and its `TextStyle` spread into one object are one. */ +export interface ParagraphToMeasure { + /** The value, with its codes. */ + readonly value: string; + /** The height of a capital. */ + readonly height: number; + /** The width its lines wrap at. Missing, or 0 or less, breaks lines only at `\P`. */ + readonly width?: number; + /** One of `FONTS`. Defaults to `txt.shx`. */ + readonly font?: string; + /** Defaults to 1. */ + readonly widthFactor?: number; + /** Degrees to the right. Defaults to 0. */ + readonly obliqueAngle?: number; + /** The point of the box `align` and `valign` name. Defaults to `[0, 0]`. */ + readonly at?: Point; + /** Degrees counterclockwise. Defaults to 0. */ + readonly rotation?: number; + /** Defaults to `"left"`. */ + readonly align?: ParagraphAlign; + /** Defaults to `"top"`. */ + readonly valign?: ParagraphVerticalAlign; + /** A factor of the spacing of a text's lines, from 0.25 to 4. Defaults to 1. */ + readonly lineSpacing?: number; + /** Defaults to `"at-least"`. */ + readonly lineSpacingStyle?: LineSpacingStyle; +} + +/** A run of characters a paragraph draws in one font and one format, as a text is drawn. */ +export interface ParagraphRun { + /** The characters it draws. */ + readonly value: string; + /** Its first point, along the line from `at`, where its first character is placed. */ + readonly x: number; + /** Its baseline, up from `at`. */ + readonly baseline: number; + /** The height of its capitals. */ + readonly height: number; + /** The font it is drawn in: the style's, or one a `\f` or `\F` code set. */ + readonly font: string; + /** True for a run in its font's bold face. */ + readonly bold: boolean; + /** How far its characters' advances take it along the line from its first point. */ + readonly advance: number; + /** Where it starts and ends to draw along the line from `at`, as `layoutText` gives a text. */ + readonly start: number; + readonly end: number; +} + +/** A line a paragraph draws that is no letter: an underline, an overline, a strike-through or a stack's bar or slash. */ +export interface ParagraphStroke { + readonly kind: "underline" | "overline" | "strike-through" | "bar"; + /** From `at`, along the line and up it. */ + readonly from: Point; + readonly to: Point; +} + +/** One line of a paragraph. */ +export interface ParagraphLine { + /** What it draws: its characters in order, and each stack as its parts either side of its divider. */ + readonly value: string; + readonly runs: readonly ParagraphRun[]; + /** Its baseline, up from `at`. */ + readonly baseline: number; + /** + * Where its ink starts and ends along the line from `at`, upright: from the left of its first + * character's ink to the right of its last one's. Both 0 for a line with nothing. + */ + readonly start: number; + readonly end: number; + /** How far above its baseline it reaches: its A, which sets where it sits under at-least spacing. */ + readonly top: number; +} + +/** A paragraph before it is turned and moved to its point: X along its lines, Y up them, from `at`. */ +export interface ParagraphLayout { + readonly lines: readonly ParagraphLine[]; + readonly strokes: readonly ParagraphStroke[]; + /** + * The box `align` and `valign` place it by, `[left, bottom, right, top]`: from the first line's + * top to the bottom of the last line's ink, or to where exact spacing ends it, and as wide as + * the width from the point `align` names, or as the widest line without one. + */ + readonly frame: readonly [number, number, number, number]; + /** + * The box of all it draws, its letters with what they reach below the baseline and their lean, + * and its strokes: `[left, bottom, right, top]`. Undefined when it draws nothing. + */ + readonly ink: readonly [number, number, number, number] | undefined; + /** How far along a letter its lean takes its top, for each height of it. */ + readonly lean: number; + readonly widthFactor: number; + readonly obliqueAngle: number; + /** + * True for an estimate: the value holds a code tsdraft does not lay out or a character its + * tables do not hold, a font is not one of `FONTS`, an SHX font is slanted or draws `%%c`. + */ + readonly approximate: boolean; + /** The first code or character of the value that tsdraft refuses to write, or undefined. */ + readonly problem: string | undefined; +} + +/** A paragraph where it plots, as `measureParagraph` gives it. */ +export interface ParagraphMeasure { + /** + * The box of all it draws, turned as it is: its lower left, lower right, upper right and upper + * left corners. Undefined when it draws nothing. + */ + readonly corners: readonly [Point, Point, Point, Point] | undefined; + /** The box `align` and `valign` place it by, turned, in the same order. */ + readonly frame: readonly [Point, Point, Point, Point]; + /** + * Each line that draws a character, as `measureText` gives a text: the start and the end of + * its baseline, then the end and the start of the line along its top, leaned as it is. + */ + readonly lines: readonly { + readonly value: string; + readonly corners: readonly [Point, Point, Point, Point]; + }[]; + readonly approximate: boolean; +} + +/** The numbers of a face of a font, at height 1 and width factor 1. */ +interface Face { + readonly font: string; + readonly bold: boolean; + readonly shx: boolean; + readonly advances: readonly number[]; + readonly lefts: readonly number[]; + readonly rights: readonly number[]; + readonly tops: readonly number[]; + readonly bottoms: readonly number[]; + /** Where a text starts and ends to draw, as `layoutText` reads them: 0 for a bold face. */ + readonly heads: readonly number[] | undefined; + readonly tails: readonly number[] | undefined; + /** How far below the baseline its underline lies. */ + readonly underline: number; + readonly afterStack: number; + /** How far below the baseline a text of it reaches. */ + readonly below: number; +} + +/** A face of a font of `FONT_METRICS`, regular or bold. */ +function faceOf(font: string, metrics: FontMetrics, bold: boolean): Face { + const info = fontInfo(font); + const shx = info?.file.endsWith(".shx") ?? true; + const own = bold ? metrics.bold : undefined; + // The bold face's numbers are in heights of its own capital A, and its descent in the regular's. + const scale = own ? (capHeightOf(font) ?? 1) / (capHeightOf(font, true) ?? 1) : 1; + return { + font, + bold: own !== undefined, + shx, + advances: own?.advances ?? metrics.advances, + lefts: own?.lefts ?? metrics.lefts, + rights: own?.rights ?? metrics.rights, + tops: own?.tops ?? metrics.tops, + bottoms: own?.bottoms ?? metrics.bottoms, + heads: own ? undefined : metrics.heads, + tails: own ? undefined : metrics.tails, + underline: shx ? UNDERLINE_SHX : metrics.below * scale, + afterStack: metrics.afterStack, + below: metrics.below * scale, + }; +} + +/** Characters with a space the line does not break at as a space, which is how it is drawn. */ +function nonBreaking(value: string): string { + return value.replaceAll("\u00a0", " "); +} + +/** A number that is finite, or `fallback`. */ +function finite(value: unknown, fallback: number): number { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} + +/** Where a character's numbers are in the tables, and whether they hold its own. */ +function indexOf(character: string): number { + return tableIndex(character.codePointAt(0)!); +} + +/** A part of a stack, measured at height 1: its ink's width, top and bottom, and its first left. */ +interface Part { + readonly value: string; + /** How wide its ink is: from `left` to the right of its last character's ink. */ + readonly ink: number; + readonly left: number; + readonly top: number; + readonly bottom: number; + readonly odd: boolean; +} + +function partOf(value: string, face: Face): Part { + let advance = 0; + let ink = 0; + let left: number | undefined; + let top = 0; + let bottom = 0; + let odd = false; + for (const character of value) { + let index = indexOf(character); + if (index < 0) { + index = UNKNOWN; + odd = true; + } + left ??= face.lefts[index]!; + ink = advance + face.rights[index]!; + // A space reaches neither up nor down: a part of spaces only stands as wide as they are. + if (character !== " ") { + top = Math.max(top, face.tops[index]!); + bottom = Math.min(bottom, face.bottoms[index]!); + } + advance += face.advances[index]!; + } + return { value, ink: ink - (left ?? 0), left: left ?? 0, top, bottom, odd }; +} + +/** + * A stack laid out about its start on the baseline, in drawing units: its parts' first points and + * baselines, its bar or slash, how far its ink reaches along and up and down, and the advance it + * takes, to the next character's first point. + */ +interface StackShape { + readonly parts: readonly { + readonly value: string; + readonly x: number; + readonly up: number; + /** How far its ink reaches above its baseline, in heights. */ + readonly top: number; + }[]; + readonly stroke: readonly [Point, Point] | undefined; + readonly ink: number; + readonly top: number; + readonly bottom: number; + readonly advance: number; +} + +function stackShape( + top: Part, + bottom: Part, + separator: "/" | "#" | "^", + face: Face, + size: number, + widthFactor: number, +): StackShape { + const across = size * widthFactor; + const parts: StackShape["parts"][number][] = []; + let stroke: [Point, Point] | undefined; + let ink: number; + let rise: number; + if (separator === "#") { + // The top part's baseline at a digit's top, and the slash's middle at the bottom part's ink + // top, or a digit's where it has none. + const digit = face.tops[indexOf("0")]!; + const up = digit * size; + const after = (top.ink + SLASH_GAP) * across; + parts.push({ value: top.value, x: -top.left * across, up, top: top.top }); + parts.push({ value: bottom.value, x: after - bottom.left * across, up: 0, top: bottom.top }); + const middle: Point = [ + (top.ink + SLASH_GAP / 2) * across, + (bottom.top > 0 ? bottom.top : digit) * size, + ]; + const turn = (SLASH_ANGLE * Math.PI) / 180; + const half: Point = [ + ((Math.cos(turn) * SLASH_LENGTH) / 2) * across, + ((Math.sin(turn) * SLASH_LENGTH) / 2) * size, + ]; + stroke = [ + [middle[0] - half[0], middle[1] - half[1]], + [middle[0] + half[0], middle[1] + half[1]], + ]; + ink = after + bottom.ink * across; + rise = up + top.top * size; + } else { + const wide = Math.max(top.ink, bottom.ink); + const bar = (bottom.top - bottom.bottom + STACK_GAP) * size; + const up = bar + STACK_GAP * size; + const centered = separator === "/"; + const offset = (part: Part) => (centered ? ((wide - part.ink) / 2) * across : 0); + parts.push({ value: top.value, x: offset(top) - top.left * across, up, top: top.top }); + parts.push({ + value: bottom.value, + x: offset(bottom) - bottom.left * across, + up: 0, + top: bottom.top, + }); + if (centered) { + stroke = [ + [0, bar], + [wide * across, bar], + ]; + } + ink = wide * across; + rise = up + top.top * size; + } + return { + parts, + stroke, + ink, + top: rise, + bottom: bottom.bottom * size, + advance: ink + face.afterStack * across, + }; +} + +/** + * A run of a line as it is built. Its value is the stretches in `head`, if any, and then the + * stretch of `source` from `from` to `to`, which grows while the run's characters follow on in + * one string. + */ +interface Built { + readonly kind: "run"; + head: string[] | undefined; + source: string; + from: number; + to: number; + readonly x: number; + readonly face: Face; + readonly format: RunFormat; + /** Its advances so far, and where its last character's first point is. */ + advance: number; + last: number; + lastIndex: number; + top: number; + bottom: number; +} + +/** What a line holds as it is built, in drawing units from its first point. */ +interface Line { + readonly items: ( + | Built + | { + readonly kind: "stack"; + readonly x: number; + readonly shape: StackShape; + readonly face: Face; + readonly value: string; + } + )[]; + /** True when it ends in a stack and the spaces after the stack were dropped. */ + spaced: boolean; +} + +/** Where the next character of a line goes, and what it continues. */ +interface Pen { + /** Where the next character's first point is, if it continues the run. */ + x: number; + /** The run the next character continues, by its key, or undefined after a stack or at the start. */ + key: string | undefined; + /** Where the last character's ink ends. */ + ink: number; +} + +/** A word's characters of one format, the stretch of `source` from `from` to `to`, or a stack. */ +type WordPart = + | { + kind: "characters"; + source: string; + from: number; + to: number; + face: Face; + key: string; + format: RunFormat; + } + | { + readonly kind: "stack"; + readonly shape: StackShape; + readonly face: Face; + readonly value: string; + }; + +/** The parts of a word or of the spaces before it, kept from word to word to be used again. */ +interface Parts { + readonly items: WordPart[]; + count: number; +} + +/** The value of a run as built, as one flat string. */ +function valueOf(run: Built): string { + const last = run.source.slice(run.from, run.to); + return run.head === undefined ? last : [...run.head, last].join(""); +} + +/** + * Lays a paragraph out about its point, in time in proportion to its value: its lines broken at + * its width and at each `\P`, each run of each line where it draws, and its strokes. It reads any + * value and never throws. + */ +export function layoutParagraph(paragraph: ParagraphToMeasure): ParagraphLayout { + return layOut(settingsOf(paragraph), parseParagraph(paragraph.value)); +} + +/** What a paragraph's layout reads of it apart from its value, with each number as written. */ +interface Settings { + readonly height: number; + readonly widthFactor: number; + readonly obliqueAngle: number; + /** The width, or 0 for none. */ + readonly width: number; + readonly factor: number; + readonly exactly: boolean; + /** The font of `FONTS`, or undefined for one that is not, which is measured as `txt.shx`. */ + readonly font: string | undefined; + readonly align: ParagraphAlign | undefined; + readonly valign: ParagraphVerticalAlign | undefined; +} + +/** A paragraph's settings, from its numbers as the writers write them, as a file holds them. */ +function settingsOf(paragraph: ParagraphToMeasure): Settings { + const chosen = written(finite(paragraph.lineSpacing, 1)); + const font = paragraph.font ?? STANDARD_FONT; + const align = paragraph.align; + const valign = paragraph.valign; + return { + height: Math.max(written(finite(paragraph.height, 0)), 0), + widthFactor: written(finite(paragraph.widthFactor, 1)), + obliqueAngle: written(finite(paragraph.obliqueAngle, 0)), + width: Math.max(written(finite(paragraph.width, 0)), 0), + factor: chosen >= LINE_SPACING_RANGE[0] && chosen <= LINE_SPACING_RANGE[1] ? chosen : 1, + exactly: paragraph.lineSpacingStyle === "exactly", + font: fontMetrics(font).known ? font : undefined, + align: align === "center" || align === "right" ? align : undefined, + valign: valign === "middle" || valign === "bottom" ? valign : undefined, + }; +} + +function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { + const { height, widthFactor, obliqueAngle, factor, exactly } = settings; + const along = height * widthFactor; + const own = fontMetrics(settings.font); + const ownFont = settings.font ?? STANDARD_FONT; + const given = settings.width; + const wrapAt = given > 0 ? given + SLACK * height : Infinity; + const tangent = Math.tan((obliqueAngle * Math.PI) / 180); + const lean = Number.isFinite(tangent) ? tangent : 0; + let approximate = settings.font === undefined || parsed.problem !== undefined; + + // The faces of the call, by font and weight. A paragraph names at most the fonts of `FONTS`. + const faces = new Map(); + const faceFor = (format: RunFormat): Face => { + const font = format.font ?? ownFont; + const metrics = font === ownFont ? own.metrics : FONT_METRICS[font]!; + const bold = format.bold && metrics.bold !== undefined; + const key = `${font}|${bold}`; + let face = faces.get(key); + if (!face) faces.set(key, (face = faceOf(font, metrics, bold))); + return face; + }; + const keyOf = (format: RunFormat, face: Face): string => + `${face.font}|${face.bold}|${format.underline}|${format.overline}|${format.strikeThrough}`; + + const lines: Line[] = []; + let line: Line = { items: [], spaced: false }; + lines.push(line); + const pen: Pen = { x: 0, key: undefined, ink: 0 }; + const word: Parts = { items: [], count: 0 }; + const spaces: Parts = { items: [], count: 0 }; + let words = 0; + + /** + * Places parts from where `pen` is, and moves `pen` on past them. With `into`, it adds them to + * that line. It gives how far the last of them reach for the break: the last characters' ink + * less the left of the first of them, or the last stack's ink; spaces have no part in it. + */ + const place = (parts: Parts, pen: Pen, into?: Line): number => { + let { x, key, ink } = pen; + let reach = x; + let left: number | undefined; + for (let p = 0; p < parts.count; p++) { + const part = parts.items[p]!; + if (part.kind === "stack") { + if (into) { + into.items.push({ + kind: "stack", + x, + shape: part.shape, + face: part.face, + value: part.value, + }); + } + reach = x + part.shape.ink; + x += part.shape.advance; + ink = reach; + key = undefined; + left = undefined; + continue; + } + const { face } = part; + let run: Built | undefined; + if (key !== part.key) { + // A new run starts where the last one's advances end, or its ink where that is further. + if (key !== undefined && ink > x) x = ink; + key = part.key; + if (into) { + run = { + kind: "run", + head: undefined, + source: part.source, + from: part.from, + to: part.from, + x, + face, + format: part.format, + advance: 0, + last: x, + lastIndex: 0, + top: 0, + bottom: 0, + }; + into.items.push(run); + } + } else if (into) { + const last = into.items[into.items.length - 1]; + run = last?.kind === "run" ? last : undefined; + } + const { source: value, to } = part; + for (let k = part.from; k < to; k++) { + const code = value.charCodeAt(k); + let index = tableIndex(value.codePointAt(k)!); + if (index < 0) index = UNKNOWN; + ink = x + face.rights[index]! * along; + if (code !== 32) { + left ??= face.lefts[index]! * along; + reach = ink - left; + } + if (run) { + run.last = x; + run.lastIndex = index; + if (face.tops[index]! > run.top) run.top = face.tops[index]!; + if (face.bottoms[index]! < run.bottom) run.bottom = face.bottoms[index]!; + } + x += face.advances[index]! * along; + // A pair of surrogates is one character. + if (code >= 0xd800 && code <= 0xdbff && k + 1 < to && value.charCodeAt(k + 1) >= 0xdc00) + k++; + } + if (run) { + // The run holds the part's characters, as one stretch where they follow on. + if (run.source !== value || run.to !== part.from) { + if (run.to > run.from) (run.head ??= []).push(run.source.slice(run.from, run.to)); + run.source = value; + run.from = part.from; + } + run.to = to; + run.advance = x - run.x; + } + } + pen.x = x; + pen.key = key; + pen.ink = ink; + return reach; + }; + + /** Drops the spaces a line ends with. */ + const endLine = (): void => { + if (spaces.count > 0 && line.items[line.items.length - 1]?.kind === "stack") line.spaced = true; + spaces.count = 0; + }; + const trial: Pen = { x: 0, key: undefined, ink: 0 }; + const endWord = (): void => { + if (word.count === 0) return; + trial.x = pen.x; + trial.key = pen.key; + trial.ink = pen.ink; + place(spaces, trial); + if (words > 0 && place(word, trial) > wrapAt) { + endLine(); + line = { items: [], spaced: false }; + lines.push(line); + pen.x = 0; + pen.key = undefined; + pen.ink = 0; + } else place(spaces, pen, line); + place(word, pen, line); + words++; + word.count = 0; + spaces.count = 0; + }; + /** + * Appends the stretch of `source` from `from` to `to`, of one run's format, to a list of parts: + * to its last part where that follows on in the same format, or in a part kept from before. + */ + const append = ( + into: Parts, + source: string, + from: number, + to: number, + format: RunFormat, + face: Face, + key: string, + ): void => { + const last = into.count > 0 ? into.items[into.count - 1] : undefined; + if ( + last?.kind === "characters" && + last.key === key && + last.source === source && + last.to === from + ) { + last.to = to; + return; + } + const kept = into.items[into.count]; + if (kept?.kind === "characters") { + kept.source = source; + kept.from = from; + kept.to = to; + kept.face = face; + kept.key = key; + kept.format = format; + } else into.items[into.count] = { kind: "characters", source, from, to, face, key, format }; + into.count++; + }; + + for (const piece of parsed.pieces) { + if (piece.kind === "break") { + endWord(); + endLine(); + line = { items: [], spaced: false }; + lines.push(line); + pen.x = 0; + pen.key = undefined; + pen.ink = 0; + words = 0; + continue; + } + const face = faceFor(piece.format); + if (piece.kind === "stack") { + const top = partOf(piece.top, face); + const bottom = partOf(piece.bottom, face); + if (top.odd || bottom.odd || !(face.shx || STACKS_MEASURED.has(face.font))) + approximate = true; + // How wide a part of spaces stands is measured only where the other part is wider. + const blank = (part: Part) => part.value.length > 0 && part.top === 0 && part.bottom === 0; + if ((blank(top) && top.ink > bottom.ink) || (blank(bottom) && bottom.ink > top.ink)) { + approximate = true; + } + const shape = stackShape(top, bottom, piece.separator, face, height, widthFactor); + const value = `${piece.top}${piece.separator}${piece.bottom}`; + word.items[word.count++] = { kind: "stack", shape, face, value }; + continue; + } + if (face.shx && piece.diameter) approximate = true; + const { format } = piece; + const key = keyOf(format, face); + let from = 0; + // A space the line does not break at is drawn as a space. + const value = nonBreaking(piece.value); + const breaking = piece.value; + for (let k = 0; k < value.length; k++) { + if (breaking.charCodeAt(k) === 32) { + if (k > from) append(word, value, from, k, format, face, key); + endWord(); + append(spaces, value, k, k + 1, format, face, key); + from = k + 1; + } else if (tableIndex(value.codePointAt(k)!) < 0) { + approximate = true; + } + } + if (value.length > from) append(word, value, from, value.length, format, face, key); + } + endWord(); + endLine(); + + if (lean !== 0 && [...faces.values()].some((face) => face.shx)) approximate = true; + + // Each line's ink along it, upright and leaned, and how far it reaches up and down. + const measured = lines.map((built) => { + let up = 0; + let stackUp = 0; + let down = 0; + let start: number | undefined; + /** How far the lean moves where the line starts: by its first character's bottom. */ + let startLean = 0; + let end = 0; + for (const item of built.items) { + if (item.kind === "stack") { + stackUp = Math.max(stackUp, item.shape.top); + down = Math.min(down, item.shape.bottom); + start ??= item.x; + end = item.x + item.shape.ink; + continue; + } + const run = item; + up = Math.max(up, (run.format.overline ? Math.max(run.top, OVERLINE) : run.top) * height); + down = Math.min(down, run.bottom * height); + if (start === undefined) { + let index = tableIndex( + (run.head?.[0] ?? run.source.slice(run.from, run.to)).codePointAt(0) ?? 32, + ); + if (index < 0) index = UNKNOWN; + start = run.x + run.face.lefts[index]! * along; + startLean = lean * run.face.bottoms[index]! * height; + } + end = run.last + run.face.rights[run.lastIndex]! * along; + } + const empty = start === undefined; + // A line's A is at least a capital's height, and D a third of it unless a stack reaches highest. + const top = empty ? height : Math.max(up, stackUp); + // A line that ends in a stack and dropped spaces after it is placed by its first point and + // not by its ink: the left of its first character's ink further on, at any attachment. + const first = built.items[0]; + const shift = built.spaced && first?.kind === "run" ? (start ?? 0) - first.x : 0; + return { + built, + top, + below: stackUp > up ? 0 : AT_LEAST_BELOW * height, + down, + start: start ?? 0, + end, + leanedStart: (start ?? 0) + startLean - shift, + leanedEnd: empty ? 0 : end + lean * top - shift, + }; + }); + + // Down the box: each line's baseline from its top. + const baselines: number[] = []; + let boxHeight: number; + if (exactly) { + measured.forEach((_, k) => baselines.push(-height - k * EXACT_PITCH * factor * height)); + boxHeight = -baselines[baselines.length - 1]! + EXACT_BELOW * height; + } else { + let top = 0; + for (const m of measured) { + baselines.push(top - m.top); + top -= factor * (m.top + m.below + AT_LEAST_BELOW * height); + } + const last = measured[measured.length - 1]!; + boxHeight = -(baselines[baselines.length - 1]! + last.down); + } + const { align, valign } = settings; + const boxTop = valign === "middle" ? boxHeight / 2 : valign === "bottom" ? boxHeight : 0; + + const ink: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]; + const include = (x: number, y: number): void => { + if (x < ink[0]) ink[0] = x; + if (y < ink[1]) ink[1] = y; + if (x > ink[2]) ink[2] = x; + if (y > ink[3]) ink[3] = y; + }; + const strokes: ParagraphStroke[] = []; + const stroke = (kind: ParagraphStroke["kind"], from: Point, to: Point): void => { + strokes.push({ kind, from, to }); + include(...from); + include(...to); + }; + let widest = 0; + const laid = measured.map((m, k): ParagraphLine => { + const baseline = boxTop + baselines[k]!; + const offset = + align === "center" + ? -(m.leanedStart + m.leanedEnd) / 2 + : align === "right" + ? -m.leanedEnd + : -m.leanedStart; + const runs: ParagraphRun[] = []; + /** The value of the line's one run or stack, and those of all once it has more, joined flat. */ + let value = ""; + let values: string[] | undefined; + const add = (part: string): void => { + if (values) values.push(part); + else if (value === "") value = part; + else values = [value, part]; + }; + /** Adds a run of `value` in `face` at its first point `x`, of `size`, with its baseline at `base`. */ + const run = (value: string, x: number, base: number, size: number, face: Face, top: number) => { + if (value === "") return; + let advance = 0; + let head: number | undefined; + let tail = 0; + for (const character of value) { + let index = indexOf(character); + if (index < 0) index = UNKNOWN; + head ??= face.heads?.[index] ?? 0; + advance += face.advances[index]!; + tail = face.tails?.[index] ?? 0; + } + const scale = size * widthFactor; + const drawn: ParagraphRun = { + value, + x, + baseline: base, + height: size, + font: face.font, + bold: face.bold, + advance: advance * scale, + start: x + (head ?? 0) * scale, + end: x + (advance + tail) * scale, + }; + runs.push(drawn); + const below = face.below * size; + const reach = Math.max(top, 1) * size; + const from = Math.min(drawn.start, x); + const to = Math.max(drawn.end, x + drawn.advance); + include(from - lean * below, base - below); + include(to + lean * reach, base + reach); + include(from + lean * reach, base + reach); + include(to - lean * below, base - below); + }; + for (const item of m.built.items) { + if (item.kind === "stack") { + add(item.value); + const at = item.x + offset; + for (const part of item.shape.parts) { + run(part.value, at + part.x, baseline + part.up, height, item.face, part.top); + } + const drawnStroke = item.shape.stroke; + if (drawnStroke) { + const [[x0, y0], [x1, y1]] = drawnStroke; + stroke("bar", [at + x0, baseline + y0], [at + x1, baseline + y1]); + } + continue; + } + const built = item; + const x = built.x + offset; + const drawn = valueOf(built); + add(drawn); + run(drawn, x, baseline, height, built.face, built.top); + const { underline, overline, strikeThrough } = built.format; + const across = (kind: ParagraphStroke["kind"], up: number): void => + stroke(kind, [x, baseline + up], [x + built.advance, baseline + up]); + if (underline) across("underline", -built.face.underline * height); + if (overline) across("overline", OVERLINE * height); + if (strikeThrough) across("strike-through", STRIKE_THROUGH * height); + } + widest = Math.max(widest, m.end - m.start); + return { + value: values ? values.join("") : value, + runs, + baseline, + start: m.built.items.length === 0 ? 0 : m.start + offset, + end: m.built.items.length === 0 ? 0 : m.end + offset, + top: m.top, + }; + }); + + const frameWidth = given > 0 ? given : widest; + const left = align === "center" ? -frameWidth / 2 : align === "right" ? -frameWidth : 0; + return { + lines: laid, + strokes, + frame: [left, boxTop - boxHeight, left + frameWidth, boxTop], + ink: ink[0] === Infinity ? undefined : ink, + lean, + widthFactor, + obliqueAngle, + approximate, + problem: parsed.problem, + }; +} + +/** The corners of a box of a layout where `place` puts them: lower left, lower right, upper right, upper left. */ +function corners( + place: (along: number, up: number) => Point, + [x0, y0, x1, y1]: readonly [number, number, number, number], +): [Point, Point, Point, Point] { + return [place(x0, y0), place(x1, y0), place(x1, y1), place(x0, y1)]; +} + +/** A paragraph's measure from its layout, in time in proportion to its lines. */ +export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout): ParagraphMeasure { + const place = placer(paragraph); + const box = (b: readonly [number, number, number, number]) => corners(place, b); + const lines: { value: string; corners: [Point, Point, Point, Point] }[] = []; + for (const line of layout.lines) { + if (line.runs.length === 0) continue; + const lean = layout.lean * line.top; + lines.push({ + value: line.value, + corners: [ + place(line.start, line.baseline), + place(line.end, line.baseline), + place(line.end + lean, line.baseline + line.top), + place(line.start + lean, line.baseline + line.top), + ], + }); + } + return { + corners: layout.ink && box(layout.ink), + frame: box(layout.frame), + lines, + approximate: layout.approximate, + }; +} + +/** + * A paragraph's rotation in degrees as its direction is worked out from it: reduced to a turn, + * from 0 up to 360 as a reader gives an angle back, then rounded as written, with 0 for one that + * rounds to 360. So one direction has one rotation, and a read of the file gives it back. + */ +export function paragraphTurn(rotation: number | undefined): number { + const turned = written(((finite(rotation, 0) % 360) + 360) % 360); + return turned === 360 ? 0 : turned; +} + +/** + * The direction a paragraph's lines run in, from `paragraphTurn`: the cosine and the sine as the + * DXF writes them, groups 11 and 21, with 15 significant digits, and `[1, 0]` for no turn, which + * the writers leave out. Both writers and the placement of its layout take it from here. + */ +export function paragraphDirection(rotation: number | undefined): readonly [number, number] { + const degrees = paragraphTurn(rotation); + if (degrees === 0) return [1, 0]; + const turn = (degrees * Math.PI) / 180; + return [Number(fifteenDigits(Math.cos(turn))), Number(fifteenDigits(Math.sin(turn)))]; +} + +/** Where a point of a paragraph's layout is in the drawing: turned to its direction and moved to `at`. */ +export function placer( + paragraph: Pick, +): (along: number, up: number) => Point { + const [cos, sin] = paragraphDirection(paragraph.rotation); + const [x, y] = paragraph.at ?? [0, 0]; + return (along, up) => [x + along * cos - up * sin, y + along * sin + up * cos]; +} + +/** + * Measures a paragraph as it plots: the box of all it draws, the box it is placed by, and each + * line that draws a character, where its width, its justification, its rotation and its style's + * font, width factor and oblique angle put them, by the rules at the top of this module. + * + * ```ts + * measureParagraph({ value: "ALL WORK SHALL COMPLY", height: 0.1, width: 1.5 }).lines.length; + * ``` + */ +export function measureParagraph(paragraph: ParagraphToMeasure): ParagraphMeasure { + return measured(paragraph, layoutParagraph(paragraph)); +} + +/** The shortest value a `ParagraphMeasurer` lays out only once in each of its settings. */ +const LONG = 256; + +/** A box `[left, bottom, right, top]` of a layout, or undefined for one that draws nothing. */ +type Ink = ParagraphLayout["ink"]; + +/** + * `layoutParagraph` and the box `measureParagraph` gives, for the paragraphs of one call, which + * may share their values. + */ +export interface ParagraphMeasurer { + /** Lays it out, keeping the last layout of each long value. */ + layout(paragraph: ParagraphToMeasure): ParagraphLayout; + /** + * The corners of the box of all it draws, as `measureParagraph` gives them, keeping only that + * box of each layout of a long value, so that each place after the first costs a constant. + */ + box(paragraph: ParagraphToMeasure): ParagraphMeasure["corners"]; + /** + * What `layout` costs before it lays a paragraph out, in characters of its value: 0 for a value + * shorter than `LONG`, one laid out for the first time or a layout it keeps, and the value's + * length for a long value laid out before in other settings, or one that took the place of + * another of its length, as `Strings` keeps them. A layout reads each character many times + * over, so it is priced at the whole length. The caller pays it before it calls `layout`. + */ + again(paragraph: ParagraphToMeasure): number; + /** What `box` costs before it lays a paragraph out, as `again` gives it for `layout`. */ + boxAgain(paragraph: ParagraphToMeasure): number; +} + +/** A key of a paragraph's settings. */ +function keyOf(settings: Settings): string { + return JSON.stringify(settings); +} + +/** + * Lays out as `layoutParagraph` does, and lays each value of `LONG` characters or more out once + * in each of its settings, keeping only what a caller asks for: the box of each layout, or the + * last layout. What it does again for a long value it reports first, through `again` and + * `boxAgain`, for the caller to pay. It holds those values until it is dropped, so make one for + * a call. + */ +export function paragraphMeasurer(): ParagraphMeasurer { + interface Kept { + boxes: Map | undefined; + last: { readonly key: string; readonly layout: ParagraphLayout } | undefined; + } + const kept = new Strings(); + const long = (value: unknown): value is string => + typeof value === "string" && value.length >= LONG; + /** What laying a long value out again costs, unless `has` finds what it keeps. */ + const cost = (paragraph: ParagraphToMeasure, has: (found: Kept, key: string) => boolean) => { + const value = paragraph.value; + if (!long(value)) return 0; + const found = kept.get(value); + const again = + kept.clashes(value) || (found !== undefined && !has(found, keyOf(settingsOf(paragraph)))); + return again ? value.length : 0; + }; + const entry = (value: string): Kept => { + let found = kept.get(value); + if (!found) kept.set(value, (found = { boxes: undefined, last: undefined })); + return found; + }; + const layout = (paragraph: ParagraphToMeasure): ParagraphLayout => { + const value = paragraph.value; + if (!long(value)) return layoutParagraph(paragraph); + const settings = settingsOf(paragraph); + const key = keyOf(settings); + const found = entry(value); + if (found.last?.key !== key) { + found.last = { key, layout: layOut(settings, parseParagraph(value)) }; + } + return found.last.layout; + }; + const box = (paragraph: ParagraphToMeasure): ParagraphMeasure["corners"] => { + const value = paragraph.value; + let ink: Ink; + if (!long(value)) ink = layoutParagraph(paragraph).ink; + else { + const settings = settingsOf(paragraph); + const key = keyOf(settings); + const found = entry(value); + found.boxes ??= new Map(); + if (found.boxes.has(key)) ink = found.boxes.get(key); + else found.boxes.set(key, (ink = layOut(settings, parseParagraph(value)).ink)); + } + return ink && corners(placer(paragraph), ink); + }; + return { + layout, + box, + again: (paragraph) => cost(paragraph, (found, key) => found.last?.key === key), + boxAgain: (paragraph) => cost(paragraph, (found, key) => found.boxes?.has(key) ?? false), + }; +} + +/** The fields of a paragraph its layout reads that a `TextStyle` holds. */ +const STYLED = ["font", "widthFactor", "obliqueAngle"] as const; + +/** The fields of a paragraph its layout reads that only the paragraph holds. */ +const OWN = [ + "value", + "height", + "width", + "at", + "rotation", + "align", + "valign", + "lineSpacing", + "lineSpacingStyle", +] as const; + +/** + * A paragraph in its style, as `measureParagraph` takes it: the font, the width factor and the + * oblique angle from the style where it has them, and the rest from the paragraph. Only those + * fields are read. + */ +export function paragraphInStyle( + paragraph: ParagraphToMeasure, + style: object | undefined, +): ParagraphToMeasure { + const out: Record = {}; + const from = paragraph as unknown as Record; + for (const field of OWN) out[field] = from[field]; + for (const field of STYLED) { + out[field] = + typeof style === "object" && style !== null && Object.hasOwn(style, field) + ? (style as Record)[field] + : from[field]; + } + return out as unknown as ParagraphToMeasure; +} + +/** + * The attachment an MTEXT holds for a paragraph's `align` and `valign`: 1 to 3 along the top, + * left to right, 4 to 6 along the middle and 7 to 9 along the bottom. + */ +export function paragraphAttachment( + paragraph: Pick, +): number { + const across = paragraph.align === "center" ? 1 : paragraph.align === "right" ? 2 : 0; + const down = paragraph.valign === "middle" ? 1 : paragraph.valign === "bottom" ? 2 : 0; + return 1 + across + 3 * down; +} + +/** The `align` and `valign` of an MTEXT's attachment, 1 to 9, or undefined for any other number. */ +export function attachmentPlace( + attachment: number, +): { readonly align: ParagraphAlign; readonly valign: ParagraphVerticalAlign } | undefined { + if (!Number.isInteger(attachment) || attachment < 1 || attachment > 9) return undefined; + const aligns = ["left", "center", "right"] as const; + const valigns = ["top", "middle", "bottom"] as const; + return { + align: aligns[(attachment - 1) % 3]!, + valign: valigns[Math.floor((attachment - 1) / 3)]!, + }; +} + +/** How an MTEXT holds a paragraph's line spacing style: 1 for at least, 2 for exactly. */ +export function lineSpacingStyleCode( + paragraph: Pick, +): 1 | 2 { + return paragraph.lineSpacingStyle === "exactly" ? 2 : 1; +} diff --git a/src/pdf.ts b/src/pdf.ts index 3a58c80..4732096 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -4,7 +4,7 @@ import type { XrefDrawings } from "./blocks.ts"; import type { Drawing } from "./drawing.ts"; import { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; -import { FONTS, fontInfo, type Font } from "./fonts.ts"; +import { FONTS, fontInfo, type Font, capHeightOf } from "./fonts.ts"; import { paperInfo } from "./papers.ts"; import { Sha256 } from "./sha256.ts"; import { filled } from "./shape.ts"; @@ -28,7 +28,9 @@ export interface PdfOptions { /** * The TrueType file of each font the texts are set in, by the font's name in `FONTS`, such as * `{ Arial: bytes }`: the font's own file, or one made to its widths. The PDF embeds each, cut - * to the letters it uses. A text in a font with no file here, or with a file `pdfFace` does + * to the letters it uses. A run of a paragraph in bold is set in the file of its font's bold + * face, by the font's name and ` Bold`, such as `{ "Arial Bold": bytes }`, which `boldFontKey` + * gives. A text in a font with no file here, or with a file `pdfFace` does * not take, and a text in an SHX font, is set in a standard face that is not embedded. */ readonly fonts?: Readonly>; @@ -269,6 +271,7 @@ const ATTRIBUTES = new Set([ "textLength", "lengthAdjust", "xml:space", + "font-weight", ]); /** @@ -287,7 +290,13 @@ function unescape(text: string, where: string): string { /** One of the three faces every PDF reader has without a file, as a font of the page. */ interface Face { - readonly name: "Helvetica" | "Times-Roman" | "Courier"; + readonly name: + | "Helvetica" + | "Times-Roman" + | "Courier" + | "Helvetica-Bold" + | "Times-Bold" + | "Courier-Bold"; /** The font whose widths it is given, which has the same advances. */ readonly widthsOf: Font; /** The height of a capital as a share of the size, as the font it has the widths of has it. */ @@ -335,6 +344,39 @@ const FACES = { descent: -157, stem: 51, }, + sansBold: { + name: "Helvetica-Bold", + widthsOf: "Arial", + capHeight: FONTS.Arial.capHeight, + ownCapHeight: 0.718, + flags: 262176, + box: "-170 -228 1003 962", + ascent: 718, + descent: -207, + stem: 140, + }, + serifBold: { + name: "Times-Bold", + widthsOf: "Times New Roman", + capHeight: FONTS["Times New Roman"].bold.capHeight, + ownCapHeight: 0.676, + flags: 262178, + box: "-168 -218 1000 935", + ascent: 683, + descent: -217, + stem: 139, + }, + monoBold: { + name: "Courier-Bold", + widthsOf: "Courier New", + capHeight: FONTS["Courier New"].bold.capHeight, + ownCapHeight: 0.562, + flags: 262177, + box: "-113 -250 749 801", + ascent: 629, + descent: -157, + stem: 106, + }, } as const satisfies Record; /** @@ -360,8 +402,21 @@ const FACE_OF_FONT: ReadonlyMap = new Map( }), ); +/** The bold face of each standard face, which has its widths: tsdraft measures bold as regular. */ +const BOLD_OF: ReadonlyMap = new Map([ + [FACES.sans, FACES.sansBold], + [FACES.serif, FACES.serifBold], + [FACES.mono, FACES.monoBold], +]); + +/** The key in `fonts` of the bold face of a font: its name and ` Bold`, such as `Arial Bold`. */ +export function boldFontKey(font: string): string { + return `${font} Bold`; +} + /** - * The face a PDF of tsdraft's sets a text in, for the font its style names. With `file`, the + * The face a PDF of tsdraft's sets a text in, for the font its style names, or its bold face for a + * run of a paragraph a code sets in bold. With `file`, the * TrueType file given for the font in `fonts`, it is the PostScript name of the file's font, * which the PDF embeds, when the font is a TrueType font of `FONTS` and the file one the PDF can * embed. Otherwise it is `Helvetica`, `Times-Roman` or `Courier`, which no PDF embeds: Arial, @@ -369,17 +424,17 @@ const FACE_OF_FONT: ReadonlyMap = new Map( * the face of its kind, stretched to the length the text plots. A font that is not one of * `FONTS` is set in Courier, as the picture draws it in the font of `Standard`. */ -export function pdfFace(font: string, file?: Uint8Array): string { +export function pdfFace(font: string, file?: Uint8Array, bold = false): string { const read = file === undefined ? undefined : embeddable(font, file); - return read === undefined ? standIn(font).name : read.name; + return read === undefined ? standIn(font, bold).name : read.name; } -/** The standard face a font is set in when it is not embedded. */ -function standIn(font: string | undefined): Face { - return ( +/** The standard face a font is set in when it is not embedded, in bold or not. */ +function standIn(font: string | undefined, bold = false): Face { + const face = (typeof font === "string" && Object.hasOwn(FONTS, font) ? FACE_OF_FONT.get(font) : undefined) ?? - FACES.mono - ); + FACES.mono; + return bold ? BOLD_OF.get(face)! : face; } /** The font of a file, when it is a TrueType font for a TrueType font of `FONTS` a PDF can embed. */ @@ -811,7 +866,10 @@ class PdfWriter { private readonly faces = new Map(); private readonly layers = new Map(); private readonly widths = new Map(); - /** Each font of `FONTS` whose file the PDF embeds, or null for one it sets in a face. */ + /** + * Each font of `FONTS` whose file the PDF embeds, by its name or `boldFontKey` of it, or null for + * one it sets in a face. + */ private readonly embedded = new Map(); private readonly deflate: PdfOptions["deflate"]; @@ -864,14 +922,18 @@ class PdfWriter { return number; } - /** The font a text in `font` is embedded in, read from its file once, or null for none. */ - private embeddedOf(font: string): Embedded | null { - let found = this.embedded.get(font); + /** + * The font a text in `font` is embedded in, in its bold face for `bold`, read from its file + * once, or null for none. + */ + private embeddedOf(font: string, bold: boolean): Embedded | null { + const named = bold ? boldFontKey(font) : font; + let found = this.embedded.get(named); if (found === undefined) { - const own = fontInfo(font)?.capHeight; + const own = capHeightOf(font, bold); const file = - this.files !== undefined && own !== undefined && Object.hasOwn(this.files, font) - ? this.files[font] + this.files !== undefined && own !== undefined && Object.hasOwn(this.files, named) + ? this.files[named] : undefined; const read = file === undefined ? undefined : embeddable(font, file); // The leading CAD app makes the capital `A` of a font as tall as the text, by the number @@ -882,7 +944,7 @@ class PdfWriter { read === undefined || capital === undefined ? null : new Embedded(read, capital, this.reserve()); - this.embedded.set(font, found); + this.embedded.set(named, found); } return found; } @@ -1348,9 +1410,14 @@ class PdfWriter { where, ); } - const embedded = this.embeddedOf(font); + const weight = element["font-weight"]; + if (weight !== undefined && weight !== "bold") { + throw refuse(`the font-weight ${JSON.stringify(weight)}`, where); + } + const bold = weight === "bold"; + const embedded = this.embeddedOf(font, bold); // A font that is not one of `FONTS` is drawn as `toSVG` draws it, in the font of `Standard`. - const face = standIn(font); + const face = standIn(font, bold); let codes: number[]; let natural: number; let size: number; diff --git a/src/read/check.ts b/src/read/check.ts index 175b3bd..a4af9ec 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -150,6 +150,8 @@ const ENTITY: Readonly> = { rotation: "number", style: "string", value: "string", + lineSpacing: "number", + lineSpacingStyle: { oneOf: ["at-least", "exactly"] }, }, dimension: { ...BASE, diff --git a/src/read/entities.ts b/src/read/entities.ts index f09b4e8..e175367 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -292,11 +292,12 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { } const dx = num(r, 11); const dy = num(r, 21); - // Its direction, groups 11 and 21, or else its rotation in radians, group 50. + // Its direction, groups 11 and 21, or else its rotation, group 50, which the leading CAD app + // reads as degrees, though the DXF Reference gives radians. const rotation = dx !== undefined && dy !== undefined && (dx !== 0 || dy !== 0) ? degrees((Math.atan2(dy, dx) * 180) / Math.PI) - : degrees((((num(r, 50) ?? 0) % (2 * Math.PI)) * 180) / Math.PI); + : degrees(num(r, 50) ?? 0); const entity: ReadMtext = { ...base, kind: "mtext", @@ -307,6 +308,8 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { rotation, style: name(r, 7) ?? "Standard", value: textOnce(value), + lineSpacing: num(r, 44) ?? 1, + lineSpacingStyle: num(r, 73) === 2 ? "exactly" : "at-least", }; return { entity }; } diff --git a/src/read/model.ts b/src/read/model.ts index 2195247..2dd77ea 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -308,7 +308,7 @@ export interface ReadInsert extends ReadEntityBase { /** * A paragraph text. Its value keeps its formatting codes, such as `\P` between paragraphs, and - * it is not laid out. + * `layoutMtext` lays it out. */ export interface ReadMtext extends ReadEntityBase { readonly kind: "mtext"; @@ -326,6 +326,10 @@ export interface ReadMtext extends ReadEntityBase { readonly style: string; /** As the leading CAD app holds it. */ readonly value: string; + /** The factor of its line spacing, 1 when the file states none. */ + readonly lineSpacing: number; + /** How its line spacing is taken: as the least, or exactly. */ + readonly lineSpacingStyle: "at-least" | "exactly"; } /** A linear or an aligned dimension. */ diff --git a/src/read/mtext.ts b/src/read/mtext.ts new file mode 100644 index 0000000..cf4554c --- /dev/null +++ b/src/read/mtext.ts @@ -0,0 +1,64 @@ +// The layout of a paragraph text a file holds, by the one layout of a paragraph: from its width, +// attachment, line spacing and value, in its style's font or the font of `FONTS` nearest it. +import { nearestFont } from "../fonts.ts"; +import { + attachmentPlace, + layoutParagraph, + measureParagraph, + type ParagraphLayout, + type ParagraphMeasure, + type ParagraphToMeasure, +} from "../paragraphs.ts"; +import type { ReadMtext, ReadTextStyle } from "./model.ts"; + +/** + * A read MTEXT as `layoutParagraph` takes it: in the font of `FONTS` nearest its style's, with + * its style's width factor and oblique angle. `exact` is false when the font is not the + * style's own, or the attachment is not one of 1 to 9, which is then taken as 1. + */ +export function mtextToMeasure( + mtext: ReadMtext, + style?: Pick, +): { readonly paragraph: ParagraphToMeasure; readonly exact: boolean } { + const font = nearestFont(style?.family ?? style?.font ?? ""); + const place = attachmentPlace(mtext.attachment); + const paragraph: ParagraphToMeasure = { + value: mtext.value, + height: mtext.height, + width: mtext.width, + font: font.font, + widthFactor: style?.widthFactor ?? 1, + obliqueAngle: style?.oblique ?? 0, + at: mtext.at, + rotation: mtext.rotation, + align: place?.align ?? "left", + valign: place?.valign ?? "top", + lineSpacing: mtext.lineSpacing, + lineSpacingStyle: mtext.lineSpacingStyle, + }; + return { paragraph, exact: font.exact && place !== undefined }; +} + +/** + * Lays a read MTEXT out as tsdraft lays out a paragraph, in its style, which the caller finds by + * the MTEXT's `style`. Its layout is `approximate` when its font or its attachment is not one + * tsdraft knows. + */ +export function layoutMtext( + mtext: ReadMtext, + style?: Pick, +): ParagraphLayout { + const { paragraph, exact } = mtextToMeasure(mtext, style); + const layout = layoutParagraph(paragraph); + return exact ? layout : { ...layout, approximate: true }; +} + +/** Measures a read MTEXT as `measureParagraph` measures a paragraph, in its style. */ +export function measureMtext( + mtext: ReadMtext, + style?: Pick, +): ParagraphMeasure { + const { paragraph, exact } = mtextToMeasure(mtext, style); + const measure = measureParagraph(paragraph); + return exact ? measure : { ...measure, approximate: true }; +} diff --git a/src/rules.ts b/src/rules.ts index 99321e2..3f0838e 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -23,6 +23,31 @@ import { import { isPaperUnit, isUnits, modelLength } from "./units.ts"; import { isTooLarge, written, writtenAngle } from "./format.ts"; import { fontInfo, STANDARD_TEXT_STYLE, type Font } from "./fonts.ts"; +import { + parseParagraph, + PARAGRAPH_CONTROL, + PARAGRAPH_ASTRAL, + PARAGRAPH_NESTING, + PARAGRAPH_NEVER_CLOSED, + PARAGRAPH_NEVER_OPENED, + PARAGRAPH_PRIVATE_USE, + PARAGRAPH_SHX_DIAMETER, + PARAGRAPH_STACK_LINED, + PARAGRAPH_STACK_PART, + PARAGRAPH_STACK_SEPARATOR, + PARAGRAPH_TOO_DEEP, + PARAGRAPH_TRAILING, + type BoldFont, + type ParsedParagraph, + type paragraphFontOption, + type paragraphFontOptionTwice, + type paragraphItalic, + type paragraphNoSemicolon, + type paragraphNotLaidOut, + type paragraphShxBold, + type paragraphUnknownCode, + type paragraphUnknownFont, +} from "./paragraph-codes.ts"; import { BUILT_IN_LINETYPES, builtInLinetype, LINEWEIGHTS, patternLength } from "./linetypes.ts"; import { layerAuditKey, @@ -131,6 +156,9 @@ const R12_DIMENSIONS = 'tsdraft writes no dimensions to R12 drawings. Use DXF version "R2018" for a dimension'; const R12_LEADERS = 'tsdraft writes no leaders to R12 drawings. Use DXF version "R2018" for a leader'; +const R12_PARAGRAPHS = + 'tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph'; +const LINE_SPACING = "A paragraph's line spacing is a factor from 0.25 to 4"; const R12_POLYLINES = 'tsdraft writes no arcs or widths of a polyline to R12 drawings. Use DXF version "R2018" for a polyline with bulges or a width'; const POLYLINE_WIDTH = @@ -871,6 +899,7 @@ export type R12Layouts = typeof R12_LAYOUTS; export type R12Dimensions = typeof R12_DIMENSIONS; export type R12Leaders = typeof R12_LEADERS; export type R12Polylines = typeof R12_POLYLINES; +export type R12Paragraphs = typeof R12_PARAGRAPHS; /** Resolves to `N` when it is a width a polyline can have, and to the error message otherwise. */ export type PolylineWidth = NotNegative; @@ -878,6 +907,356 @@ export type PolylineWidth = NotNegative = NotNegative; +/** + * Resolves to `N` when it is a line spacing factor a paragraph can have, from 0.25 to 4, and to + * the error message otherwise. + */ +export type LineSpacing = number extends N + ? N + : `${N}` extends + | `0.${"0" | "1"}${string}` + | `0.2${"0" | "1" | "2" | "3" | "4"}${string}` + | `0.${"0" | "1" | "2"}` + | `-${string}` + | `${string}e${string}` + | "0" + ? typeof LINE_SPACING + : `${N}` extends `0.${string}` | `${"1" | "2" | "3"}` | `${"1" | "2" | "3"}.${string}` | "4" + ? N + : typeof LINE_SPACING; + +/** A digit of a hexadecimal number, in either case. */ +type HexDigit = Chars<"0123456789abcdefABCDEF">; + +/** + * The first of `\`, `{`, `}` and `%` in `S`, and what follows it, or `undefined` for none: a + * delimiter is the first when what comes before it holds none of the others. + */ +type ParagraphStep = S extends `${infer A}\\${infer R}` + ? A extends `${string}${"{" | "}" | "%"}${string}` + ? ParagraphBrace + : ["\\", R] + : ParagraphBrace; + +type ParagraphBrace = S extends `${infer A}{${infer R}` + ? A extends `${string}${"}" | "%" | "\\"}${string}` + ? ParagraphClose + : ["{", R] + : ParagraphClose; + +type ParagraphClose = S extends `${infer A}}${infer R}` + ? A extends `${string}${"%" | "\\" | "{"}${string}` + ? ParagraphPercent + : ["}", R] + : ParagraphPercent; + +type ParagraphPercent = S extends `${string}%${infer R}` ? ["%", R] : undefined; + +/** The codes of a paragraph that draw a character, and need nothing after them. */ +type ParagraphPlainCode = "P" | "~" | "\\" | "{" | "}" | "o"; + +/** The codes tsdraft does not lay out that end with a `;`. */ +type ParagraphEndedCode = "p" | "H" | "W" | "Q" | "T" | "A" | "C" | "c"; + +/** + * Whether the characters are underlined, `L`, struck through, `K`, both or neither, as the codes + * `\L`, `\l`, `\K` and `\k` set it and each `}` puts it back. + */ +type Lined = "" | "L" | "K" | "LK"; + +/** + * The format the walk keeps of the characters, as each `{` saves it and its `}` puts it back: + * their lines, and whether a `\f` or `\F` has set them in an SHX font. + */ +interface Format { + readonly lined: Lined; + readonly shx: boolean; +} + +/** The format of a value's first character. */ +interface PlainFormat extends Format { + readonly lined: ""; + readonly shx: false; +} + +/** What `\L`, `\l`, `\K` and `\k` make of `F`. */ +type Relined = C extends "L" + ? F extends "K" | "LK" + ? "LK" + : "L" + : C extends "l" + ? F extends "K" | "LK" + ? "K" + : "" + : C extends "K" + ? F extends "L" | "LK" + ? "LK" + : "K" + : F extends "L" | "LK" + ? "L" + : ""; + +/** + * Resolves to `T` when it is a value a paragraph can be given, and to the error message + * otherwise: no control character but a line feed, which is a paragraph break, and no character a + * text cannot hold, and the codes `parseParagraph` reads, each as tsdraft lays it out, with `%%c` + * refused in an SHX font that a `\f` or `\F` names. Two checks are left to the code when it + * runs: `%%c` in the paragraph's own font, which only the style knows, and a character above + * U+FFFF, since TypeScript reads a template literal type by code points and never splits the + * surrogate pair that holds one, so no pattern of a type can find it. + */ +export type ParagraphValue = string extends T + ? T + : T extends `${string}${Exclude}${string}` + ? typeof PARAGRAPH_CONTROL + : T extends `${string}${Chars}${string}` + ? typeof PARAGRAPH_PRIVATE_USE + : ParagraphCodes; + +/** + * The most steps the walk of a literal value takes. A value that needs more passes as it is, and + * is checked when the code runs, so the compiler never gives up on a long one. + */ +type ParagraphTypeSteps = 250; + +/** + * Walks `S`, the rest of the value `T`, from one special character to the next, with what each + * open brace saved in `D`, a mark in `N` for each step, and the format of the characters in `F`. + */ +type ParagraphCodes< + T extends string, + S extends string, + D extends Format[], + N extends 0[], + F extends Format, +> = N["length"] extends ParagraphTypeSteps + ? T + : ParagraphStep extends [infer M, infer R extends string] + ? M extends "{" + ? D["length"] extends typeof PARAGRAPH_NESTING + ? typeof PARAGRAPH_TOO_DEEP + : ParagraphCodes + : M extends "}" + ? D extends [...infer E extends Format[], infer Saved extends Format] + ? ParagraphCodes + : typeof PARAGRAPH_NEVER_OPENED + : M extends "%" + ? R extends `%${"c" | "C"}${infer After}` + ? F["shx"] extends true + ? typeof PARAGRAPH_SHX_DIAMETER + : ParagraphCodes + : R extends `%${"d" | "D" | "p" | "P"}${infer After}` + ? ParagraphCodes + : ParagraphCodes + : ParagraphCode + : D extends [] + ? T + : typeof PARAGRAPH_NEVER_CLOSED; + +/** Reads the code after a backslash, `R` and what follows it. */ +type ParagraphCode< + T extends string, + R extends string, + D extends Format[], + N extends 0[], + F extends Format, +> = R extends `${infer C}${infer After}` + ? C extends ParagraphPlainCode + ? ParagraphCodes + : C extends "L" | "l" | "K" | "k" + ? ParagraphCodes; shx: F["shx"] }> + : C extends "f" | "F" + ? After extends `${infer Body};${infer Next}` + ? ParagraphFont + : ReturnType> + : C extends "S" + ? ParagraphStack + : C extends ParagraphEndedCode + ? After extends `${string};${string}` + ? ReturnType> + : ReturnType> + : C extends "N" | "X" | "O" + ? ReturnType> + : C extends "U" | "u" + ? After extends `+${infer H1}${infer H2}${infer H3}${infer H4}${infer Next}` + ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] + ? ParagraphUnicode, Next, D, N, F> + : ReturnType> + : ReturnType> + : C extends "M" | "m" + ? After extends `+${"1" | "2" | "3" | "4" | "5"}${infer H1}${infer H2}${infer H3}${infer H4}${string}` + ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] + ? ReturnType> + : ReturnType> + : ReturnType> + : ReturnType> + : typeof PARAGRAPH_TRAILING; + +/** A `\U+XXXX` code, with its four digits in lower case. */ +type ParagraphUnicode< + T extends string, + X extends string, + Next extends string, + D extends Format[], + N extends 0[], + F extends Format, +> = X extends `00${"0" | "1"}${string}` | "007f" + ? typeof PARAGRAPH_CONTROL + : X extends `d${"8" | "9" | "a" | "b" | "c" | "d" | "e" | "f"}${string}` + ? typeof PARAGRAPH_ASTRAL + : X extends `e8${string}` + ? typeof PARAGRAPH_PRIVATE_USE + : ParagraphCodes; + +/** A `\f` or `\F` code: a font of `FONTS`, then its options. */ +type ParagraphFont< + T extends string, + C extends "f" | "F", + Body extends string, + Next extends string, + D extends Format[], + N extends 0[], + F extends Format, +> = Body extends `${infer Name}|${infer Options}` + ? Name extends Font + ? ParagraphFontOptions> + : ReturnType> + : Body extends Font + ? ParagraphCodes> + : ReturnType>; + +/** `F` in the font `Name`, which is an SHX font when it has no bold face. */ +type InFont = { + lined: F["lined"]; + shx: Name extends BoldFont ? false : true; +}; + +/** The options of a font code, with the letters of those given so far in `Given`. */ +type ParagraphFontOptions< + T extends string, + C extends "f" | "F", + Name extends Font, + O extends string, + Next extends string, + D extends Format[], + N extends 0[], + F extends Format, + Given extends string = never, +> = N["length"] extends ParagraphTypeSteps + ? T + : O extends `${infer First}|${infer More}` + ? ParagraphFontOnce extends true + ? ParagraphFontOptions> + : ParagraphFontOnce + : ParagraphFontOnce extends true + ? ParagraphCodes + : ParagraphFontOnce; + +/** The letter of a font option. */ +type OptionLetter = O extends `${infer L}${string}` ? L : never; + +/** True for an option a font may have whose letter `Given` does not hold, and the message otherwise. */ +type ParagraphFontOnce< + C extends string, + Name extends Font, + O extends string, + Given extends string, +> = + ParagraphFontOption extends true + ? O extends `${Given}${string}` + ? ReturnType>> + : true + : ParagraphFontOption; + +/** + * True for one or more digits, as `isNumbered` in `src/paragraph-codes.ts` reads a font option's + * number. Past 64 it gives up and leaves the rest to the runtime check. + */ +type AllDigits = K["length"] extends 64 + ? true + : S extends `${Digit}${infer R}` + ? R extends "" + ? true + : AllDigits + : false; + +/** True for an option a font may have, and the message otherwise. */ +type ParagraphFontOption = O extends + | "b0" + | "i0" + ? true + : O extends `${"c" | "p"}${infer Count}` + ? AllDigits extends true + ? true + : ReturnType> + : O extends "b1" + ? Name extends BoldFont + ? true + : ReturnType> + : O extends "i1" + ? ReturnType> + : ReturnType>; + +/** A digit or a capital, which a stacked part may hold. */ +type Tall = Chars<"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ">; + +/** + * What a stacked part holds so far: nothing, `""`; spaces only, `"s"`; signs only, `"o"`; digits or + * capitals with signs or not, `"t"`; or something it may not hold, `"x"`. + */ +type PartHolds = "" | "s" | "o" | "t" | "x"; + +/** What a part holds after the character `C`. */ +type PartStep

= C extends " " + ? P extends "" | "s" + ? "s" + : "x" + : C extends Tall + ? P extends "" | "o" | "t" + ? "t" + : "x" + : C extends "." | "," | "+" | "-" + ? P extends "" | "o" + ? "o" + : P extends "t" + ? "t" + : "x" + : "x"; + +/** + * A `\S` code from after its letter: its parts, divided by the first `/`, `#` or `^`, up to its + * `;`, with what the part being read holds in `P` and whether the top part may be stacked in + * `Top`. It is refused in underlined or struck-through characters. + */ +type ParagraphStack< + T extends string, + S extends string, + D extends Format[], + Divided extends boolean, + N extends 0[], + F extends Format, + P extends PartHolds, + Top extends boolean, +> = N["length"] extends ParagraphTypeSteps + ? T + : S extends `\\${infer C}${infer R}` + ? ParagraphStack, Top> + : S extends `;${infer R}` + ? Divided extends true + ? F["lined"] extends "" + ? [Top, P extends "" | "s" | "t" ? true : false] extends [true, true] + ? ParagraphCodes + : typeof PARAGRAPH_STACK_PART + : typeof PARAGRAPH_STACK_LINED + : typeof PARAGRAPH_STACK_SEPARATOR + : S extends `${"/" | "#" | "^"}${infer R}` + ? Divided extends true + ? ParagraphStack + : ParagraphStack + : S extends `${infer C}${infer R}` + ? ParagraphStack, Top> + : ReturnType>; + /** Returns what is wrong with a layer name for a DXF version, or undefined when it is valid. */ export function layerNameProblem(name: string, version: DxfVersion): string | undefined { const problem = nameProblem(name, LAYER_NAMES); @@ -1040,6 +1419,7 @@ export const R12_ONLY = { dimensions: R12_DIMENSIONS, leaders: R12_LEADERS, polylines: R12_POLYLINES, + paragraphs: R12_PARAGRAPHS, } as const; /** What is wrong with a donut's hole, of `inside` across, or undefined. */ @@ -1212,6 +1592,70 @@ export function textAlignProblem(field: "align" | "valign", value: unknown): str .replace(/, ([^,]*)$/, " or $1")}`; } +/** How a paragraph is justified across its box, and up and down it, and how its lines are spaced. The first of each is the default. */ +export const PARAGRAPH_ALIGNS = ["left", "center", "right"] as const; +export const PARAGRAPH_VERTICAL_ALIGNS = ["top", "middle", "bottom"] as const; +export const LINE_SPACING_STYLES = ["at-least", "exactly"] as const; + +/** The least and the most line spacing factor the leading CAD app takes. */ +export const LINE_SPACING_RANGE = [0.25, 4] as const; + +/** Returns what is wrong with a paragraph's `align`, `valign` or `lineSpacingStyle`, or undefined. */ +export function paragraphChoiceProblem( + field: "align" | "valign" | "lineSpacingStyle", + value: unknown, +): string | undefined { + const values: readonly string[] = + field === "align" + ? PARAGRAPH_ALIGNS + : field === "valign" + ? PARAGRAPH_VERTICAL_ALIGNS + : LINE_SPACING_STYLES; + return values.includes(value as string) + ? undefined + : `${field} must be ${values + .map((v) => JSON.stringify(v)) + .join(", ") + .replace(/, ([^,]*)$/, " or $1")}`; +} + +/** + * Returns what is wrong with a paragraph's line spacing factor, or undefined. The factor as given + * is held to the range, as the type holds it, so none that passes rounds out of it when written. + */ +export function lineSpacingProblem(value: unknown): string | undefined { + return typeof value === "number" && + value >= LINE_SPACING_RANGE[0] && + value <= LINE_SPACING_RANGE[1] + ? undefined + : LINE_SPACING; +} + +/** + * Returns what is wrong with a paragraph's value in its style's font, or undefined: a code + * tsdraft does not know or does not lay out, a brace that is never closed or never opened, a code + * with no `;` to end it, a font that is not one of `FONTS`, italic, bold or `%%c` in an SHX font, + * braces nested past `PARAGRAPH_NESTING`, a control character, and the characters a text cannot + * hold. + */ +export function paragraphValueProblem(value: unknown, font: unknown): string | undefined { + if (typeof value !== "string") return "A paragraph's value must be a string"; + return paragraphProblemIn(parseParagraph(value), font); +} + +/** + * What `paragraphValueProblem` gives for a value already read, in its style's font. A font that + * is not one of `FONTS` has an error of its own, and is not checked here. + */ +export function paragraphProblemIn( + parsed: Pick, + font: unknown, +): string | undefined { + if (parsed.problem !== undefined) return parsed.problem; + const shx = typeof font === "string" && fontInfo(font)?.file.endsWith(".shx") === true; + return parsed.ownDiameter && shx ? PARAGRAPH_SHX_DIAMETER : undefined; +} + /** Returns what is wrong with a layer color, or undefined when it is valid. */ export function layerColorProblem(color: number): string | undefined { return Number.isInteger(color) && color >= 1 && color <= 255 ? undefined : COLOR; diff --git a/src/shape.ts b/src/shape.ts index 919d778..d3a2779 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -18,6 +18,7 @@ import type { Line, LinearDimension, Linetype, + Paragraph, Polyline, Text, TextStyle, @@ -52,6 +53,7 @@ const KINDS = [ "circle", "arc", "text", + "paragraph", "insert", "linear-dimension", "aligned-dimension", @@ -468,6 +470,16 @@ function shapes(all: boolean, typed = all): Shapes { { kind, layer: string, at: point, height: number, value: string, rotation: number }, { ...shared, ...justified }, ), + paragraph: fields( + { kind, layer: string, at: point, height: number, value: string, rotation: number }, + { + ...shared, + ...justified, + width: number, + lineSpacing: number, + lineSpacingStyle: ruled(string), + }, + ), insert: fields( { kind, layer: string, block: ruled(string), at: point }, { id: ruled(string), scale: ruled(scale), rotation: number, attributes: ruled(map(string)) }, diff --git a/src/standard/define.ts b/src/standard/define.ts index 44e920c..f130dea 100644 --- a/src/standard/define.ts +++ b/src/standard/define.ts @@ -835,7 +835,9 @@ function titleBlockDrawing( } } for (const e of block.entities) { - if (e.kind === "text" && e.style !== undefined) styleNames.add(layerKey(e.style)); + if ((e.kind === "text" || e.kind === "paragraph") && e.style !== undefined) { + styleNames.add(layerKey(e.style)); + } if (e.kind !== "insert") continue; const inserted = byName.get(layerKey(e.block)); if (inserted && !blocks.includes(inserted)) blocks.push(inserted); diff --git a/src/standard/lint.ts b/src/standard/lint.ts index b85775d..46b5baa 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -25,6 +25,7 @@ import type { LeaderStyle, Linetype, Point, + Paragraph, Text, TextStyle, Viewport, @@ -40,6 +41,7 @@ import { leaderPicture } from "../leaders.ts"; import { validViewportView, viewReaches } from "../layouts.ts"; import type { Diagnostic, LintRule } from "../lint.ts"; import { inStyle, measureText } from "../measure.ts"; +import { measureParagraph, paragraphInStyle } from "../paragraphs.ts"; import { DEFAULT_PLOT_STYLE_TABLE, paperInfo } from "../papers.ts"; import { idKey, @@ -613,7 +615,7 @@ export function lintStandard( if (where.block === undefined && layerKey(entity.layer) === "0") { say("layer-outside-standard", `${label}: ${DRAWN.layerZero}`, about); } - if (entity.kind === "text" && !roleOf(entity.style)) { + if ((entity.kind === "text" || entity.kind === "paragraph") && !roleOf(entity.style)) { say("text-style-outside-standard", `${label}: ${DRAWN.textWithoutRole}`, about); } if (entity.kind === "leader" && entity.textStyle !== undefined && !roleOf(entity.textStyle)) { @@ -1026,7 +1028,7 @@ export function lintStandard( * more for each 32 characters of its value and its tag, which it is measured and named by. */ const keep = ( - text: Text, + text: Text | Paragraph, styled: Styled | undefined, placement: Placement | undefined, titleBlock: boolean, @@ -1041,7 +1043,9 @@ export function lintStandard( const what = note ? `The line ${shown(text.value)} of its note` : placement === undefined - ? "This text" + ? text.kind === "paragraph" + ? "This paragraph" + : "This text" : tag === undefined ? `The text ${shown(text.value)} of its block` : `The attribute ${shown(tag)} of its block`; @@ -1121,7 +1125,7 @@ export function lintStandard( } return; } - if (entity.kind === "text") { + if (entity.kind === "text" || entity.kind === "paragraph") { if (hidden({ name: walk.layer(entity.layer) })) return; keep(entity, walk.styled(walk.style(entity.style)), undefined, false); return; @@ -1131,7 +1135,9 @@ export function lintStandard( if (placed === undefined || frozen({ name: placed.layer })) return; const titleBlock = standardBlocks.has(walk.key(entity.block)); eachDrawn(placed, walk.blocks(), frozen, (drawn, placement) => { - if (drawn.kind !== "text" || hidden(placement.layer)) return; + if ((drawn.kind !== "text" && drawn.kind !== "paragraph") || hidden(placement.layer)) { + return; + } keep(drawn, walk.styled(drawn.style), placement, titleBlock); }); } catch (thrown) { @@ -1319,18 +1325,24 @@ interface Measured { * box `boxer` gives it there: its capitals, and what its font draws below the baseline. */ function placedText( - text: Text, + text: Text | Paragraph, style: TextStyle | undefined, matrix: Matrix | undefined, ): { readonly height: number; readonly box: Box } { - const { corners, descent } = measureText(inStyle(text, style)); - const [c0, c1, c2, c3] = corners; - const below = descent / text.height || 0; - const points: Point[] = [ - ...corners, - [c0[0] - (c3[0] - c0[0]) * below, c0[1] - (c3[1] - c0[1]) * below], - [c1[0] - (c2[0] - c1[0]) * below, c1[1] - (c2[1] - c1[1]) * below], - ]; + let points: Point[]; + if (text.kind === "paragraph") { + const { corners, frame } = measureParagraph(paragraphInStyle(text, style)); + points = [...(corners ?? frame)]; + } else { + const { corners, descent } = measureText(inStyle(text, style)); + const [c0, c1, c2, c3] = corners; + const below = descent / text.height || 0; + points = [ + ...corners, + [c0[0] - (c3[0] - c0[0]) * below, c0[1] - (c3[1] - c0[1]) * below], + [c1[0] - (c2[0] - c1[0]) * below, c1[1] - (c2[1] - c1[1]) * below], + ]; + } const placed = matrix ? points.map((p) => mapPoint(matrix, p)) : points; const xs = placed.map((p) => p[0]); const ys = placed.map((p) => p[1]); @@ -1441,15 +1453,33 @@ function lettering( ...(text.align === undefined ? {} : { align: text.align }), ...(text.valign === undefined ? {} : { valign: text.valign }), }); - const textOf = (text: Text): Text => ({ - kind: "text", - layer: layer(text.layer), - at: text.at, - height: text.height, - value: text.value, - rotation: text.rotation, - ...justified(text), - }); + const textOf = (text: Text | Paragraph): Text | Paragraph => + text.kind === "paragraph" + ? { + kind: "paragraph", + layer: layer(text.layer), + at: text.at, + height: text.height, + value: text.value, + rotation: text.rotation, + ...(text.style === undefined ? {} : { style: style(text.style)! }), + ...(text.width === undefined ? {} : { width: text.width }), + ...(text.align === undefined ? {} : { align: text.align }), + ...(text.valign === undefined ? {} : { valign: text.valign }), + ...(text.lineSpacing === undefined ? {} : { lineSpacing: text.lineSpacing }), + ...(text.lineSpacingStyle === undefined + ? {} + : { lineSpacingStyle: text.lineSpacingStyle }), + } + : { + kind: "text", + layer: layer(text.layer), + at: text.at, + height: text.height, + value: text.value, + rotation: text.rotation, + ...justified(text), + }; const definitionOf = (definition: AttributeDefinition): AttributeDefinition => ({ tag: definition.tag, value: definition.value, @@ -1465,7 +1495,9 @@ function lettering( const enter = (): Entered => { if (entered) return entered; // What each block holds that can draw a text, and the blocks that insert each. - type Item = { readonly text: Text } | { readonly insert: Insert; readonly block: Block }; + type Item = + | { readonly text: Text | Paragraph } + | { readonly insert: Insert; readonly block: Block }; const held = new Map(); const insertedBy = new Map(); const lettered: Block[] = []; @@ -1483,9 +1515,14 @@ function lettering( let texts = false; for (const e of filled(block.entities)) { const kind = (e as { readonly kind?: unknown } | null | undefined)?.kind; - if ((kind !== "text" && kind !== "insert") || !isSound(TYPED.entity, e, false)) continue; - const entity = e as Text | Insert; - if (entity.kind === "text") { + if ( + (kind !== "text" && kind !== "paragraph" && kind !== "insert") || + !isSound(TYPED.entity, e, false) + ) { + continue; + } + const entity = e as Text | Paragraph | Insert; + if (entity.kind === "text" || entity.kind === "paragraph") { items.push({ text: entity }); texts = true; continue; @@ -1875,7 +1912,9 @@ function closureOf(id: string, titleBlock: StandardTitleBlock): TitleBlockIndex const block = queue[i]!; blocks.set(layerKey(block.name), { name: block.name, json: canonical(block) }); for (const e of block.entities) { - if (e.kind === "text" && e.style !== undefined) styles.add(layerKey(e.style)); + if ((e.kind === "text" || e.kind === "paragraph") && e.style !== undefined) { + styles.add(layerKey(e.style)); + } const linetype = (e as { readonly linetype?: string }).linetype; if (linetype !== undefined) lines.add(layerKey(linetype)); const inner = e.kind === "insert" ? byName.get(layerKey(e.block)) : undefined; diff --git a/src/svg.ts b/src/svg.ts index 4b9a7fd..2bd889b 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -19,6 +19,7 @@ import { type Leader, type LeaderStyle, type Line, + type Paragraph, type Point, type Polyline, type Text, @@ -40,13 +41,20 @@ import { type SideArc, } from "./polylines.ts"; import { boxer, type Boxer } from "./extents.ts"; -import { fontInfo, STANDARD_FONT } from "./fonts.ts"; +import { fontInfo, STANDARD_FONT, capHeightOf } from "./fonts.ts"; import { fmt, written } from "./format.ts"; import { layerKey, layerKeys } from "./layers.ts"; import { findLayout, validViewportView } from "./layouts.ts"; import { leaderPicture, type LeaderPicture } from "./leaders.ts"; import { builtInLinetype, LINEWEIGHTS, lineweightCode } from "./linetypes.ts"; import { drawnValue, inStyle, layoutText } from "./measure.ts"; +import { + paragraphInStyle, + paragraphMeasurer, + paragraphTurn, + placer, + type ParagraphLayout, +} from "./paragraphs.ts"; import { DEFAULT_PLOT_STYLE_TABLE, paperInfo } from "./papers.ts"; import { shown as quoted, turning, viewportProblem } from "./rules.ts"; import { filled } from "./shape.ts"; @@ -484,6 +492,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): pictures.set(e, { style, textStyle, picture }); return picture; }; + /** The layout of each paragraph, a long value laid out once for the picture. */ + const paragraphs = paragraphMeasurer(); /** * The element of an entity that draws something of its own, where `matrix` puts it. Its * dashes stop once they pass the room left in the picture, and `write` then refuses it. @@ -497,6 +507,11 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): matrix?: Matrix, ): string => { const room = longest - length; + if (e.kind === "paragraph") { + const style = styleOf(e, from); + const layout = () => paragraphs.layout(paragraphInStyle(e, style)); + return paragraphToSvg(e, layout, mark, drawnPen, look, matrix, room); + } if (e.kind === "leader") { const tables = tablesOf(from); const style = tables.leaderStyles.get(key(e.style)); @@ -711,6 +726,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): if (!box) return []; const lettered = shown[1].kind === "text" || + shown[1].kind === "paragraph" || shown[1].kind === "insert" || shown[1].kind === "linear-dimension" || shown[1].kind === "aligned-dimension" || @@ -1038,7 +1054,7 @@ export function visibility(drawing: Drawing, drawNoPlot: boolean | undefined) { return layer?.frozen === true || (drawNoPlot !== true && layer?.plot === false); }; const styleOf = (e: Entity, from?: Referenced): TextStyle | undefined => - e.kind === "text" && e.style !== undefined + (e.kind === "text" || e.kind === "paragraph") && e.style !== undefined ? tablesOf(from).textStyles.get(key(e.style)) : undefined; return { tablesOf, layerOf, hidden, frozen, styleOf, key }; @@ -1063,7 +1079,7 @@ function viewOf(view: SvgOptions["view"]): [number, number, number, number] | un type Drawn = Exclude; /** An entity that is one shape, with a linetype and a lineweight it may have of its own. */ -type Shape = Exclude; +type Shape = Exclude; /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ function styled(e: Drawn): Pick { @@ -1155,6 +1171,67 @@ function leaderToSvg( return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } +/** + * A paragraph as a group: each run of each line as a text is drawn, in its font and in bold where + * a code sets it, and its underlines, overlines, strike-throughs and the bars of its stacks as + * lines of its pen, which take no dashes. It stops once it passes `room`, the characters left in + * the picture, longer than the room, which `write` then refuses, and lays nothing out when its + * value alone passes it. + */ +function paragraphToSvg( + e: Paragraph, + layOut: () => ParagraphLayout, + mark: string, + pen: Pen, + look: Look, + matrix: Matrix | undefined, + room: number, +): string { + const place = placer(e); + const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + const parts: string[] = []; + let left = room - e.value.length; + const add = (part: string): void => { + parts.push(part); + left -= part.length; + }; + const layout = left < 0 ? undefined : layOut(); + const { widthFactor = 1, obliqueAngle = 0 } = layout ?? {}; + for (const line of layout?.lines ?? []) { + if (left < 0) break; + for (const run of line.runs) { + if (left < 0) break; + const text: Text = { + kind: "text", + layer: e.layer, + at: place(run.x, run.baseline), + height: run.height, + value: run.value, + rotation: paragraphTurn(e.rotation), + }; + const style: TextStyle = { name: "", font: run.font, widthFactor, obliqueAngle }; + // The run is drawn in its own face, from its first point. + const drawn = { + start: run.start - run.x, + end: run.end - run.x, + advance: run.advance, + bold: run.bold, + }; + add(textToSvg(text, style, pen, `data-part="text"`, matrix, false, drawn)); + } + } + for (const { kind, from, to } of layout?.strokes ?? []) { + if (left < 0) break; + const [a, b] = [at(place(...from)), at(place(...to))]; + add( + ``, + ); + } + const open = ``; + return `${open}>\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; +} + /** * A dimension as a group: its extension lines and its dimension line, which take the dashes * of its pen, its arrowheads, filled, and its text. A dimension whose style the drawing does @@ -1287,34 +1364,70 @@ function entityToSvg( // sweep-flag 1 is the positive-angle direction in local (Y-up) coordinates: counterclockwise. return ``; } - case "text": { - // Undo the group's Y flip so the text reads upright, then apply CAD rotation. - let t = `translate(${fmt(e.at[0])} ${fmt(e.at[1])}) scale(1 -1)${e.rotation ? ` rotate(${fmt(-e.rotation)})` : ""}`; - // An insert's matrix is applied last, so it comes first. - if (matrix) t = `matrix(${matrix.map(fmt).join(" ")}) ${t}`; - const font = fontInfo(style?.font ?? STANDARD_FONT); - const width = style?.widthFactor ?? 1; - const oblique = style?.obliqueAngle ?? 0; - // The text is drawn from where it starts to plot, on its baseline, before the style - // widens or slants it, and held to the length it plots. - const { start, end, baseline } = layoutText(inStyle(e, style)); - if (written(start) !== 0 || written(baseline) !== 0) { - t += ` translate(${fmt(start)} ${fmt(-baseline)})`; - } - // The leading CAD app slants a text after it widens it, so the width factor does not widen - // the lean. The transform applied last comes first. - if (oblique !== 0) t += ` skewX(${fmt(-oblique)})`; - if (width !== 1) t += ` scale(${fmt(width)} 1)`; - // A text's height is the height of its capitals, which a font draws smaller than its size. - const size = e.height / (font?.capHeight ?? SCREEN_CAP_HEIGHT); - const length = written((end - start) / width); - const held = length > 0 ? ` textLength="${length}" lengthAdjust="spacingAndGlyphs"` : ""; - const family = font?.family ?? "monospace"; - // The font by its name in `FONTS`, and empty for a font that is not one of them. - const named = font ? (style?.font ?? STANDARD_FONT) : ""; - return `${esc(drawnValue(e.value))}`; - } + case "text": + return textToSvg(e, style, pen, mark, matrix, true); + } +} + +/** + * A text as an element, drawn from where `layoutText` starts it and held to its length, or, for a + * run of a paragraph, from where its layout starts it, in bold where it is. `decode` draws its + * `%%` codes as the characters they stand for. A bold run's `font-weight` comes before the three + * attributes the command sizes a text by. + */ +function textToSvg( + e: Text, + style: TextStyle | undefined, + pen: Pen, + mark: string, + matrix: Matrix | undefined, + decode: boolean, + run?: { + readonly start: number; + readonly end: number; + readonly advance: number; + readonly bold: boolean; + }, +): string { + // Undo the group's Y flip so the text reads upright, then apply CAD rotation. + let t = `translate(${fmt(e.at[0])} ${fmt(e.at[1])}) scale(1 -1)${e.rotation ? ` rotate(${fmt(-e.rotation)})` : ""}`; + // An insert's matrix is applied last, so it comes first. + if (matrix) t = `matrix(${matrix.map(fmt).join(" ")}) ${t}`; + const named = style?.font ?? STANDARD_FONT; + const font = fontInfo(named); + const width = style?.widthFactor ?? 1; + const oblique = style?.obliqueAngle ?? 0; + // A text is drawn on its baseline, before the style widens or slants it. In a TrueType font it + // is drawn from its first point and held to its characters' advances, as the leading CAD app's + // PDF sets its glyphs; in an SHX font, which plots as strokes, from where it starts to plot and + // held to the length it plots. + const trueType = font?.pitchAndFamily !== undefined; + let start: number; + let end: number; + let baseline = 0; + if (run) [start, end] = trueType ? [0, run.advance] : [run.start, run.end]; + else { + const laid = layoutText(inStyle(e, style)); + const first = laid.end - laid.advance; + [start, end] = trueType ? [first, first + laid.advances] : [laid.start, laid.end]; + baseline = laid.baseline; + } + if (written(start) !== 0 || written(baseline) !== 0) { + t += ` translate(${fmt(start)} ${fmt(-baseline)})`; } + // The leading CAD app slants a text after it widens it, so the width factor does not widen + // the lean. The transform applied last comes first. + if (oblique !== 0) t += ` skewX(${fmt(-oblique)})`; + if (width !== 1) t += ` scale(${fmt(width)} 1)`; + // A text's height is the height of its capitals, which a font draws smaller than its size. + const size = e.height / (capHeightOf(named, run?.bold) ?? SCREEN_CAP_HEIGHT); + const length = written((end - start) / width); + const held = length > 0 ? ` textLength="${length}" lengthAdjust="spacingAndGlyphs"` : ""; + const family = font?.family ?? "monospace"; + const value = decode ? drawnValue(e.value) : e.value; + // The font by its name in `FONTS`, and empty for a font that is not one of them. + const weight = run?.bold ? ` font-weight="bold"` : ""; + return `${esc(value)}`; } /** A circle, or the ellipse an insert that scales unevenly makes of one. */ diff --git a/test/bounded.test.ts b/test/bounded.test.ts index b447a0e..aba3dd8 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -1803,6 +1803,16 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint shafts: [[[0, 0]]], ...fields, }) as unknown as Entity; + const paragraph = (fields: Data): Entity => + ({ + kind: "paragraph", + layer: "0", + at: [0, 0], + height: 1, + value: "N", + rotation: 0, + ...fields, + }) as unknown as Entity; for (let n = 0; n < 16; n++) { const blocks = copies(sheet.blocks); const layout: Data = { @@ -1842,6 +1852,15 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint ), }), leader({ textStyle: long }), + // A paragraph of many lines, of many runs, of one long word, of deep braces, or of numbers + // past what can be drawn. + paragraph({ value: "WORD ".repeat(20_000), width: 1 }), + paragraph({ value: "\\La\\l\\S1/2;".repeat(10_000), width: 0 }), + paragraph({ value: long, width: 0.5, style: "HEADING" }), + paragraph({ value: `${"{".repeat(50_000)}x`, width: 1e99, height: 1e99, rotation: 1e99 }), + // And of a run for each character and of stacks that each end a line. + paragraph({ value: "\\fArial|b1;a\\fArial|b0;b".repeat(4_000), width: 1e-6 }), + paragraph({ value: "\\S1/2; X\\S2^ ; X\\S^2; ".repeat(2_000), width: 1e-6 }), ]); const tree = nested(leaf, depth, width, "T"); // Many lines that no check reads beside one label. @@ -2274,3 +2293,134 @@ test("polylines that share a long list of points, each with lists or a width of assert.ok(Array.isArray(found) || found instanceof RangeError, String(found)); } }); + +test("a paragraph of many lines, runs or braces, a long word and numbers past drawing stay bounded", () => { + const paragraph = (fields: Record): Entity => + ({ + kind: "paragraph", + layer: "0", + at: [0, 0], + height: 1, + value: "N", + rotation: 0, + ...fields, + }) as unknown as Entity; + const hostile = [ + paragraph({ value: "WORD ".repeat(100_000), width: 1 }), + paragraph({ value: "\\La\\l\\S1/2;".repeat(50_000) }), + paragraph({ value: "W".repeat(500_000), width: 0.5 }), + paragraph({ value: `${"{".repeat(250_000)}x`, width: 1e99, height: 1e99, rotation: 1e99 }), + paragraph({ value: "\\".repeat(500_000) }), + paragraph({ value: "\\S".repeat(250_000) }), + paragraph({ value: "A B ".repeat(100_000), width: -1, lineSpacing: 1e300 }), + // A run for each character, bold on and off, and stacks of every kind, of long parts, and + // each ending a line where the spaces after it are dropped. + paragraph({ value: "{\\La}{\\Kb}".repeat(50_000), width: 1e-6 }), + paragraph({ value: "\\fArial|b1;a\\fArial|b0;b".repeat(20_000), width: 2 }), + paragraph({ value: "\\S1/2; X\\S2^ ; X\\S^2; 1\\S1#2; ".repeat(10_000), width: 1e-6 }), + paragraph({ value: `\\S${"1".repeat(200_000)}/${"2".repeat(200_000)};`, width: 1 }), + paragraph({ value: "%".repeat(500_000), lineSpacingStyle: "exactly" }), + paragraph({ value: `\\fArial${"|b0".repeat(200_000)};X` }), + ]; + for (const [i, leaf] of hostile.entries()) { + const d: Drawing = { + ...withModel(nested(leaf, 20, 2)), + entities: [...sheet.entities, leaf, nested(leaf, 20, 2).top], + layouts: [{ ...sheet.layouts![0]!, entities: [...sheet.layouts![0]!.entities, leaf] }], + }; + const fns: [string, () => unknown][] = [ + ["lint", () => lintWithin(d, {}, 20_000)], + ["inspectText", () => inspectWithin(d, {}, 200_000)], + [ + "extents", + () => + boxer( + d.textStyles, + d.blocks, + undefined, + undefined, + undefined, + d.dimensionStyles, + d.leaderStyles, + 20_000, + )(d.entities), + ], + ["toSVG", () => svgWithin(d, {}, 20_000)], + [ + "the PDF of the layout", + () => svgToPDF([svgWithin(d, { layout: "C-101" }, 20_000)], { fonts: embedded }), + ], + ]; + for (const [name, fn] of fns) { + const result = settled(3000, fn); + assert.ok( + !(result instanceof Error) || result instanceof RangeError, + `paragraph ${i}, ${name}: ${String(result)}`, + ); + } + } +}); + +test("a long paragraph value many places share is laid out once in each of its settings, and each other place pays", () => { + const paragraph = (value: string, fields: Record = {}): Entity => + ({ + kind: "paragraph", + layer: "0", + at: [0, 0], + height: 1, + value, + rotation: 0, + ...fields, + }) as unknown as Entity; + const lines = "AB\\P".repeat(20_000); + // The extents map the box of its one layout at each place, whatever its lines. + const boxes = boxer([], [], undefined, undefined, undefined, [], [], 0); + const many = Array.from({ length: 10_000 }, () => paragraph(lines)); + assert.ok(within(1000, () => boxes(many))); + assert.equal(boxes.capped, undefined); + // A layout in other settings lays it out again, and is paid for before it is. + const wide = "HHHH ".repeat(16_000); + for (const settings of [ + (i: number) => ({ height: 1 + i / 1000 }), + (i: number) => ({ width: 10 + i }), + ]) { + const each = Array.from({ length: 200 }, (_, i) => paragraph(wide, settings(i))); + const paying = boxer([], [], undefined, undefined, undefined, [], [], 0); + within(1000, () => paying(each)); + assert.equal(paying.capped, each[1]); + } + // The text checks read its lines again at each place after the first, and pay for them first. + const shared: Drawing = { + ...createDrawing({ units: "ft" }).build(), + entities: Array.from({ length: 128 }, () => paragraph("H\\P".repeat(2000))), + }; + const [stop, ...rest] = within(1000, () => inspectWithin(shared, {}, 1)); + assert.equal(rest.length, 0); + assert.match(stop!.message, /stopped short at entity #1 of model space/); + // One long value at many widths is laid out again at each, and each place after the first + // pays first, by the value's length and by its lines. + for (const value of ["AB ".repeat(12_000), "\\S1/2;".repeat(6_000)]) { + const d: Drawing = { + ...createDrawing({ units: "ft" }).build(), + entities: Array.from({ length: 1000 }, (_, i) => + paragraph(value, { at: [i * 1e5, 0], height: 0.1, width: 1 + i / 1000 }), + ), + }; + const [first] = within(1000, () => inspectWithin(d, {}, value.length - 1)); + assert.match(first!.message, /stopped short at entity #1 of model space/); + const capped = within(1000, () => inspectWithin(d, {}, 300_000)); + assert.equal(capped.at(-1)?.rule, "text-check-capped"); + const boxes = boxer([], [], undefined, undefined, undefined, [], [], value.length - 1); + within(1000, () => boxes(d.entities)); + assert.equal(boxes.capped, d.entities[1]); + assert.ok(settled(1000, () => svgWithin(d, {}, 300_000)) instanceof RangeError); + } + // The lines of a value at a new width are paid for besides its length. + const words = "AB ".repeat(12_000); + const wrapped: Drawing = { + ...createDrawing({ units: "ft" }).build(), + entities: [1, 2].map((width) => paragraph(words, { height: 0.1, width })), + }; + const [paid] = within(1000, () => inspectWithin(wrapped, {}, words.length + 1000)); + assert.match(paid!.message, /stopped short at entity #1 of model space/); +}); diff --git a/test/format.test.ts b/test/format.test.ts index e6ccd59..8ce9031 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -39,7 +39,7 @@ function refusal(value: unknown): readonly Diagnostic[] { return assert.fail("fromJSON took the value"); } -const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "text", "insert", "linear-dimension", "aligned-dimension" or "leader"`; +const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension" or "leader"`; test("a drawing goes to JSON and back unchanged", () => { const drawing = sample(); diff --git a/test/measure.test.ts b/test/measure.test.ts index 29a24e3..f9fa412 100644 --- a/test/measure.test.ts +++ b/test/measure.test.ts @@ -9,6 +9,7 @@ import { type Point, } from "../src/index.ts"; import { extents } from "../src/extents.ts"; +import { fontInfo } from "../src/fonts.ts"; const near = (a: number, b: number): boolean => Math.abs(a - b) < 1e-9; const same = (corners: readonly Point[], expected: readonly Point[]): void => { @@ -23,11 +24,27 @@ test("the width table holds every font, with a number for each character of its const count = FONT_METRICS_RANGES.reduce((sum, [first, last]) => sum + last - first + 1, 0); assert.equal(count, 191); for (const [font, metrics] of Object.entries(FONT_METRICS)) { - for (const table of [metrics.advances, metrics.tails, metrics.heads]) { + const { bold } = metrics; + for (const table of [ + metrics.advances, + metrics.tails, + metrics.heads, + metrics.lefts, + metrics.rights, + metrics.tops, + metrics.bottoms, + ...(bold ? [bold.advances, bold.lefts, bold.rights, bold.tops, bold.bottoms] : []), + ]) { assert.equal(table.length, count, font); assert.ok(table.every(Number.isFinite), font); } assert.ok(metrics.below > 0 && metrics.below < 1, font); + assert.ok(metrics.afterStack > 0 && metrics.afterStack < 1, font); + // A line of paragraph text rises at least a height above its baseline and its box never + // ends above the baseline. + assert.ok(metrics.tops.every((top) => top >= 1) && metrics.bottoms.every((b) => b <= 0), font); + // Only a TrueType font has a bold face. + assert.equal(bold !== undefined, fontInfo(font)?.pitchAndFamily !== undefined, font); } }); @@ -132,6 +149,12 @@ test("a text's box is turned about its point and leans with its oblique angle", [13 + 2 * long, 23], [13, 23], ]); + // It is turned by its rotation as written: one under a millionth of a degree is no turn. + const tall = { value: "HHHH", height: 1e9, font: "Arial" } as const; + assert.deepEqual( + measureText({ ...tall, rotation: 4e-7 }).corners, + measureText({ ...tall, rotation: 0 }).corners, + ); }); test("the extents hold a text's box and what its font draws below the baseline", () => { diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts new file mode 100644 index 0000000..48e79c5 --- /dev/null +++ b/test/paragraphs.test.ts @@ -0,0 +1,470 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import { Script } from "node:vm"; +import { + bold, + createDrawing, + layoutMtext, + layoutParagraph, + lint, + measureMtext, + measureParagraph, + paragraphInStyle, + parseParagraph, + plain, + readDXF, + stack, + subscript, + superscript, + svgToPDF, + toDXF, + toSVG, + underline, + type Drawing, + type Entity, + type Paragraph, +} from "../src/index.ts"; +import { readProblems } from "./read-agreement.ts"; +import { timeLimit } from "./time-limit.ts"; + +const running = new Script("running()"); +/** What `fn` gives, stopped after `ms`, so a run that never ends fails. */ +const within = (ms: number, fn: () => T): T => { + Object.assign(globalThis, { running: fn }); + return running.runInThisContext({ timeout: timeLimit(ms) }) as T; +}; + +/** What a value draws, a piece at a time: characters, `[top, divider, bottom]` and `|` for a break. */ +const drawn = (value: string) => + parseParagraph(value).pieces.map((p) => + p.kind === "characters" ? p.value : p.kind === "stack" ? [p.top, p.separator, p.bottom] : "|", + ); + +test("a paragraph's codes draw what the DXF Reference gives them", () => { + assert.deepEqual(drawn("ONE\\PTWO"), ["ONE", "|", "TWO"]); + assert.deepEqual(drawn("A\\~B \\\\ \\{ \\}"), ["A\u00a0B \\ { }"]); + // %% starts no other code: %%% and %%u draw as they are, and %%%d is a percent and a degree. + assert.deepEqual(drawn("45%%d %%P0.5 %%c6 100%%% %%u %%%d"), ["45° ±0.5 Ø6 100%%% %%u %°"]); + assert.deepEqual(drawn("\\U+00B0\\u+00b1"), ["°±"]); + assert.deepEqual(drawn("3\\S1/2;\\S1#2;\\S+0.1^-0.2;"), [ + "3", + ["1", "/", "2"], + ["1", "#", "2"], + ["+0.1", "^", "-0.2"], + ]); + // A backslash takes the character after it as it is, in a stack's parts. + assert.deepEqual(drawn("\\S1\\/2/3\\;;"), [["1/2", "/", "3;"]]); + const formats = parseParagraph("{\\LU}\\OO\\o\\KK\\k{\\fArial|b1|i0|c0|p34;B}R").pieces.map((p) => + p.kind === "characters" ? [p.value, p.format] : p.kind, + ); + const plainFormat = { + underline: false, + overline: false, + strikeThrough: false, + bold: false, + font: undefined, + }; + assert.deepEqual(formats, [ + ["U", { ...plainFormat, underline: true }], + ["O", { ...plainFormat, overline: true }], + ["K", { ...plainFormat, strikeThrough: true }], + ["B", { ...plainFormat, bold: true, font: "Arial" }], + ["R", plainFormat], + ]); + assert.equal(parseParagraph("{\\fArial|b1;B}\\P\\S2^ ;").problem, undefined); +}); + +test("the helpers write codes that draw their text as given", () => { + assert.deepEqual(drawn(plain("50% \\ {x} %%d %%%P")), ["50% \\ {x} %%d %%%P"]); + assert.deepEqual(drawn(stack("1/2", "3;4", "#")), [["1/2", "#", "3;4"]]); + assert.deepEqual(drawn(superscript("2")), [["2", "^", " "]]); + assert.deepEqual(drawn(subscript("2")), [["", "^", "2"]]); + assert.equal(parseParagraph(`${bold("A", "Arial")}${underline("B")}`).problem, undefined); +}); + +test("what tsdraft does not lay out is refused, and named", () => { + const refused: [string, RegExp][] = [ + ["{A", /never closed/], + ["A}", /closes no \{/], + ["\\H2;A", /code \\H, which sets the height/], + ["\\W0.8;A", /code \\W/], + ["\\Q15;A", /code \\Q/], + ["\\T2;A", /code \\T/], + ["\\A1;A", /code \\A/], + ["\\C1;A", /code \\C, which sets the color/], + ["\\c255;A", /code \\c, which sets the true color/], + ["\\pi-1,l1;A", /code \\p/], + ["A\\NB", /code \\N, which starts a new column/], + ["A\\XB", /code \\X/], + ["\\OA", /code \\O, which draws a line over/], + ["\\M+18140", /code \\M, which holds a character of a code page/], + ["\\Z", /code \\Z is not one tsdraft knows/], + ["\\U+00", /code \\U is not one tsdraft knows/], + ["\\H2", /code \\H has no ; to end it/], + ["\\S1/2", /code \\S has no ; to end it/], + ["\\Ffoo.shx;A", /names the font "foo.shx", which is not one of FONTS/], + ["\\fArial|i1;A", /sets italic/], + ["\\fArial|x;A", /option "x"/], + ["\\fromans.shx|b1;A", /SHX font, which has no bold/], + ["A\\", /ends with a \\/], + ["A\nB", /control characters/], + ["\\U+0009", /control characters/], + ["\ud83d\ude00", /above U\+FFFF/], + ["\ue801", /private-use/], + [`${"{".repeat(17)}A${"}".repeat(17)}`, /nest more than 16 deep/], + ]; + for (const [value, problem] of refused) { + assert.match(parseParagraph(value).problem ?? "", problem, JSON.stringify(value)); + } +}); + +test("a paragraph is read in time in proportion to its value, however it is made", () => { + const values = [ + "{".repeat(4_000_000), + "}".repeat(4_000_000), + "\\".repeat(4_000_000), + "\\S".repeat(2_000_000), + "\\f".repeat(2_000_000), + "\\H".repeat(2_000_000), + "%%".repeat(2_000_000), + "\\fArial|b1;x".repeat(300_000), + "\\S1\\/2/3;".repeat(400_000), + "\\La\\l".repeat(800_000), + ]; + for (const value of values) within(2000, () => parseParagraph(value)); + // And laid out, at a width that breaks every word, at none, and with a word longer than any line. + for (const width of [1e-6, 0, -1, Number.NaN, 1e300]) { + within(3000, () => layoutParagraph({ value: "A BC ".repeat(400_000), height: 1, width })); + } + const long = within(2000, () => + layoutParagraph({ value: "W".repeat(2_000_000), height: 1, width: 1 }), + ); + assert.equal(long.lines.length, 1); +}); + +/** The first point of each run of a paragraph of height 1, from its point, and its value. */ +const runs = (paragraph: Omit[0], "height">) => + layoutParagraph({ ...paragraph, height: 1 }).lines.flatMap((line) => + line.runs.map((run) => [run.value, run.x, run.baseline] as const), + ); + +/** True when `a` and `b` agree to `within`, each number of them. */ +const near = (a: readonly unknown[], b: readonly unknown[], within = 1e-4): boolean => + a.length === b.length && + a.every((value, i) => + Array.isArray(value) + ? near(value, b[i] as unknown[], within) + : typeof value === "number" + ? Math.abs(value - (b[i] as number)) <= within + : value === b[i], + ); + +test("a paragraph is laid out where the leading CAD app sets its lines and runs", () => { + const arial = { font: "Arial" } as const; + const lines = (value: string, width: number, font = "Arial") => + layoutParagraph({ value, height: 1, width, font }).lines.map((line) => line.value); + // A line starts at its first character's ink and ends at its last one's, and keeps the spaces + // it starts with. The width moves no line. + for (const width of [0, 24]) { + assert.ok( + near(runs({ value: "ONE\\PTWO WALLS\\P1 TYP.", width, align: "right", ...arial }), [ + ["ONE", -2.95225, -1.01774], + ["TWO WALLS", -8.30969, -2.70214], + ["1 TYP.", -4.1487, -4.3729], + ]), + ); + } + assert.ok(near(runs({ value: " HHH ", align: "right", ...arial }), [[" HHH", -3.69031, -1]])); + // The next run starts where the last one's ink ends, past its advances. + assert.ok( + near(runs({ value: "{\\fArial|b1;f}H", ...arial }), [ + ["f", -0.01637, -1.01705], + ["H", 0.48977, -1.01705], + ]), + ); + // A word stays when the advances up to it and its ink fit; the first letter's left has no part. + assert.deepEqual(lines("THHH HHHH HHHH", 8.0795), ["THHH HHHH", "HHHH"]); + assert.deepEqual(lines("THHH HHHH HHHH", 8.0765), ["THHH", "HHHH", "HHHH"]); + assert.deepEqual(lines('HHHH 1\\S1/2;" HHHH', 6.2986), ['HHHH 11/2"', "HHHH"]); + assert.deepEqual(lines('HHHH 1\\S1/2;" HHHH', 6.2936), ["HHHH", '11/2" HHHH']); + // No slack beyond the tables' rounding, and no break but at a space: the written width just + // under the reach wraps, and the one just over it does not. + const ink = layoutParagraph({ value: "HHHH HHHH", height: 1, font: "romans.shx" }).lines[0]!; + const reach = ink.end - ink.start; + const [under, over] = [Math.floor(reach * 1e6) / 1e6, Math.ceil(reach * 1e6) / 1e6]; + assert.deepEqual(lines("HHHH HHHH HHHH", under, "romans.shx"), ["HHHH", "HHHH", "HHHH"]); + assert.deepEqual(lines("HHHH HHHH HHHH", over, "romans.shx"), ["HHHH HHHH", "HHHH"]); + assert.deepEqual(lines("HHHH\\~HHHH HHHH", 1), ["HHHH HHHH", "HHHH"]); + assert.deepEqual(lines("WATER-PROOFING", 1), ["WATER-PROOFING"]); + // At least: each line's slot is the factor times its A, D and a third, from its top. + const baselines = ( + value: string, + lineSpacing: number, + lineSpacingStyle: "at-least" | "exactly" = "at-least", + ) => + layoutParagraph({ value, height: 1, ...arial, lineSpacing, lineSpacingStyle }).lines.map( + (line) => line.baseline, + ); + for (const factor of [0.5, 1, 1.5, 2]) { + assert.ok(near(baselines("HHH\\PHHH", factor), [-1, -1 - (5 / 3) * factor])); + } + assert.ok(near(baselines("HHH\\P\u00c5\u00c9\u00ce\\PHHH", 1), [-1, -2.9191, -4.5858])); + assert.ok(near(baselines("1\\S1/2;\\PHHH", 1), [-2.3415, -2.6748 - 1])); + // Exactly: 5/3 of the height times the factor apart, the first a height below the top. + assert.ok( + near(baselines("HHH\\P\u00c5\u00c9\u00ce\\PHHH", 2, "exactly"), [-1, -13 / 3, -23 / 3]), + ); + // The box ends at the last line's ink below its baseline. + assert.ok( + near(runs({ value: "HHH\\PHgy", valign: "bottom", ...arial }), [ + ["HHH", -0.11187, 1.96066], + ["Hgy", -0.11187, 0.294], + ]), + ); + // A superscript is a third of a height up, and a fraction's bar a sixth below its top part. + assert.ok( + near( + runs({ value: "X\\S2^ ;", ...arial }), + [ + ["X", -0.00614, -1.33811], + ["2", 0.88472, -1.00409], + [" ", 0.92565, -1.33811], + ], + 1e-3, + ), + ); + const fraction = layoutParagraph({ value: '1\\S1/2;"', height: 1, ...arial }); + assert.ok(near(fraction.strokes[0]!.from, [0.6248, -1.1708])); + assert.ok(near(fraction.strokes[0]!.to, [1.2872, -1.1708])); + assert.ok( + near( + fraction.lines[0]!.runs.map((run) => run.x), + [-0.15208, 0.61968, 0.58392, 1.354], + ), + ); + // A slash stack raises its top part a digit's top, and centers the slash at its bottom part's. + const slash = layoutParagraph({ value: "\\S1#A;", height: 1, ...arial }); + assert.ok( + near( + slash.lines[0]!.runs.map((run) => run.baseline), + [-1.00409, -2.00819], + ), + ); + const [from, to] = [slash.strokes[0]!.from, slash.strokes[0]!.to]; + assert.ok(near([(from[1] + to[1]) / 2], [-1.00819])); + // An underline lies at the descent of a TrueType font and a fifth of a height in an SHX font. + for (const [font, below] of [ + ["Arial", -0.29604], + ["romans.shx", -0.2], + ] as const) { + const [line] = layoutParagraph({ value: "\\LHHHH\\l HH", height: 1, font }).strokes; + assert.ok(near([line!.from[1] - -1], [below]), font); + } +}); + +test("what the tables cannot lay out exactly is approximate, or refused", () => { + const approximate = (value: string, font: string, obliqueAngle = 0) => + layoutParagraph({ value, height: 1, font, obliqueAngle }).approximate; + assert.equal(approximate("H%%cH", "Arial"), false); + assert.equal(approximate("H%%cH", "romans.shx"), true); + assert.equal(approximate("H\u00d8H", "romans.shx"), false); + assert.equal(approximate("ONE", "romans.shx", 15), true); + assert.equal(approximate("ONE", "Arial", 15), false); + assert.equal(approximate("1\\S1/2;", "Arial"), false); + assert.equal(approximate("1\\S1/2;", "Times New Roman"), true); + for (const value of ["\\Sx/y;", "\\S1/2a;", "\\S+/1;", "\\S 1/2;", "\\S1/2/3;"]) { + assert.match(parseParagraph(value).problem ?? "", /stacked part/, value); + } + for (const value of ["\\S1/2;", "\\S+0.01^-0.02;", "\\S2^ ;", "\\S^2;", "\\SAB#CD;"]) { + assert.equal(parseParagraph(value).problem, undefined, value); + } + assert.match(parseParagraph("\\OOVER").problem ?? "", /code \\O, which draws a line over/); + assert.match(parseParagraph("\\L1\\S1/2;").problem ?? "", /stack in underlined/); + assert.equal(parseParagraph("{\\L1}\\S1/2;").problem, undefined); +}); + +/** A drawing with one paragraph of these fields, as data. */ +function holding(fields: Record, dxf: "R12" | "R2018" = "R2018"): Drawing { + const paragraph = { + kind: "paragraph", + layer: "0", + at: [0, 0], + height: 0.1, + rotation: 0, + value: "NOTE", + ...fields, + }; + return { ...createDrawing({ dxf }).build(), entities: [paragraph as unknown as Entity] }; +} + +test("lint refuses a paragraph built as data that the leading CAD app would not take as written", () => { + const errors = (drawing: Drawing) => + lint(drawing) + .filter((d) => d.severity === "error") + .map((d) => `${d.rule}: ${d.message}`); + assert.deepEqual(errors(holding({})), []); + assert.deepEqual(errors(holding({}, "R12")), [ + 'paragraph: paragraph #0: tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph', + ]); + const refused: [Record, RegExp][] = [ + [{ value: "A\nB" }, /^paragraph: .*control characters/], + [{ value: "\\H2;A" }, /^paragraph: .*code \\H/], + [{ lineSpacing: 5 }, /^paragraph: .*from 0.25 to 4/], + [ + { lineSpacingStyle: "loose" }, + /^paragraph: .*lineSpacingStyle must be "at-least" or "exactly"/, + ], + [{ align: "justified" }, /^text-align: .*align must be "left", "center" or "right"/], + [{ valign: "baseline" }, /^text-align: .*valign must be "top", "middle" or "bottom"/], + [{ width: 0 }, /^geometry: .*width: This value must be greater than 0/], + [{ height: -1 }, /^geometry: .*height: This value must be greater than 0/], + [{ style: "NOTES" }, /^undefined-text-style: /], + // An SHX font draws %%c as a sign of its own, which is not laid out yet: the style's or one a + // code sets. + [{ value: "%%c6" }, /^paragraph: .*%%c in an SHX font/], + [{ value: "\\fArial;\\fromans.shx;%%c6" }, /^paragraph: .*%%c in an SHX font/], + ]; + for (const [fields, problem] of refused) { + const found = errors(holding(fields)); + assert.ok( + found.some((e) => problem.test(e)), + `${JSON.stringify(fields)}: ${found.join("; ")}`, + ); + } + // A TrueType font keeps it. + const arial = { textStyles: [{ name: "NOTES", font: "Arial" }] }; + assert.deepEqual(errors({ ...holding({ value: "%%c6", style: "NOTES" }), ...arial }), []); + assert.deepEqual(errors(holding({ value: "\\fArial;%%c6" })), []); +}); + +test("readDXF gives back each paragraph as toDXF wrote it, in model space, a block and a layout", async () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "NOTES", font: "Arial" }); + const long = Array.from({ length: 80 }, (_, i) => `WORD${i} ^ CARET`).join(" "); + d.paragraph( + `${bold("NOTES", "Arial")}\n1. ${underline("ALL")} WORK 3${stack("1", "2")}" \\U+00B0 %%d`, + { + at: [0, 0], + width: 2, + height: 0.1, + style: "NOTES", + align: "right", + valign: "bottom", + rotation: 15, + lineSpacing: 1.25, + lineSpacingStyle: "exactly", + id: "notes", + }, + ); + d.paragraph(long, { at: [0, -2], width: 4 }); + d.block("TAG", {}, () => d.paragraph("TAG", { at: [0, 0], align: "center", valign: "middle" })); + d.insert("TAG", [5, 5]); + d.layout("SHEET", { paper: "ARCH D" }, () => + d.paragraph(long, { at: [1, 20], width: 6, height: 0.125 }), + ); + const drawing = d.build(); + const read = await readDXF(toDXF(drawing), { geometry: true }); + assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); + const mtexts = read.model.entities!.filter((e) => e.kind === "mtext"); + assert.equal(mtexts.length, 2); + assert.equal(mtexts[1]!.kind === "mtext" && mtexts[1]!.value, long); +}); + +test("a paragraph is laid out from its numbers as written, as a read of the file lays it out", async () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "NOTES", font: "Arial" }); + // Each is within the writers' rounding of where its second word wraps. + d.paragraph("HHHH HHHH", { at: [0, 0], height: 1, width: 8.234652113580001, style: "NOTES" }); + d.paragraph("HHHH HHHH", { at: [0, 5], height: 0.1000004, width: 0.823466, style: "NOTES" }); + const drawing = d.build(); + const read = await readDXF(toDXF(drawing), { geometry: true }); + const style = read.textStyles.find((s) => s.name === "NOTES"); + const mtexts = read.model.entities!.filter((e) => e.kind === "mtext"); + assert.deepEqual( + mtexts.map((m) => layoutMtext(m, style).lines.length), + [2, 1], + ); + drawing.entities.forEach((e, i) => { + const laid = layoutParagraph(paragraphInStyle(e as Paragraph, drawing.textStyles![0])); + assert.deepEqual(laid.lines, layoutMtext(mtexts[i]!, style).lines); + }); +}); + +test("a paragraph is placed in the direction the DXF holds: its rotation within a turn, as written", async () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "NOTES", font: "Arial" }); + const rotations = [8571234567891230000, 400.5, -30, 4e-7, 359.9999996]; + for (const [i, rotation] of rotations.entries()) { + d.paragraph("HHHH", { at: [0, 10 * i], height: 1e9, rotation, style: "NOTES" }); + } + const drawing = d.build(); + const read = await readDXF(toDXF(drawing), { geometry: true }); + const style = read.textStyles.find((s) => s.name === "NOTES"); + const mtexts = read.model.entities!.filter((e) => e.kind === "mtext"); + drawing.entities.forEach((e, i) => { + const placed = measureParagraph(paragraphInStyle(e as Paragraph, drawing.textStyles![0])); + assert.deepEqual(placed.lines, measureMtext(mtexts[i]!, style).lines, String(rotations[i])); + }); + assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); +}); + +test("a run and a text in a TrueType font are plotted from their first point at their advances", () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "NOTES", font: "Arial" }); + // An "f" reaches past its advance, which stretches no glyph: the leading CAD app plots 100 Tz. + d.layout("SHEET", { paper: "ARCH D" }, () => { + d.paragraph("f {\\Lf}", { at: [1, 20], height: 1, style: "NOTES" }); + d.text([1, 10], "f", { height: 1, style: "NOTES" }); + }); + const picture = toSVG(d.build(), { layout: "SHEET" }); + const page = new TextDecoder("latin1").decode(svgToPDF([picture])); + assert.deepEqual( + [...page.matchAll(/(\S+) Tz/g)].map((m) => m[1]), + ["100", "100", "100"], + ); +}); + +test("a bold run is drawn bold, and plotted in a bold face or the bold file given", () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "NOTES", font: "Arial" }); + d.layout("SHEET", { paper: "ARCH D" }, () => + d.paragraph(`${bold("BOLD", "Arial")} REGULAR`, { at: [1, 20], height: 0.125, style: "NOTES" }), + ); + const drawing = d.build(); + const picture = toSVG(drawing, { layout: "SHEET" }); + assert.equal(picture.match(/font-weight="bold"/g)?.length, 1); + const text = (bytes: Uint8Array) => new TextDecoder("latin1").decode(bytes); + const faces = text(svgToPDF([picture])); + assert.ok(faces.includes("/BaseFont /Helvetica-Bold") && faces.includes("/BaseFont /Helvetica ")); + const font = new Uint8Array( + readFileSync(new URL("../cli/assets/fonts/JetBrainsMono-Regular.ttf", import.meta.url)), + ); + const embedded = text(svgToPDF([picture], { fonts: { "Arial Bold": font } })); + assert.ok(!embedded.includes("/BaseFont /Helvetica-Bold") && embedded.includes("/FontFile2")); +}); + +test("under a standard a paragraph is held to its role's text style and height, as a text is", async () => { + const { default: sheet, standard } = await import("../examples/site-plan.ts"); + assert.deepEqual( + lint(sheet, { standard }).filter((d) => d.severity === "error"), + [], + ); + const [layout] = sheet.layouts!; + const at = layout!.entities.findIndex((e) => e.kind === "paragraph"); + const changed = (fields: Record): Drawing => ({ + ...sheet, + layouts: [ + { + ...layout!, + entities: layout!.entities.map((e, i) => (i === at ? ({ ...e, ...fields } as Entity) : e)), + }, + ], + }); + const rules = (drawing: Drawing) => + lint(drawing, { standard }) + .filter((d) => d.severity === "error" && d.entity === at) + .map((d) => d.rule); + assert.deepEqual(rules(changed({ height: 0.2 })), ["height-off-role"]); + assert.deepEqual(rules(changed({ style: undefined })), ["text-style-outside-standard"]); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index fab53d1..06a0f87 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -19,6 +19,7 @@ import { idHandle } from "../src/handles.ts"; import { findLeaderStyle, leaderPicture } from "../src/leaders.ts"; import { layerKey } from "../src/layers.ts"; import { entityLinetype, lineweightCode } from "../src/linetypes.ts"; +import { paragraphAttachment, paragraphTurn } from "../src/paragraphs.ts"; import { textOnce, textTwice } from "../src/read/groups.ts"; import type { DrawingRead, @@ -291,6 +292,33 @@ export function readProblems( start(got, mine, got.value, label); return; } + case "paragraph": { + if (!kind("mtext") || got.kind !== "mtext") return; + const style = styleOf(want.style); + // A DWG keeps a `\U+XXXX` as written, where a DXF's reader decodes it. + if (got.value !== once(want.value) && got.value !== want.value) { + say(`${label}: reads ${JSON.stringify(got.value)}`); + } + if (!sameName(got.style, style?.name ?? want.style ?? "Standard")) { + say(`${label}: style ${got.style}`); + } + if (!nearPoint(got.at, point(want.at))) say(`${label}: at ${got.at}`); + for (const [what, a, b] of [ + ["height", got.height, written(want.height)], + ["width", got.width, written(want.width ?? 0)], + ["attachment", got.attachment, paragraphAttachment(want)], + ["line spacing", got.lineSpacing, written(want.lineSpacing ?? 1)], + ] as const) { + if (!near(a, b)) say(`${label}: ${what} ${a}, expected ${b}`); + } + if (got.lineSpacingStyle !== (want.lineSpacingStyle ?? "at-least")) { + say(`${label}: line spacing ${got.lineSpacingStyle}`); + } + // Its direction is written with 15 digits, which give its turn back within their rounding. + const turned = (((got.rotation - paragraphTurn(want.rotation)) % 360) + 360) % 360; + if (Math.min(turned, 360 - turned) > 1e-9) say(`${label}: turned ${got.rotation}`); + return; + } case "insert": { if (!kind("insert") || got.kind !== "insert") return; const block = blocks.get(layerKey(want.block)); diff --git a/test/read.test.ts b/test/read.test.ts index 42ef4dd..d8a5427 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -1026,7 +1026,8 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only [8, "A"], [10, "1e999"], ], - // The leading CAD app leaves out a measurement of 1, and a rotation in radians may be any number. + // The leading CAD app leaves out a measurement of 1, and a rotation may be any number. It + // reads an MTEXT's group 50 as degrees. [ [0, "DIMENSION"], [8, "A"], @@ -1038,15 +1039,22 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only [50, "1e308"], [1, "M"], ], + [ + [0, "MTEXT"], + [8, "A"], + [50, "390"], + [1, "M"], + ], ), [0, "EOF"], ]), { geometry: true }, ); assert.deepEqual(checkDrawingRead(plain(read)), []); - const [own, plainLine, dimension, mtext] = read.model.entities!; + const [own, plainLine, dimension, mtext, turned] = read.model.entities!; assert.equal(dimension?.kind === "dimension" && dimension.measurement, 1); assert.ok(mtext?.kind === "mtext" && mtext.rotation >= 0 && mtext.rotation < 360); + assert.equal(turned?.kind === "mtext" && turned.rotation, 30); assert.deepEqual( [own?.linetype, own?.color, own?.trueColor, own?.lineweight, own?.linetypeScale], ["DASHED", 0, 0xff0000, 35, 2.5], diff --git a/test/rules.test.ts b/test/rules.test.ts index 2a7d7bf..4c9f601 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -1254,3 +1254,82 @@ test("a polyline's width, radius and arcs, a cloud's arc and a donut's hole are // @ts-expect-error: R12 holds no donut, which is a polyline of arcs. assert.throws(() => r12.donut([0, 0], 1), /no arcs or widths/); }); + +test("a paragraph's height, width, line spacing and codes are checked twice", () => { + const d = createDrawing(); + const r12 = createDrawing({ dxf: "R12" }); + const at: Point = [0, 0]; + // @ts-expect-error: a height must be greater than 0. + assert.throws(() => d.paragraph("NOTE", { at, height: 0 }), /greater than 0/); + // @ts-expect-error: a width must be greater than 0. + assert.throws(() => d.paragraph("NOTE", { at, width: -1 }), /greater than 0/); + // @ts-expect-error: a width that rounds to 0 is written as 0, which wraps nothing. + assert.throws(() => d.paragraph("NOTE", { at, width: 1e-7 }), /written as 0/); + // @ts-expect-error: the leading CAD app takes a line spacing from 0.25 to 4. + assert.throws(() => d.paragraph("NOTE", { at, lineSpacing: 0.2 }), /from 0.25 to 4/); + // @ts-expect-error: the leading CAD app takes a line spacing from 0.25 to 4. + assert.throws(() => d.paragraph("NOTE", { at, lineSpacing: 4.5 }), /from 0.25 to 4/); + // @ts-expect-error: a factor is held to the range as given, so none rounds into it when written. + assert.throws(() => d.paragraph("NOTE", { at, lineSpacing: 0.2499999 }), /from 0.25 to 4/); + // @ts-expect-error: nor out of it. + assert.throws(() => d.paragraph("NOTE", { at, lineSpacing: 4.0000004 }), /from 0.25 to 4/); + d.paragraph("NOTE", { at, lineSpacing: 0.25 }).paragraph("NOTE", { at, lineSpacing: 4 }); + // @ts-expect-error: a brace is never closed. + assert.throws(() => d.paragraph("{\\LNOTE", { at }), /never closed/); + // @ts-expect-error: a brace closes nothing. + assert.throws(() => d.paragraph("NOTE}", { at }), /closes no \{/); + // @ts-expect-error: a height inside the value is not laid out yet. + assert.throws(() => d.paragraph("\\H2x;NOTE", { at }), /code \\H, which sets the height/); + // @ts-expect-error: nor are a paragraph's indents and tab stops. + assert.throws(() => d.paragraph("\\pxi-3,l3;NOTE", { at }), /code \\p, which sets the indents/); + // @ts-expect-error: nor is a tab. + assert.throws(() => d.paragraph("1.\tNOTE", { at }), /control characters/); + // @ts-expect-error: nor are columns. + assert.throws(() => d.paragraph("ONE\\NTWO", { at }), /code \\N, which starts a new column/); + // @ts-expect-error: a code tsdraft does not know. + assert.throws(() => d.paragraph("\\ZNOTE", { at }), /code \\Z is not one tsdraft knows/); + // @ts-expect-error: a font with no ; to end it. + assert.throws(() => d.paragraph("\\fArial|b1NOTE", { at }), /no ; to end it/); + // @ts-expect-error: a font that is not one of FONTS. + assert.throws(() => d.paragraph("\\fHelvetica;NOTE", { at }), /not one of FONTS/); + // @ts-expect-error: tsdraft has no widths for italic. + assert.throws(() => d.paragraph("\\fArial|b0|i1;NOTE", { at }), /sets italic/); + // @ts-expect-error: a font's option has digits alone after its letter, as the parser reads it. + assert.throws(() => d.paragraph("\\fArial|c-1;NOTE", { at }), /option "c-1"/); + // @ts-expect-error: and gives each option once. + assert.throws(() => d.paragraph("\\fArial|b1|b0;NOTE", { at }), /option b twice/); + d.paragraph("\\fArial|b0|c01|p34;NOTE", { at }); + // @ts-expect-error: an SHX font has no bold. + assert.throws(() => d.paragraph("\\ftxt.shx|b1;NOTE", { at }), /SHX font, which has no bold/); + // @ts-expect-error: a stack needs a divider. + assert.throws(() => d.paragraph("3\\S12;", { at }), /needs a \/, # or \^/); + // @ts-expect-error: nor is an overline. + assert.throws(() => d.paragraph("\\ONOTE", { at }), /code \\O, which draws a line over/); + // @ts-expect-error: nor is a stacked part of letters whose tops the tables do not hold. + assert.throws(() => d.paragraph("\\Sx/y;", { at }), /stacked part/); + // @ts-expect-error: nor is a stack in underlined text. + assert.throws(() => d.paragraph("{\\L1\\S1/2;}", { at }), /stack in underlined/); + // @ts-expect-error: and a slash after the divider is a character of the bottom part. + assert.throws(() => d.paragraph("\\S1/2/3;", { at }), /stacked part/); + const deep = "{{{{{{{{{{{{{{{{{x}}}}}}}}}}}}}}}}}"; + // @ts-expect-error: braces nest at most 16 deep. + assert.throws(() => d.paragraph(deep, { at }), /nest more than 16 deep/); + // An SHX font draws %%c as a sign of its own, which is not laid out yet. The type does not know + // the style's font. + assert.throws(() => d.paragraph("%%c6", { at }), /%%c in an SHX font/); + d.textStyle({ name: "NOTES", font: "Arial" }); + // @ts-expect-error: but it knows one a code names, as far as its group reaches. + assert.throws(() => d.paragraph("\\fromans.shx;%%c6", { at }), /%%c in an SHX font/); + // @ts-expect-error: a group inside it in another font closes back to the SHX one. + assert.throws(() => d.paragraph("\\Fromans.shx;{\\fArial;x}%%C6", { at }), /%%c in an SHX/); + d.paragraph("{\\fromans.shx;x}%%c6 {\\fromans.shx;{\\fArial;%%c6}}", { at, style: "NOTES" }); + // @ts-expect-error: a backslash before a line feed would escape the paragraph break. + assert.throws(() => d.paragraph("A\\\nB", { at }), /code \\\n is not one tsdraft knows/); + d.paragraph("A\\\\\nB", { at, style: "NOTES" }); + // A line feed is a paragraph break, and the codes tsdraft lays out pass. + const laid = + "{\\fArial|b1;NOTES}\n1. {\\LALL} WORK\\~%%d %%c %%% 100%% \\S1/2; \\S+0.01^-0.02; \\S2^ ; \\S^2; \\U+00B0 \\\\"; + d.paragraph(laid, { at, width: 2, style: "NOTES" }); + // @ts-expect-error: R12 holds no paragraph. + assert.throws(() => r12.paragraph("NOTE", { at }), /no paragraphs to R12/); +}); diff --git a/test/shape.test.ts b/test/shape.test.ts index 1000fe2..e8ff3bd 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -82,6 +82,22 @@ const kinds: { ...styled, ...justified, }, + paragraph: { + kind: "paragraph", + layer: "0", + at: [0, 8], + height: 0.5, + rotation: 15, + value: 'ALL WORK SHALL {\\LCOMPLY}\\P3\\S1/2;" GAP', + width: 6, + style: "NOTES", + align: "center", + valign: "bottom", + lineSpacing: 1.5, + lineSpacingStyle: "exactly", + id: "k", + ...styled, + }, insert: { kind: "insert", layer: "0", @@ -489,7 +505,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #9: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #10: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ From b77731e763ea1d560d4fde99e30158edfef2a098 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 19 Nov 2026 19:45:59 -0500 Subject: [PATCH 05/35] Dimension styles: stacked fractions, words below the line, text in a break or on a leader, and tick weights A dimension style now sets how its dimensions look, and each dimension is drawn as the leading CAD app draws it: - `fraction: "stacked"` or `"diagonal"` stacks the fraction of a feet-and-inch measurement, at `fractionScale` of the text's height, as `4'-1` and a stacked `7/16`. - `textPlacement: "centered"` puts the text in a break of the dimension line. - `textFit: "leader"` moves a text with no room between the extension lines out on a leader. - `dimensionLineweight` and `extensionLineweight` set the pens. The arrowhead `"oblique"` is a thin tick. - A dimension's `textBelow` writes words under its line, such as `WINDOW HEAD HT.` under `6'-8"`. `dimensionPicture` takes the dimension style's text style. It sets each text's box from the top of its tallest letter or stack to the foot of its lowest. Ticks turn outward where the text does not fit, and the dimension line is drawn in pieces. `toSVG`, the plot, the extents and `inspectText` draw each text as the paragraph the file holds, stacks included. A stack in a dimension's text sits with its bar, or the middle of its slash, half a height over the line. `lint` refuses a value outside each field's list and a stacked fraction outside architectural units. It also refuses what is not laid out yet: - a text centered in a line it is wider than - words below a text that moves out - a leader beside arrowheads twice the text's height - closed filled arrowheads round a centered text with a leader Closed filled arrowheads need room for the wider of the texts above and below the line, with a stacked fraction counted as its longer part, and for the text as tsdraft lays it out where that is wider. Round a text centered in the line they need room for the text and both arrowheads, as the leading CAD app turns them outward otherwise. `readDXF` reads a dimension's words below into `textBelow`, and reads a dimension style's new settings and its arrowheads' block. The built-in standard is now version 2. It adds the dimension style `arrows`: closed filled arrows with the text centered. A standard's dimension style takes the new fields, with `fraction` and `fractionScale` in its writing. A stacked part of a paragraph now stands by its own ink, as the leading CAD app sets it, from the font tables' new column `stackTops`. A slash stack stands its top part on its bottom part's ink. No other number in the tables changed. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 24 + GUIDE.md | 10 +- README.md | 6 +- docs/assets/outdoor-kitchen-dark.svg | 40 +- docs/assets/outdoor-kitchen-light.svg | 40 +- docs/assets/plan-set-A-101-dark.svg | 541 ++++++++++++--------- docs/assets/plan-set-A-101-light.svg | 541 ++++++++++++--------- docs/assets/plan-set-A-201-dark.svg | 660 +++++++++++++++----------- docs/assets/plan-set-A-201-light.svg | 660 +++++++++++++++----------- docs/assets/site-plan-dark.svg | 47 +- docs/assets/site-plan-light.svg | 47 +- docs/dimensions.md | 130 +++-- docs/format.md | 6 +- docs/reading.md | 5 +- docs/rules.md | 7 +- docs/standard.md | 13 +- examples/site-plan.ts | 4 +- scripts/readme-drawing.ts | 20 +- src/arrowheads.ts | 23 +- src/dimensions.ts | 361 ++++++++++++-- src/drawing.ts | 93 +++- src/dxf-r2018.ts | 118 +++-- src/extents.ts | 37 +- src/font-metrics.ts | 527 ++++++++++++++++++++ src/index.ts | 12 + src/inspect.ts | 50 +- src/lint.ts | 11 +- src/paragraph-codes.ts | 26 +- src/paragraphs.ts | 103 +++- src/read/check.ts | 9 + src/read/dxf.ts | 31 +- src/read/entities.ts | 6 +- src/read/model.ts | 32 ++ src/rules.ts | 109 ++++- src/shape.ts | 10 +- src/standard/default.ts | 17 +- src/standard/define.ts | 2 +- src/standard/document.ts | 19 + src/standard/lint.ts | 6 + src/standard/literal.ts | 25 +- src/standard/shape.ts | 48 +- src/svg.ts | 65 ++- standard.json | 62 ++- standard.schema.json | 75 ++- test/bounded.test.ts | 18 + test/dimensions.test.ts | 159 ++++++- test/paragraphs.test.ts | 8 +- test/read-agreement.ts | 11 +- test/shape.test.ts | 14 +- test/standard.test.ts | 8 +- 50 files changed, 3556 insertions(+), 1340 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebdf93f..901e261 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,30 @@ ## Unreleased +- What a dimension style sets of how its dimensions look. In architectural units, `fraction` + stacks the fraction of an inch over a bar, `"stacked"`, or beside a slash, `"diagonal"`, at + `fractionScale` of the text's height, as `4'-1` and a stacked `7/16`. `textPlacement: + "centered"` puts the text in a break of the dimension line, and `textFit: "leader"` moves a text + with no room between the extension lines out on a leader. `dimensionLineweight` and + `extensionLineweight` set the pens of the dimension line and of the extension lines, and the + arrowhead `"oblique"` is a thin tick. A dimension's `textBelow` writes words under its line, as + `WINDOW HEAD HT.` under `6'-8"`. `dimensionPicture` draws each as the leading CAD app does: the + text's box from the top of its tallest letter or stack to the foot of its lowest, ticks that + turn outward where the text does not fit, the line in pieces, and the leader. It takes the + dimension style's text style. `lint` and the builder refuse a value outside each field's list, + a stacked fraction outside architectural units, and what is not laid out yet: a text centered + in a line it is wider than, words below a text that moves out, a leader beside arrowheads twice + the text's height, and closed filled arrowheads round a centered text with a leader. + `readDXF` reads a dimension's words below into `textBelow`, and a dimension style's + `textVertical`, `textInside`, `textMove`, `fraction`, `fractionScale`, lineweights and + arrowheads' block. The built-in standard, version 2, adds the dimension style `arrows`, with + closed filled arrows and the text centered, and a standard's dimension style takes the new + fields, with `fraction` and `fractionScale` in its writing. +- A stacked part of a paragraph stands by its own ink, top less bottom, as the leading CAD app sets + it, from the font tables' new column `stackTops`: a 7 over a 16 stands lower than a capital. + A slash stack stands its top part on its bottom part's ink, and its gap is not widened with + the letters. Every other number of the tables is as it was. + - `readDXF` leaves out of a block's and a space's `entities` an entity the file marks invisible, group 60, and counts it under `other` as `invisible`. A dynamic block's definition and each `*U` block that holds one of its states keep the entities of every state, with those of the states diff --git a/GUIDE.md b/GUIDE.md index a4290f3..ea9f3e5 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -363,7 +363,12 @@ d.linearDimension([24, 30], [76, 30], [0, 20], { style: "PLAN" }); - CAD writes the measurement. `text: "<> TYP"` adds to it. - `units: "architectural"` writes feet and inches, as `4'-1 7/16"`, from a length in inches times `measurementScale`, so give a drawing in feet `measurementScale: 12`. `precision` is - then the least fraction: 4 for 1/16". Never write feet and inches as a dimension's `text`. + then the least fraction: 4 for 1/16". `fraction: "stacked"` stacks the fraction, at + `fractionScale` of the text's height. Never write feet and inches as a dimension's `text`. +- `textBelow: "WINDOW HEAD HT."` writes words under the line. `textPlacement: "centered"` puts + the text in a break of the line, `textFit: "leader"` moves a text with no room out on a + leader, `arrowhead: "oblique"` draws a thin tick, and `dimensionLineweight` and + `extensionLineweight` set the pens. - Never draw a dimension from lines and text. [docs/dimensions.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/dimensions.md) has the rest. @@ -587,8 +592,7 @@ writeFileSync("plan.dxf", toDXF(drawing)); ## What tsdraft cannot draw yet -- Hatches, fills, and dimensions that are not linear or aligned. A fraction of an inch in a - dimension is on the line, as `1 7/16`, not stacked. +- Hatches, fills, and dimensions that are not linear or aligned. - A leader with two roots, a curved shaft, a block in place of its note, or a note attached at its top or bottom. - A block read from another file. A block is drawn in the drawing that inserts it. An xref diff --git a/README.md b/README.md index 624e7da..a321849 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,9 @@ d.linearDimension([34, 30], [86, 30], [0, 22], { style: "PLAN" }); // 52.0' ``` `alignedDimension` measures along the two points, and a style with `units: "architectural"` -writes feet and inches, as `4'-1 7/16"`. [Dimensions](docs/dimensions.md) has the rest. +writes feet and inches, as `4'-1 7/16"`, with the fraction on the line or stacked. A style puts +the text above the line or in a break of it and moves a text with no room out on a leader, and +a dimension takes words below its line. [Dimensions](docs/dimensions.md) has the rest. A layout is a sheet of paper that a CAD program shows as a tab and plots as one page. What is drawn inside `layout` is on the sheet, in inches of paper, and a viewport shows the model on it at a @@ -244,7 +246,7 @@ It draws layers, lines, polylines with arcs and widths, rectangles, revision clo circles, arcs, single-line text and paragraph text that wraps to a width, with linetypes and lineweights, text styles and justification, blocks with attributes and inserts of them, references to DWG files as xrefs, linear and aligned dimensions in decimal units or -feet and inches, leaders, layouts with a page setup and viewports, which can freeze their own +feet and inches with stacked fractions, words below the line and text on a leader, leaders, layouts with a page setup and viewports, which can freeze their own layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. diff --git a/docs/assets/outdoor-kitchen-dark.svg b/docs/assets/outdoor-kitchen-dark.svg index 5826ae2..afb5891 100644 --- a/docs/assets/outdoor-kitchen-dark.svg +++ b/docs/assets/outdoor-kitchen-dark.svg @@ -3177,7 +3177,9 @@ - 2'-0" + + 2'-0" + @@ -3185,7 +3187,9 @@ - 3'-0" + + 3'-0" + @@ -3193,7 +3197,9 @@ - 2'-6" + + 2'-6" + @@ -3201,7 +3207,9 @@ - 8'-0" + + 8'-0" + @@ -3209,7 +3217,9 @@ - 3'-0" + + 3'-0" + @@ -3217,7 +3227,9 @@ - 3'-0" + + 3'-0" + @@ -3225,7 +3237,9 @@ - 9'-0" + + 9'-0" + @@ -4087,7 +4101,9 @@ - 2'-6" + + 2'-6" + @@ -4095,7 +4111,9 @@ - 3'-0" + + 3'-0" + @@ -4103,7 +4121,9 @@ - 3'-0" + + 3'-0" + diff --git a/docs/assets/outdoor-kitchen-light.svg b/docs/assets/outdoor-kitchen-light.svg index 4d6d891..7b7e449 100644 --- a/docs/assets/outdoor-kitchen-light.svg +++ b/docs/assets/outdoor-kitchen-light.svg @@ -3177,7 +3177,9 @@ - 2'-0" + + 2'-0" + @@ -3185,7 +3187,9 @@ - 3'-0" + + 3'-0" + @@ -3193,7 +3197,9 @@ - 2'-6" + + 2'-6" + @@ -3201,7 +3207,9 @@ - 8'-0" + + 8'-0" + @@ -3209,7 +3217,9 @@ - 3'-0" + + 3'-0" + @@ -3217,7 +3227,9 @@ - 3'-0" + + 3'-0" + @@ -3225,7 +3237,9 @@ - 9'-0" + + 9'-0" + @@ -4087,7 +4101,9 @@ - 2'-6" + + 2'-6" + @@ -4095,7 +4111,9 @@ - 3'-0" + + 3'-0" + @@ -4103,7 +4121,9 @@ - 3'-0" + + 3'-0" + diff --git a/docs/assets/plan-set-A-101-dark.svg b/docs/assets/plan-set-A-101-dark.svg index 117674d..28c9161 100644 --- a/docs/assets/plan-set-A-101-dark.svg +++ b/docs/assets/plan-set-A-101-dark.svg @@ -1,7 +1,7 @@ - + - + @@ -134,8 +134,8 @@ - - + + @@ -156,8 +156,8 @@ - - + + @@ -268,136 +268,138 @@ - - + + - GARAGE - 498 SF | 10'-0" CLG. + GARAGE + 498 SF | 10'-0" CLG. - FOYER - + FOYER + - STUDY - 296 SF | 10'-0" CLG. + STUDY + 296 SF | 10'-0" CLG. - GREAT ROOM - 521 SF | 10'-0" CLG. + GREAT ROOM + 521 SF | 10'-0" CLG. - KITCHEN - 384 SF | 10'-0" CLG. + KITCHEN + 384 SF | 10'-0" CLG. - LAUNDRY - 96 SF | 9'-0" CLG. + LAUNDRY + 96 SF | 9'-0" CLG. - PWDR. - + PWDR. + - PANTRY - + PANTRY + - ENTRY PORCH - 52 SF + ENTRY PORCH + 52 SF - COVERED LANAI - 232 SF + COVERED LANAI + 232 SF - 101 + 101 - 102 + 102 - 103 + 103 - 104 + 104 - 105 + 105 - 106 + 106 - 107 + 107 - 108 + 108 - 109 + 109 - A + A - 1-01 + 1-01 - A + A - 1-02 + 1-02 - A + A - 1-03 + 1-03 - E + E - 1-04 + 1-04 - A + A - 1-05 + 1-05 - B + B - 1-06 + 1-06 - D + D - 1-07 + 1-07 - C + C - 1-08 + 1-08 - D + D - 1-09 + 1-09 - 10'-0" + + 10'-0" + @@ -405,7 +407,9 @@ - 12'-0" + + 12'-0" + @@ -413,7 +417,9 @@ - 6'-9" + + 6'-9" + @@ -421,7 +427,9 @@ - 2'-7" + + 2'-7" + @@ -429,7 +437,9 @@ - 7'-2" + + 7'-2" + @@ -437,7 +447,9 @@ - 7'-0" + + 7'-0" + @@ -445,7 +457,9 @@ - 6'-6" + + 6'-6" + @@ -453,7 +467,9 @@ - 22'-0" + + 22'-0" + @@ -461,7 +477,9 @@ - 9'-4" + + 9'-4" + @@ -469,7 +487,9 @@ - 20'-8" + + 20'-8" + @@ -477,7 +497,9 @@ - 52'-0" + + 52'-0" + @@ -485,7 +507,9 @@ - 21'-0" + + 21'-0" + @@ -493,7 +517,9 @@ - 21'-0" + + 21'-0" + @@ -501,7 +527,9 @@ - 10'-0" + + 10'-0" + @@ -509,7 +537,9 @@ - 52'-0" + + 52'-0" + @@ -517,7 +547,9 @@ - 8'-0" + + 8'-0" + @@ -525,7 +557,9 @@ - 20'-0" + + 20'-0" + @@ -533,7 +567,9 @@ - 9'-6" + + 9'-6" + @@ -541,7 +577,9 @@ - 6'-6" + + 6'-6" + @@ -549,7 +587,9 @@ - 44'-0" + + 44'-0" + @@ -557,7 +597,9 @@ - 4'-10" + + 4'-10" + @@ -565,7 +607,9 @@ - 6'-8" + + 6'-8" + @@ -573,7 +617,9 @@ - 17'-6" + + 17'-6" + @@ -581,7 +627,9 @@ - 9'-8" + + 9'-8" + @@ -589,7 +637,9 @@ - 5'-4" + + 5'-4" + @@ -597,37 +647,60 @@ - 44'-0" - - - - 16'-0" X 8'-0" IMPACT RATED - OVERHEAD DOOR, SEE A-601 - - - RAISED LANAI SLAB EL. 10.67' NAVD, - ON STEM WALLS PER S-101, 36" GUARD - - - ENTRY PORCH SLAB EL. 10.67' NAVD, - 4" STEP DOWN FROM DOOR 101, - 36" GUARD AT OPEN EDGE - - - 5R DN TO WALK AT 8.00', - HANDRAILS BOTH SIDES - - - 4R DN TO GARAGE SLAB, - HANDRAIL, 36" LANDING - - - 4R DN TO POOL DECK - AT 8.40' NAVD - - - FLOOD VENT, TYP. OF 4, - SEE S-101 + + 44'-0" + + + + + + + 16'-0" X 8'-0" IMPACT RATED + OVERHEAD DOOR, SEE A-601 + + + + + + RAISED LANAI SLAB EL. 10.67' NAVD, + ON STEM WALLS PER S-101, 36" GUARD + + + + + + ENTRY PORCH SLAB EL. 10.67' NAVD, + 4" STEP DOWN FROM DOOR 101, + 36" GUARD AT OPEN EDGE + + + + + + 5R DN TO WALK AT 8.00', + HANDRAILS BOTH SIDES + + + + + + 4R DN TO GARAGE SLAB, + HANDRAIL, 36" LANDING + + + + + + 4R DN TO POOL DECK + AT 8.40' NAVD + + + + + + FLOOD VENT, TYP. OF 4, + SEE S-101 + @@ -650,7 +723,9 @@ - 1'-3" + + 1'-3" + @@ -658,7 +733,9 @@ - 1'-8" + + 1'-8" + @@ -697,7 +774,7 @@ - 1 + 1 @@ -717,7 +794,7 @@ - 1 + 1 @@ -743,7 +820,7 @@ - 1 + 1 @@ -767,7 +844,7 @@ - 1 + 1 @@ -809,31 +886,31 @@ - 1 - UP - GARAGE SLAB EL. 8.50' NAVD - F.F.E. 11.00' NAVD - - + 1 + UP + GARAGE SLAB EL. 8.50' NAVD + F.F.E. 11.00' NAVD + + - 1 - A-301 + 1 + A-301 - 1 - A-301 + 1 + A-301 - 2 - A-301 + 2 + A-301 @@ -852,48 +929,48 @@ - HALYARD & MOSS - ENGINEERING - DEMO - 100 EXAMPLE WAY, SUITE 0 - CORAL HERON KEY, FL 34999 - CA NO. 00000 (FICTIONAL) - PROJECT - CALLOWAY RESIDENCE - NEW TWO-STORY SINGLE-FAMILY RESIDENCE - 218 SANDPIPER COVE DRIVE - CORAL HERON KEY, FLORIDA 34999 - OWNER - JUNIPER AND THEO CALLOWAY - LOT 14, BLOCK C, HERON SOUND ESTATES - PARCEL ID 00-00-00-00000-000-0140 - MANGROVE COUNTY (FICTIONAL) - REVISIONS - ENGINEER'S SEAL - DEMONSTRATION SET - NOT FOR CONSTRUCTION - NO SEAL. NO ENGINEER OF RECORD. - ENGINEER OF RECORD - J. R. HALYARD, P.E. (FICTIONAL) - FLORIDA P.E. NO. 00000 - DATE - JOB NO. - DRAWN BY - CHECKED BY - SCALE - SHEET TITLE - SHEET NUMBER + HALYARD & MOSS + ENGINEERING - DEMO + 100 EXAMPLE WAY, SUITE 0 + CORAL HERON KEY, FL 34999 + CA NO. 00000 (FICTIONAL) + PROJECT + CALLOWAY RESIDENCE + NEW TWO-STORY SINGLE-FAMILY RESIDENCE + 218 SANDPIPER COVE DRIVE + CORAL HERON KEY, FLORIDA 34999 + OWNER + JUNIPER AND THEO CALLOWAY + LOT 14, BLOCK C, HERON SOUND ESTATES + PARCEL ID 00-00-00-00000-000-0140 + MANGROVE COUNTY (FICTIONAL) + REVISIONS + ENGINEER'S SEAL + DEMONSTRATION SET + NOT FOR CONSTRUCTION + NO SEAL. NO ENGINEER OF RECORD. + ENGINEER OF RECORD + J. R. HALYARD, P.E. (FICTIONAL) + FLORIDA P.E. NO. 00000 + DATE + JOB NO. + DRAWN BY + CHECKED BY + SCALE + SHEET TITLE + SHEET NUMBER - 2026-11-13 - 26-0418 - AGENT - -- - AS NOTED - FIRST FLOOR PLAN - - ISSUED FOR PERMIT - A-101 - SHEET 3 OF 15 + 2026-11-13 + 26-0418 + AGENT + -- + AS NOTED + FIRST FLOOR PLAN + + ISSUED FOR PERMIT + A-101 + SHEET 3 OF 15 @@ -907,98 +984,98 @@ - NO. - DATE - DESCRIPTION - 0 - 2026-11-13 - ISSUED FOR PERMIT - 1 - 2026-11-13 - PLAN REVIEW RESPONSES + NO. + DATE + DESCRIPTION + 0 + 2026-11-13 + ISSUED FOR PERMIT + 1 + 2026-11-13 + PLAN REVIEW RESPONSES - 1 - A-101 - FIRST FLOOR PLAN - SCALE: 1/4" = 1'-0" + 1 + A-101 + FIRST FLOOR PLAN + SCALE: 1/4" = 1'-0" - N + N - PLAN NOTES + PLAN NOTES - 1. - DIMENSIONS ARE TO THE FACE OF MASONRY OR THE FACE OF STUD UNLESS NOTED. DO - NOT SCALE THE DRAWINGS. - 2. - EXTERIOR WALLS OF THE FIRST FLOOR ARE 8" CMU WITH A REINFORCED TIE BEAM. SEE - S-101 AND S-501. - 3. - ALL EXTERIOR GLAZED OPENINGS ARE IMPACT RATED FOR THE DESIGN PRESSURES ON - A-601, WITH FLORIDA PRODUCT APPROVAL. - 4. - GARAGE SEPARATION (FBC-R R302.6): 5/8" TYPE X GYPSUM BOARD ON THE GARAGE CEILING - BELOW BEDROOM 2 AND THE HALL, 1/2" GYPSUM BOARD ON THE GARAGE WALLS AND ON - STRUCTURE SUPPORTING THE CEILING. DOOR 103: SOLID CORE 1 3/8" MIN., SELF-CLOSING - AND SELF-LATCHING. - 5. - FLOOD VENTS: 4 ENGINEERED VENTS, EACH CERTIFIED (ICC-ES) TO COVER 200 SQ. FT. OF - ENCLOSED AREA: 4 X 200 = 800 SQ. FT. >= 528 SQ. FT. GROSS GARAGE AREA. BOTTOM - WITHIN 12" OF GRADE, ON TWO WALLS (FBC-R R322.2.2). LOCATIONS PER S-101. - 6. - SMOKE AND CARBON MONOXIDE ALARMS PER E-101, INTERCONNECTED. - 7. - MAIN STAIR: 18 RISERS AT 7.68" (7 3/4" MAX.), 17 TREADS AT 10", 36" LANDINGS TOP AND - BOTTOM, HANDRAIL 34"-38" ABOVE THE NOSINGS, GUARD 36" MIN. (FBC-R R311.7). - 8. - GARAGE STEPS AT DOOR 103: 36" LANDING, 4 RISERS AT 7 1/2", TREADS 10", HANDRAIL ONE - SIDE. ENTRY STAIR: 5 RISERS AT 6 3/8", TREADS 11", HANDRAILS BOTH SIDES. LANAI STEPS: - 4 RISERS AT 6 13/16", TREADS 11", HANDRAILS BOTH SIDES. - 9. - GUARDS 36" HIGH AT THE PORCH AND LANAI EDGES, WHICH ARE 32" ABOVE FINISHED - GRADE (8.00' NAVD), WITH NO OPENING A 4" SPHERE PASSES (FBC-R R312.1). - 10. - ROOM AREAS ON THE TAGS ARE NET, TO THE INSIDE FACE OF THE WALLS. G-001 - TABULATES GROSS AREAS. - LEGEND + 1. + DIMENSIONS ARE TO THE FACE OF MASONRY OR THE FACE OF STUD UNLESS NOTED. DO + NOT SCALE THE DRAWINGS. + 2. + EXTERIOR WALLS OF THE FIRST FLOOR ARE 8" CMU WITH A REINFORCED TIE BEAM. SEE + S-101 AND S-501. + 3. + ALL EXTERIOR GLAZED OPENINGS ARE IMPACT RATED FOR THE DESIGN PRESSURES ON + A-601, WITH FLORIDA PRODUCT APPROVAL. + 4. + GARAGE SEPARATION (FBC-R R302.6): 5/8" TYPE X GYPSUM BOARD ON THE GARAGE CEILING + BELOW BEDROOM 2 AND THE HALL, 1/2" GYPSUM BOARD ON THE GARAGE WALLS AND ON + STRUCTURE SUPPORTING THE CEILING. DOOR 103: SOLID CORE 1 3/8" MIN., SELF-CLOSING + AND SELF-LATCHING. + 5. + FLOOD VENTS: 4 ENGINEERED VENTS, EACH CERTIFIED (ICC-ES) TO COVER 200 SQ. FT. OF + ENCLOSED AREA: 4 X 200 = 800 SQ. FT. >= 528 SQ. FT. GROSS GARAGE AREA. BOTTOM + WITHIN 12" OF GRADE, ON TWO WALLS (FBC-R R322.2.2). LOCATIONS PER S-101. + 6. + SMOKE AND CARBON MONOXIDE ALARMS PER E-101, INTERCONNECTED. + 7. + MAIN STAIR: 18 RISERS AT 7.68" (7 3/4" MAX.), 17 TREADS AT 10", 36" LANDINGS TOP AND + BOTTOM, HANDRAIL 34"-38" ABOVE THE NOSINGS, GUARD 36" MIN. (FBC-R R311.7). + 8. + GARAGE STEPS AT DOOR 103: 36" LANDING, 4 RISERS AT 7 1/2", TREADS 10", HANDRAIL ONE + SIDE. ENTRY STAIR: 5 RISERS AT 6 3/8", TREADS 11", HANDRAILS BOTH SIDES. LANAI STEPS: + 4 RISERS AT 6 13/16", TREADS 11", HANDRAILS BOTH SIDES. + 9. + GUARDS 36" HIGH AT THE PORCH AND LANAI EDGES, WHICH ARE 32" ABOVE FINISHED + GRADE (8.00' NAVD), WITH NO OPENING A 4" SPHERE PASSES (FBC-R R312.1). + 10. + ROOM AREAS ON THE TAGS ARE NET, TO THE INSIDE FACE OF THE WALLS. G-001 + TABULATES GROSS AREAS. + LEGEND - 101 + 101 - DOOR NUMBER, SEE A-601 + DOOR NUMBER, SEE A-601 - A + A - WINDOW TYPE, SEE A-601 - 1-01 - WINDOW MARK, SEE A-601 + WINDOW TYPE, SEE A-601 + 1-01 + WINDOW MARK, SEE A-601 - 8" CMU WALL + 8" CMU WALL - 2X4 STUD WALL + 2X4 STUD WALL - 36" GUARD OR HALF WALL + 36" GUARD OR HALF WALL - OVERHEAD OR HIDDEN + OVERHEAD OR HIDDEN - 1 - A-301 + 1 + A-301 - SECTION CUT: NO. / SHEET + SECTION CUT: NO. / SHEET - FLOOD VENT + FLOOD VENT diff --git a/docs/assets/plan-set-A-101-light.svg b/docs/assets/plan-set-A-101-light.svg index 14e93ae..b5d5ffd 100644 --- a/docs/assets/plan-set-A-101-light.svg +++ b/docs/assets/plan-set-A-101-light.svg @@ -1,7 +1,7 @@ - + - + @@ -134,8 +134,8 @@ - - + + @@ -156,8 +156,8 @@ - - + + @@ -268,136 +268,138 @@ - - + + - GARAGE - 498 SF | 10'-0" CLG. + GARAGE + 498 SF | 10'-0" CLG. - FOYER - + FOYER + - STUDY - 296 SF | 10'-0" CLG. + STUDY + 296 SF | 10'-0" CLG. - GREAT ROOM - 521 SF | 10'-0" CLG. + GREAT ROOM + 521 SF | 10'-0" CLG. - KITCHEN - 384 SF | 10'-0" CLG. + KITCHEN + 384 SF | 10'-0" CLG. - LAUNDRY - 96 SF | 9'-0" CLG. + LAUNDRY + 96 SF | 9'-0" CLG. - PWDR. - + PWDR. + - PANTRY - + PANTRY + - ENTRY PORCH - 52 SF + ENTRY PORCH + 52 SF - COVERED LANAI - 232 SF + COVERED LANAI + 232 SF - 101 + 101 - 102 + 102 - 103 + 103 - 104 + 104 - 105 + 105 - 106 + 106 - 107 + 107 - 108 + 108 - 109 + 109 - A + A - 1-01 + 1-01 - A + A - 1-02 + 1-02 - A + A - 1-03 + 1-03 - E + E - 1-04 + 1-04 - A + A - 1-05 + 1-05 - B + B - 1-06 + 1-06 - D + D - 1-07 + 1-07 - C + C - 1-08 + 1-08 - D + D - 1-09 + 1-09 - 10'-0" + + 10'-0" + @@ -405,7 +407,9 @@ - 12'-0" + + 12'-0" + @@ -413,7 +417,9 @@ - 6'-9" + + 6'-9" + @@ -421,7 +427,9 @@ - 2'-7" + + 2'-7" + @@ -429,7 +437,9 @@ - 7'-2" + + 7'-2" + @@ -437,7 +447,9 @@ - 7'-0" + + 7'-0" + @@ -445,7 +457,9 @@ - 6'-6" + + 6'-6" + @@ -453,7 +467,9 @@ - 22'-0" + + 22'-0" + @@ -461,7 +477,9 @@ - 9'-4" + + 9'-4" + @@ -469,7 +487,9 @@ - 20'-8" + + 20'-8" + @@ -477,7 +497,9 @@ - 52'-0" + + 52'-0" + @@ -485,7 +507,9 @@ - 21'-0" + + 21'-0" + @@ -493,7 +517,9 @@ - 21'-0" + + 21'-0" + @@ -501,7 +527,9 @@ - 10'-0" + + 10'-0" + @@ -509,7 +537,9 @@ - 52'-0" + + 52'-0" + @@ -517,7 +547,9 @@ - 8'-0" + + 8'-0" + @@ -525,7 +557,9 @@ - 20'-0" + + 20'-0" + @@ -533,7 +567,9 @@ - 9'-6" + + 9'-6" + @@ -541,7 +577,9 @@ - 6'-6" + + 6'-6" + @@ -549,7 +587,9 @@ - 44'-0" + + 44'-0" + @@ -557,7 +597,9 @@ - 4'-10" + + 4'-10" + @@ -565,7 +607,9 @@ - 6'-8" + + 6'-8" + @@ -573,7 +617,9 @@ - 17'-6" + + 17'-6" + @@ -581,7 +627,9 @@ - 9'-8" + + 9'-8" + @@ -589,7 +637,9 @@ - 5'-4" + + 5'-4" + @@ -597,37 +647,60 @@ - 44'-0" - - - - 16'-0" X 8'-0" IMPACT RATED - OVERHEAD DOOR, SEE A-601 - - - RAISED LANAI SLAB EL. 10.67' NAVD, - ON STEM WALLS PER S-101, 36" GUARD - - - ENTRY PORCH SLAB EL. 10.67' NAVD, - 4" STEP DOWN FROM DOOR 101, - 36" GUARD AT OPEN EDGE - - - 5R DN TO WALK AT 8.00', - HANDRAILS BOTH SIDES - - - 4R DN TO GARAGE SLAB, - HANDRAIL, 36" LANDING - - - 4R DN TO POOL DECK - AT 8.40' NAVD - - - FLOOD VENT, TYP. OF 4, - SEE S-101 + + 44'-0" + + + + + + + 16'-0" X 8'-0" IMPACT RATED + OVERHEAD DOOR, SEE A-601 + + + + + + RAISED LANAI SLAB EL. 10.67' NAVD, + ON STEM WALLS PER S-101, 36" GUARD + + + + + + ENTRY PORCH SLAB EL. 10.67' NAVD, + 4" STEP DOWN FROM DOOR 101, + 36" GUARD AT OPEN EDGE + + + + + + 5R DN TO WALK AT 8.00', + HANDRAILS BOTH SIDES + + + + + + 4R DN TO GARAGE SLAB, + HANDRAIL, 36" LANDING + + + + + + 4R DN TO POOL DECK + AT 8.40' NAVD + + + + + + FLOOD VENT, TYP. OF 4, + SEE S-101 + @@ -650,7 +723,9 @@ - 1'-3" + + 1'-3" + @@ -658,7 +733,9 @@ - 1'-8" + + 1'-8" + @@ -697,7 +774,7 @@ - 1 + 1 @@ -717,7 +794,7 @@ - 1 + 1 @@ -743,7 +820,7 @@ - 1 + 1 @@ -767,7 +844,7 @@ - 1 + 1 @@ -809,31 +886,31 @@ - 1 - UP - GARAGE SLAB EL. 8.50' NAVD - F.F.E. 11.00' NAVD - - + 1 + UP + GARAGE SLAB EL. 8.50' NAVD + F.F.E. 11.00' NAVD + + - 1 - A-301 + 1 + A-301 - 1 - A-301 + 1 + A-301 - 2 - A-301 + 2 + A-301 @@ -852,48 +929,48 @@ - HALYARD & MOSS - ENGINEERING - DEMO - 100 EXAMPLE WAY, SUITE 0 - CORAL HERON KEY, FL 34999 - CA NO. 00000 (FICTIONAL) - PROJECT - CALLOWAY RESIDENCE - NEW TWO-STORY SINGLE-FAMILY RESIDENCE - 218 SANDPIPER COVE DRIVE - CORAL HERON KEY, FLORIDA 34999 - OWNER - JUNIPER AND THEO CALLOWAY - LOT 14, BLOCK C, HERON SOUND ESTATES - PARCEL ID 00-00-00-00000-000-0140 - MANGROVE COUNTY (FICTIONAL) - REVISIONS - ENGINEER'S SEAL - DEMONSTRATION SET - NOT FOR CONSTRUCTION - NO SEAL. NO ENGINEER OF RECORD. - ENGINEER OF RECORD - J. R. HALYARD, P.E. (FICTIONAL) - FLORIDA P.E. NO. 00000 - DATE - JOB NO. - DRAWN BY - CHECKED BY - SCALE - SHEET TITLE - SHEET NUMBER + HALYARD & MOSS + ENGINEERING - DEMO + 100 EXAMPLE WAY, SUITE 0 + CORAL HERON KEY, FL 34999 + CA NO. 00000 (FICTIONAL) + PROJECT + CALLOWAY RESIDENCE + NEW TWO-STORY SINGLE-FAMILY RESIDENCE + 218 SANDPIPER COVE DRIVE + CORAL HERON KEY, FLORIDA 34999 + OWNER + JUNIPER AND THEO CALLOWAY + LOT 14, BLOCK C, HERON SOUND ESTATES + PARCEL ID 00-00-00-00000-000-0140 + MANGROVE COUNTY (FICTIONAL) + REVISIONS + ENGINEER'S SEAL + DEMONSTRATION SET + NOT FOR CONSTRUCTION + NO SEAL. NO ENGINEER OF RECORD. + ENGINEER OF RECORD + J. R. HALYARD, P.E. (FICTIONAL) + FLORIDA P.E. NO. 00000 + DATE + JOB NO. + DRAWN BY + CHECKED BY + SCALE + SHEET TITLE + SHEET NUMBER - 2026-11-13 - 26-0418 - AGENT - -- - AS NOTED - FIRST FLOOR PLAN - - ISSUED FOR PERMIT - A-101 - SHEET 3 OF 15 + 2026-11-13 + 26-0418 + AGENT + -- + AS NOTED + FIRST FLOOR PLAN + + ISSUED FOR PERMIT + A-101 + SHEET 3 OF 15 @@ -907,98 +984,98 @@ - NO. - DATE - DESCRIPTION - 0 - 2026-11-13 - ISSUED FOR PERMIT - 1 - 2026-11-13 - PLAN REVIEW RESPONSES + NO. + DATE + DESCRIPTION + 0 + 2026-11-13 + ISSUED FOR PERMIT + 1 + 2026-11-13 + PLAN REVIEW RESPONSES - 1 - A-101 - FIRST FLOOR PLAN - SCALE: 1/4" = 1'-0" + 1 + A-101 + FIRST FLOOR PLAN + SCALE: 1/4" = 1'-0" - N + N - PLAN NOTES + PLAN NOTES - 1. - DIMENSIONS ARE TO THE FACE OF MASONRY OR THE FACE OF STUD UNLESS NOTED. DO - NOT SCALE THE DRAWINGS. - 2. - EXTERIOR WALLS OF THE FIRST FLOOR ARE 8" CMU WITH A REINFORCED TIE BEAM. SEE - S-101 AND S-501. - 3. - ALL EXTERIOR GLAZED OPENINGS ARE IMPACT RATED FOR THE DESIGN PRESSURES ON - A-601, WITH FLORIDA PRODUCT APPROVAL. - 4. - GARAGE SEPARATION (FBC-R R302.6): 5/8" TYPE X GYPSUM BOARD ON THE GARAGE CEILING - BELOW BEDROOM 2 AND THE HALL, 1/2" GYPSUM BOARD ON THE GARAGE WALLS AND ON - STRUCTURE SUPPORTING THE CEILING. DOOR 103: SOLID CORE 1 3/8" MIN., SELF-CLOSING - AND SELF-LATCHING. - 5. - FLOOD VENTS: 4 ENGINEERED VENTS, EACH CERTIFIED (ICC-ES) TO COVER 200 SQ. FT. OF - ENCLOSED AREA: 4 X 200 = 800 SQ. FT. >= 528 SQ. FT. GROSS GARAGE AREA. BOTTOM - WITHIN 12" OF GRADE, ON TWO WALLS (FBC-R R322.2.2). LOCATIONS PER S-101. - 6. - SMOKE AND CARBON MONOXIDE ALARMS PER E-101, INTERCONNECTED. - 7. - MAIN STAIR: 18 RISERS AT 7.68" (7 3/4" MAX.), 17 TREADS AT 10", 36" LANDINGS TOP AND - BOTTOM, HANDRAIL 34"-38" ABOVE THE NOSINGS, GUARD 36" MIN. (FBC-R R311.7). - 8. - GARAGE STEPS AT DOOR 103: 36" LANDING, 4 RISERS AT 7 1/2", TREADS 10", HANDRAIL ONE - SIDE. ENTRY STAIR: 5 RISERS AT 6 3/8", TREADS 11", HANDRAILS BOTH SIDES. LANAI STEPS: - 4 RISERS AT 6 13/16", TREADS 11", HANDRAILS BOTH SIDES. - 9. - GUARDS 36" HIGH AT THE PORCH AND LANAI EDGES, WHICH ARE 32" ABOVE FINISHED - GRADE (8.00' NAVD), WITH NO OPENING A 4" SPHERE PASSES (FBC-R R312.1). - 10. - ROOM AREAS ON THE TAGS ARE NET, TO THE INSIDE FACE OF THE WALLS. G-001 - TABULATES GROSS AREAS. - LEGEND + 1. + DIMENSIONS ARE TO THE FACE OF MASONRY OR THE FACE OF STUD UNLESS NOTED. DO + NOT SCALE THE DRAWINGS. + 2. + EXTERIOR WALLS OF THE FIRST FLOOR ARE 8" CMU WITH A REINFORCED TIE BEAM. SEE + S-101 AND S-501. + 3. + ALL EXTERIOR GLAZED OPENINGS ARE IMPACT RATED FOR THE DESIGN PRESSURES ON + A-601, WITH FLORIDA PRODUCT APPROVAL. + 4. + GARAGE SEPARATION (FBC-R R302.6): 5/8" TYPE X GYPSUM BOARD ON THE GARAGE CEILING + BELOW BEDROOM 2 AND THE HALL, 1/2" GYPSUM BOARD ON THE GARAGE WALLS AND ON + STRUCTURE SUPPORTING THE CEILING. DOOR 103: SOLID CORE 1 3/8" MIN., SELF-CLOSING + AND SELF-LATCHING. + 5. + FLOOD VENTS: 4 ENGINEERED VENTS, EACH CERTIFIED (ICC-ES) TO COVER 200 SQ. FT. OF + ENCLOSED AREA: 4 X 200 = 800 SQ. FT. >= 528 SQ. FT. GROSS GARAGE AREA. BOTTOM + WITHIN 12" OF GRADE, ON TWO WALLS (FBC-R R322.2.2). LOCATIONS PER S-101. + 6. + SMOKE AND CARBON MONOXIDE ALARMS PER E-101, INTERCONNECTED. + 7. + MAIN STAIR: 18 RISERS AT 7.68" (7 3/4" MAX.), 17 TREADS AT 10", 36" LANDINGS TOP AND + BOTTOM, HANDRAIL 34"-38" ABOVE THE NOSINGS, GUARD 36" MIN. (FBC-R R311.7). + 8. + GARAGE STEPS AT DOOR 103: 36" LANDING, 4 RISERS AT 7 1/2", TREADS 10", HANDRAIL ONE + SIDE. ENTRY STAIR: 5 RISERS AT 6 3/8", TREADS 11", HANDRAILS BOTH SIDES. LANAI STEPS: + 4 RISERS AT 6 13/16", TREADS 11", HANDRAILS BOTH SIDES. + 9. + GUARDS 36" HIGH AT THE PORCH AND LANAI EDGES, WHICH ARE 32" ABOVE FINISHED + GRADE (8.00' NAVD), WITH NO OPENING A 4" SPHERE PASSES (FBC-R R312.1). + 10. + ROOM AREAS ON THE TAGS ARE NET, TO THE INSIDE FACE OF THE WALLS. G-001 + TABULATES GROSS AREAS. + LEGEND - 101 + 101 - DOOR NUMBER, SEE A-601 + DOOR NUMBER, SEE A-601 - A + A - WINDOW TYPE, SEE A-601 - 1-01 - WINDOW MARK, SEE A-601 + WINDOW TYPE, SEE A-601 + 1-01 + WINDOW MARK, SEE A-601 - 8" CMU WALL + 8" CMU WALL - 2X4 STUD WALL + 2X4 STUD WALL - 36" GUARD OR HALF WALL + 36" GUARD OR HALF WALL - OVERHEAD OR HIDDEN + OVERHEAD OR HIDDEN - 1 - A-301 + 1 + A-301 - SECTION CUT: NO. / SHEET + SECTION CUT: NO. / SHEET - FLOOD VENT + FLOOD VENT diff --git a/docs/assets/plan-set-A-201-dark.svg b/docs/assets/plan-set-A-201-dark.svg index 09b6d07..eb40735 100644 --- a/docs/assets/plan-set-A-201-dark.svg +++ b/docs/assets/plan-set-A-201-dark.svg @@ -1,7 +1,7 @@ - + - + @@ -65,7 +65,7 @@ - 101 + 101 @@ -110,7 +110,7 @@ - 102 + 102 @@ -119,7 +119,7 @@ - A + A @@ -128,7 +128,7 @@ - A + A @@ -137,7 +137,7 @@ - A + A @@ -146,16 +146,16 @@ - A + A - + - B + B @@ -165,77 +165,77 @@ - E + E - + - B.F.E. 9.00' NAVD (ZONE AE) + B.F.E. 9.00' NAVD (ZONE AE) - D.F.E. 10.00' NAVD (BFE + 1'-0") + D.F.E. 10.00' NAVD (BFE + 1'-0") - RIDGE - EL. 43.11' NAVD + RIDGE + EL. 43.11' NAVD - MEAN ROOF HT. - EL. 37.11' NAVD + MEAN ROOF HT. + EL. 37.11' NAVD - TOP OF PLATE - EL. 31.61' NAVD + TOP OF PLATE + EL. 31.61' NAVD - SECOND FLOOR - EL. 22.52' NAVD + SECOND FLOOR + EL. 22.52' NAVD - TOP OF TIE BEAM - EL. 21.00' NAVD + TOP OF TIE BEAM + EL. 21.00' NAVD - FIRST FLOOR (F.F.E.) - EL. 11.00' NAVD + FIRST FLOOR (F.F.E.) + EL. 11.00' NAVD - GARAGE SLAB - EL. 8.50' NAVD + GARAGE SLAB + EL. 8.50' NAVD - FINISH GRADE - EL. 8.00' NAVD + FINISH GRADE + EL. 8.00' NAVD @@ -243,7 +243,9 @@ - 3'-0" + + 3'-0" + @@ -251,15 +253,21 @@ - 10'-0" + + 10'-0" + - + + + - 1'-6 1/4" + + 1'-6 1/4" + @@ -267,7 +275,9 @@ - 9'-1 1/8" + + 9'-1 1/8" + @@ -275,51 +285,86 @@ - 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) - - - - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT - - - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT - - - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. - - - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM - - - IMPACT RATED WINDOW, - SEE A-601 - - - 5/8" STUCCO ON 8" CMU - - - 36" GUARD AT PORCH EDGE, - 4" SPHERE MAX. OPENING (R312.1) - - - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB - - - 16'-0" X 8'-0" IMPACT - OVERHEAD DOOR, SEE A-601 - - - ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS - AT 11", HANDRAILS BOTH SIDES AT 34"-38" - - - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) + + + + + + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + + + + + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + + + + + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + + + + + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + + + + + + IMPACT RATED WINDOW, + SEE A-601 + + + + + + 5/8" STUCCO ON 8" CMU + + + + + + 36" GUARD AT PORCH EDGE, + 4" SPHERE MAX. OPENING (R312.1) + + + + + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + + + + + + 16'-0" X 8'-0" IMPACT + OVERHEAD DOOR, SEE A-601 + + + + + + ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS + AT 11", HANDRAILS BOTH SIDES AT 34"-38" + + + + + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + @@ -481,7 +526,7 @@ - 108 + 108 @@ -496,10 +541,10 @@ - + - B + B @@ -517,7 +562,7 @@ - A + A @@ -536,7 +581,7 @@ - E + E @@ -555,69 +600,69 @@ - E + E - + - B.F.E. 9.00' NAVD (ZONE AE) + B.F.E. 9.00' NAVD (ZONE AE) - D.F.E. 10.00' NAVD (BFE + 1'-0") + D.F.E. 10.00' NAVD (BFE + 1'-0") - RIDGE - EL. 43.11' NAVD + RIDGE + EL. 43.11' NAVD - MEAN ROOF HT. - EL. 37.11' NAVD + MEAN ROOF HT. + EL. 37.11' NAVD - TOP OF PLATE - EL. 31.61' NAVD + TOP OF PLATE + EL. 31.61' NAVD - SECOND FLOOR - EL. 22.52' NAVD + SECOND FLOOR + EL. 22.52' NAVD - TOP OF TIE BEAM - EL. 21.00' NAVD + TOP OF TIE BEAM + EL. 21.00' NAVD - FIRST FLOOR (F.F.E.) - EL. 11.00' NAVD + FIRST FLOOR (F.F.E.) + EL. 11.00' NAVD - FINISH GRADE - EL. 8.00' NAVD + FINISH GRADE + EL. 8.00' NAVD @@ -625,7 +670,9 @@ - 3'-0" + + 3'-0" + @@ -633,15 +680,21 @@ - 10'-0" + + 10'-0" + - + + + - 1'-6 1/4" + + 1'-6 1/4" + @@ -649,7 +702,9 @@ - 9'-1 1/8" + + 9'-1 1/8" + @@ -657,51 +712,86 @@ - 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) - - - - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT - - - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT - - - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. - - - LANAI ROOF, STANDING SEAM - METAL AT 3:12, SEE S-102 - - - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM - - - IMPACT RATED WINDOW, - SEE A-601 - - - 5/8" STUCCO ON 8" CMU - - - 36" GUARD AT LANAI, 3 SIDES, - 4" SPHERE MAX. OPENING (R312.1) - - - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB - - - LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, - HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' - - - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) + + + + + + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + + + + + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + + + + + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + + + + + + LANAI ROOF, STANDING SEAM + METAL AT 3:12, SEE S-102 + + + + + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + + + + + + IMPACT RATED WINDOW, + SEE A-601 + + + + + + 5/8" STUCCO ON 8" CMU + + + + + + 36" GUARD AT LANAI, 3 SIDES, + 4" SPHERE MAX. OPENING (R312.1) + + + + + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + + + + + + LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, + HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' + + + + + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + @@ -717,48 +807,48 @@ - HALYARD & MOSS - ENGINEERING - DEMO - 100 EXAMPLE WAY, SUITE 0 - CORAL HERON KEY, FL 34999 - CA NO. 00000 (FICTIONAL) - PROJECT - CALLOWAY RESIDENCE - NEW TWO-STORY SINGLE-FAMILY RESIDENCE - 218 SANDPIPER COVE DRIVE - CORAL HERON KEY, FLORIDA 34999 - OWNER - JUNIPER AND THEO CALLOWAY - LOT 14, BLOCK C, HERON SOUND ESTATES - PARCEL ID 00-00-00-00000-000-0140 - MANGROVE COUNTY (FICTIONAL) - REVISIONS - ENGINEER'S SEAL - DEMONSTRATION SET - NOT FOR CONSTRUCTION - NO SEAL. NO ENGINEER OF RECORD. - ENGINEER OF RECORD - J. R. HALYARD, P.E. (FICTIONAL) - FLORIDA P.E. NO. 00000 - DATE - JOB NO. - DRAWN BY - CHECKED BY - SCALE - SHEET TITLE - SHEET NUMBER + HALYARD & MOSS + ENGINEERING - DEMO + 100 EXAMPLE WAY, SUITE 0 + CORAL HERON KEY, FL 34999 + CA NO. 00000 (FICTIONAL) + PROJECT + CALLOWAY RESIDENCE + NEW TWO-STORY SINGLE-FAMILY RESIDENCE + 218 SANDPIPER COVE DRIVE + CORAL HERON KEY, FLORIDA 34999 + OWNER + JUNIPER AND THEO CALLOWAY + LOT 14, BLOCK C, HERON SOUND ESTATES + PARCEL ID 00-00-00-00000-000-0140 + MANGROVE COUNTY (FICTIONAL) + REVISIONS + ENGINEER'S SEAL + DEMONSTRATION SET + NOT FOR CONSTRUCTION + NO SEAL. NO ENGINEER OF RECORD. + ENGINEER OF RECORD + J. R. HALYARD, P.E. (FICTIONAL) + FLORIDA P.E. NO. 00000 + DATE + JOB NO. + DRAWN BY + CHECKED BY + SCALE + SHEET TITLE + SHEET NUMBER - 2026-11-13 - 26-0418 - AGENT - -- - AS NOTED - EXTERIOR ELEVATIONS, - SOUTH AND NORTH - ISSUED FOR PERMIT - A-201 - SHEET 6 OF 15 + 2026-11-13 + 26-0418 + AGENT + -- + AS NOTED + EXTERIOR ELEVATIONS, + SOUTH AND NORTH + ISSUED FOR PERMIT + A-201 + SHEET 6 OF 15 @@ -772,122 +862,122 @@ - NO. - DATE - DESCRIPTION - 0 - 2026-11-13 - ISSUED FOR PERMIT - 1 - 2026-11-13 - PLAN REVIEW RESPONSES + NO. + DATE + DESCRIPTION + 0 + 2026-11-13 + ISSUED FOR PERMIT + 1 + 2026-11-13 + PLAN REVIEW RESPONSES - 1 - A-201 - SOUTH (FRONT) ELEVATION - SCALE: 1/4" = 1'-0" + 1 + A-201 + SOUTH (FRONT) ELEVATION + SCALE: 1/4" = 1'-0" - 2 - A-201 - NORTH (REAR) ELEVATION - SCALE: 1/4" = 1'-0" + 2 + A-201 + NORTH (REAR) ELEVATION + SCALE: 1/4" = 1'-0" - ELEVATION NOTES + ELEVATION NOTES - 1. - ELEVATIONS IN FEET ARE IN NAVD 88. HEIGHTS ARE TO THE TOP OF CONCRETE OR THE TOP OF FRAMING. - 2. - FLOOD ZONE AE, PANEL 12000C0000J (DEMO). B.F.E. 9.00', D.F.E. 10.00', F.F.E. 11.00' NAVD. THE LOWEST - FLOOR IS 2'-0" ABOVE THE B.F.E. (FBC-R R322.2.1). - 3. - THE GARAGE IS BELOW THE D.F.E.: PARKING, ACCESS AND STORAGE ONLY. FLOOD DAMAGE-RESISTANT - MATERIALS BELOW THE D.F.E. FLOOD VENTS PER S-101. - 4. - STUCCO: 3 COATS, 7/8" ON LATH OVER FRAMING, 5/8" ON MASONRY, WITH CONTROL JOINTS AT 144 SQ. FT. - MAX. AND AT EVERY CHANGE OF SUBSTRATE (ASTM C926, C1063). - 5. - ALL WINDOWS AND DOORS IMPACT RATED, WITH FLORIDA PRODUCT APPROVAL, FOR THE DESIGN - PRESSURES ON A-601. WINDOW HEADS: FIRST FLOOR 8'-0", SECOND FLOOR 7'-2" A.F.F.; GARAGE WINDOW - 8'-0" ABOVE THE GARAGE SLAB. - 6. - ROOFING: STANDING SEAM METAL WITH FLORIDA PRODUCT APPROVAL, ON SELF-ADHERED - UNDERLAYMENT OVER 19/32" PLYWOOD DECK (FBC-R R905.10). - 7. - BUILDING HEIGHT IS MEASURED FROM THE D.F.E. (10.00' NAVD) TO THE MEAN ROOF HEIGHT: 27'-1 3/8", 35'-0" - MAX. IN RSF-6 RESIDENTIAL SINGLE-FAMILY (DEMO). - 8. - FINISH GRADE 8.00' NAVD AT THE FOUNDATION (EXISTING 7.50'), SLOPING AWAY 6" IN THE FIRST 10'-0" TO - THE SWALES (FBC-R R401.3). SEE C-101. - 9. - ENTRY STAIR: 5 RISERS OF 6.4" AND 4 TREADS OF 11" FROM THE PORCH (10.67') TO THE WALK. LANAI STEPS: - 4 RISERS OF 6.8" AND 3 TREADS OF 11" TO THE POOL DECK (8.40'). HANDRAILS BOTH SIDES OF EACH, 34" TO - 38" ABOVE THE NOSINGS (FBC-R R311.7.8). - 10. - GUARDS: 36" HIGH AT THE ENTRY PORCH'S OPEN EDGE AND THE LANAI'S WEST, NORTH AND EAST SIDES, - WHERE THE SLAB IS MORE THAN 30" ABOVE GRADE. NO OPENING PASSES A 4" SPHERE (FBC-R R312.1). - LEVELS - LEVEL - ABOVE F.F. - NAVD 88 + 1. + ELEVATIONS IN FEET ARE IN NAVD 88. HEIGHTS ARE TO THE TOP OF CONCRETE OR THE TOP OF FRAMING. + 2. + FLOOD ZONE AE, PANEL 12000C0000J (DEMO). B.F.E. 9.00', D.F.E. 10.00', F.F.E. 11.00' NAVD. THE LOWEST + FLOOR IS 2'-0" ABOVE THE B.F.E. (FBC-R R322.2.1). + 3. + THE GARAGE IS BELOW THE D.F.E.: PARKING, ACCESS AND STORAGE ONLY. FLOOD DAMAGE-RESISTANT + MATERIALS BELOW THE D.F.E. FLOOD VENTS PER S-101. + 4. + STUCCO: 3 COATS, 7/8" ON LATH OVER FRAMING, 5/8" ON MASONRY, WITH CONTROL JOINTS AT 144 SQ. FT. + MAX. AND AT EVERY CHANGE OF SUBSTRATE (ASTM C926, C1063). + 5. + ALL WINDOWS AND DOORS IMPACT RATED, WITH FLORIDA PRODUCT APPROVAL, FOR THE DESIGN + PRESSURES ON A-601. WINDOW HEADS: FIRST FLOOR 8'-0", SECOND FLOOR 7'-2" A.F.F.; GARAGE WINDOW + 8'-0" ABOVE THE GARAGE SLAB. + 6. + ROOFING: STANDING SEAM METAL WITH FLORIDA PRODUCT APPROVAL, ON SELF-ADHERED + UNDERLAYMENT OVER 19/32" PLYWOOD DECK (FBC-R R905.10). + 7. + BUILDING HEIGHT IS MEASURED FROM THE D.F.E. (10.00' NAVD) TO THE MEAN ROOF HEIGHT: 27'-1 3/8", 35'-0" + MAX. IN RSF-6 RESIDENTIAL SINGLE-FAMILY (DEMO). + 8. + FINISH GRADE 8.00' NAVD AT THE FOUNDATION (EXISTING 7.50'), SLOPING AWAY 6" IN THE FIRST 10'-0" TO + THE SWALES (FBC-R R401.3). SEE C-101. + 9. + ENTRY STAIR: 5 RISERS OF 6.4" AND 4 TREADS OF 11" FROM THE PORCH (10.67') TO THE WALK. LANAI STEPS: + 4 RISERS OF 6.8" AND 3 TREADS OF 11" TO THE POOL DECK (8.40'). HANDRAILS BOTH SIDES OF EACH, 34" TO + 38" ABOVE THE NOSINGS (FBC-R R311.7.8). + 10. + GUARDS: 36" HIGH AT THE ENTRY PORCH'S OPEN EDGE AND THE LANAI'S WEST, NORTH AND EAST SIDES, + WHERE THE SLAB IS MORE THAN 30" ABOVE GRADE. NO OPENING PASSES A 4" SPHERE (FBC-R R312.1). + LEVELS + LEVEL + ABOVE F.F. + NAVD 88 - RIDGE - 32'-1 3/8" - 43.11' + RIDGE + 32'-1 3/8" + 43.11' - MEAN ROOF HEIGHT - 26'-1 3/8" - 37.11' + MEAN ROOF HEIGHT + 26'-1 3/8" + 37.11' - TOP OF PLATE, 2ND FLOOR - 20'-7 3/8" - 31.61' + TOP OF PLATE, 2ND FLOOR + 20'-7 3/8" + 31.61' - SECOND FLOOR - 11'-6 1/4" - 22.52' + SECOND FLOOR + 11'-6 1/4" + 22.52' - TOP OF TIE BEAM - 10'-0" - 21.00' + TOP OF TIE BEAM + 10'-0" + 21.00' - FIRST FLOOR (F.F.E.) - 0" - 11.00' + FIRST FLOOR (F.F.E.) + 0" + 11.00' - ENTRY PORCH AND LANAI SLAB - -4" - 10.67' + ENTRY PORCH AND LANAI SLAB + -4" + 10.67' - D.F.E. - -1'-0" - 10.00' + D.F.E. + -1'-0" + 10.00' - B.F.E. - -2'-0" - 9.00' + B.F.E. + -2'-0" + 9.00' - GARAGE SLAB - -2'-6" - 8.50' + GARAGE SLAB + -2'-6" + 8.50' - POOL DECK - -2'-7 1/4" - 8.40' + POOL DECK + -2'-7 1/4" + 8.40' - FINISH GRADE AT FOUNDATION - -3'-0" - 8.00' + FINISH GRADE AT FOUNDATION + -3'-0" + 8.00' - EXISTING GRADE - -3'-6" - 7.50' + EXISTING GRADE + -3'-6" + 7.50' diff --git a/docs/assets/plan-set-A-201-light.svg b/docs/assets/plan-set-A-201-light.svg index 36f1588..d17c420 100644 --- a/docs/assets/plan-set-A-201-light.svg +++ b/docs/assets/plan-set-A-201-light.svg @@ -1,7 +1,7 @@ - + - + @@ -65,7 +65,7 @@ - 101 + 101 @@ -110,7 +110,7 @@ - 102 + 102 @@ -119,7 +119,7 @@ - A + A @@ -128,7 +128,7 @@ - A + A @@ -137,7 +137,7 @@ - A + A @@ -146,16 +146,16 @@ - A + A - + - B + B @@ -165,77 +165,77 @@ - E + E - + - B.F.E. 9.00' NAVD (ZONE AE) + B.F.E. 9.00' NAVD (ZONE AE) - D.F.E. 10.00' NAVD (BFE + 1'-0") + D.F.E. 10.00' NAVD (BFE + 1'-0") - RIDGE - EL. 43.11' NAVD + RIDGE + EL. 43.11' NAVD - MEAN ROOF HT. - EL. 37.11' NAVD + MEAN ROOF HT. + EL. 37.11' NAVD - TOP OF PLATE - EL. 31.61' NAVD + TOP OF PLATE + EL. 31.61' NAVD - SECOND FLOOR - EL. 22.52' NAVD + SECOND FLOOR + EL. 22.52' NAVD - TOP OF TIE BEAM - EL. 21.00' NAVD + TOP OF TIE BEAM + EL. 21.00' NAVD - FIRST FLOOR (F.F.E.) - EL. 11.00' NAVD + FIRST FLOOR (F.F.E.) + EL. 11.00' NAVD - GARAGE SLAB - EL. 8.50' NAVD + GARAGE SLAB + EL. 8.50' NAVD - FINISH GRADE - EL. 8.00' NAVD + FINISH GRADE + EL. 8.00' NAVD @@ -243,7 +243,9 @@ - 3'-0" + + 3'-0" + @@ -251,15 +253,21 @@ - 10'-0" + + 10'-0" + - + + + - 1'-6 1/4" + + 1'-6 1/4" + @@ -267,7 +275,9 @@ - 9'-1 1/8" + + 9'-1 1/8" + @@ -275,51 +285,86 @@ - 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) - - - - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT - - - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT - - - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. - - - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM - - - IMPACT RATED WINDOW, - SEE A-601 - - - 5/8" STUCCO ON 8" CMU - - - 36" GUARD AT PORCH EDGE, - 4" SPHERE MAX. OPENING (R312.1) - - - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB - - - 16'-0" X 8'-0" IMPACT - OVERHEAD DOOR, SEE A-601 - - - ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS - AT 11", HANDRAILS BOTH SIDES AT 34"-38" - - - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) + + + + + + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + + + + + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + + + + + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + + + + + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + + + + + + IMPACT RATED WINDOW, + SEE A-601 + + + + + + 5/8" STUCCO ON 8" CMU + + + + + + 36" GUARD AT PORCH EDGE, + 4" SPHERE MAX. OPENING (R312.1) + + + + + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + + + + + + 16'-0" X 8'-0" IMPACT + OVERHEAD DOOR, SEE A-601 + + + + + + ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS + AT 11", HANDRAILS BOTH SIDES AT 34"-38" + + + + + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + @@ -481,7 +526,7 @@ - 108 + 108 @@ -496,10 +541,10 @@ - + - B + B @@ -517,7 +562,7 @@ - A + A @@ -536,7 +581,7 @@ - E + E @@ -555,69 +600,69 @@ - E + E - + - B.F.E. 9.00' NAVD (ZONE AE) + B.F.E. 9.00' NAVD (ZONE AE) - D.F.E. 10.00' NAVD (BFE + 1'-0") + D.F.E. 10.00' NAVD (BFE + 1'-0") - RIDGE - EL. 43.11' NAVD + RIDGE + EL. 43.11' NAVD - MEAN ROOF HT. - EL. 37.11' NAVD + MEAN ROOF HT. + EL. 37.11' NAVD - TOP OF PLATE - EL. 31.61' NAVD + TOP OF PLATE + EL. 31.61' NAVD - SECOND FLOOR - EL. 22.52' NAVD + SECOND FLOOR + EL. 22.52' NAVD - TOP OF TIE BEAM - EL. 21.00' NAVD + TOP OF TIE BEAM + EL. 21.00' NAVD - FIRST FLOOR (F.F.E.) - EL. 11.00' NAVD + FIRST FLOOR (F.F.E.) + EL. 11.00' NAVD - FINISH GRADE - EL. 8.00' NAVD + FINISH GRADE + EL. 8.00' NAVD @@ -625,7 +670,9 @@ - 3'-0" + + 3'-0" + @@ -633,15 +680,21 @@ - 10'-0" + + 10'-0" + - + + + - 1'-6 1/4" + + 1'-6 1/4" + @@ -649,7 +702,9 @@ - 9'-1 1/8" + + 9'-1 1/8" + @@ -657,51 +712,86 @@ - 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) - - - - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT - - - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT - - - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. - - - LANAI ROOF, STANDING SEAM - METAL AT 3:12, SEE S-102 - - - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM - - - IMPACT RATED WINDOW, - SEE A-601 - - - 5/8" STUCCO ON 8" CMU - - - 36" GUARD AT LANAI, 3 SIDES, - 4" SPHERE MAX. OPENING (R312.1) - - - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB - - - LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, - HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' - - - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + 27'-1 3/8" BLDG. HT., D.F.E. TO MEAN ROOF (35'-0" MAX.) + + + + + + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + + + + + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + + + + + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + + + + + + LANAI ROOF, STANDING SEAM + METAL AT 3:12, SEE S-102 + + + + + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + + + + + + IMPACT RATED WINDOW, + SEE A-601 + + + + + + 5/8" STUCCO ON 8" CMU + + + + + + 36" GUARD AT LANAI, 3 SIDES, + 4" SPHERE MAX. OPENING (R312.1) + + + + + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + + + + + + LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, + HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' + + + + + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + @@ -717,48 +807,48 @@ - HALYARD & MOSS - ENGINEERING - DEMO - 100 EXAMPLE WAY, SUITE 0 - CORAL HERON KEY, FL 34999 - CA NO. 00000 (FICTIONAL) - PROJECT - CALLOWAY RESIDENCE - NEW TWO-STORY SINGLE-FAMILY RESIDENCE - 218 SANDPIPER COVE DRIVE - CORAL HERON KEY, FLORIDA 34999 - OWNER - JUNIPER AND THEO CALLOWAY - LOT 14, BLOCK C, HERON SOUND ESTATES - PARCEL ID 00-00-00-00000-000-0140 - MANGROVE COUNTY (FICTIONAL) - REVISIONS - ENGINEER'S SEAL - DEMONSTRATION SET - NOT FOR CONSTRUCTION - NO SEAL. NO ENGINEER OF RECORD. - ENGINEER OF RECORD - J. R. HALYARD, P.E. (FICTIONAL) - FLORIDA P.E. NO. 00000 - DATE - JOB NO. - DRAWN BY - CHECKED BY - SCALE - SHEET TITLE - SHEET NUMBER + HALYARD & MOSS + ENGINEERING - DEMO + 100 EXAMPLE WAY, SUITE 0 + CORAL HERON KEY, FL 34999 + CA NO. 00000 (FICTIONAL) + PROJECT + CALLOWAY RESIDENCE + NEW TWO-STORY SINGLE-FAMILY RESIDENCE + 218 SANDPIPER COVE DRIVE + CORAL HERON KEY, FLORIDA 34999 + OWNER + JUNIPER AND THEO CALLOWAY + LOT 14, BLOCK C, HERON SOUND ESTATES + PARCEL ID 00-00-00-00000-000-0140 + MANGROVE COUNTY (FICTIONAL) + REVISIONS + ENGINEER'S SEAL + DEMONSTRATION SET + NOT FOR CONSTRUCTION + NO SEAL. NO ENGINEER OF RECORD. + ENGINEER OF RECORD + J. R. HALYARD, P.E. (FICTIONAL) + FLORIDA P.E. NO. 00000 + DATE + JOB NO. + DRAWN BY + CHECKED BY + SCALE + SHEET TITLE + SHEET NUMBER - 2026-11-13 - 26-0418 - AGENT - -- - AS NOTED - EXTERIOR ELEVATIONS, - SOUTH AND NORTH - ISSUED FOR PERMIT - A-201 - SHEET 6 OF 15 + 2026-11-13 + 26-0418 + AGENT + -- + AS NOTED + EXTERIOR ELEVATIONS, + SOUTH AND NORTH + ISSUED FOR PERMIT + A-201 + SHEET 6 OF 15 @@ -772,122 +862,122 @@ - NO. - DATE - DESCRIPTION - 0 - 2026-11-13 - ISSUED FOR PERMIT - 1 - 2026-11-13 - PLAN REVIEW RESPONSES + NO. + DATE + DESCRIPTION + 0 + 2026-11-13 + ISSUED FOR PERMIT + 1 + 2026-11-13 + PLAN REVIEW RESPONSES - 1 - A-201 - SOUTH (FRONT) ELEVATION - SCALE: 1/4" = 1'-0" + 1 + A-201 + SOUTH (FRONT) ELEVATION + SCALE: 1/4" = 1'-0" - 2 - A-201 - NORTH (REAR) ELEVATION - SCALE: 1/4" = 1'-0" + 2 + A-201 + NORTH (REAR) ELEVATION + SCALE: 1/4" = 1'-0" - ELEVATION NOTES + ELEVATION NOTES - 1. - ELEVATIONS IN FEET ARE IN NAVD 88. HEIGHTS ARE TO THE TOP OF CONCRETE OR THE TOP OF FRAMING. - 2. - FLOOD ZONE AE, PANEL 12000C0000J (DEMO). B.F.E. 9.00', D.F.E. 10.00', F.F.E. 11.00' NAVD. THE LOWEST - FLOOR IS 2'-0" ABOVE THE B.F.E. (FBC-R R322.2.1). - 3. - THE GARAGE IS BELOW THE D.F.E.: PARKING, ACCESS AND STORAGE ONLY. FLOOD DAMAGE-RESISTANT - MATERIALS BELOW THE D.F.E. FLOOD VENTS PER S-101. - 4. - STUCCO: 3 COATS, 7/8" ON LATH OVER FRAMING, 5/8" ON MASONRY, WITH CONTROL JOINTS AT 144 SQ. FT. - MAX. AND AT EVERY CHANGE OF SUBSTRATE (ASTM C926, C1063). - 5. - ALL WINDOWS AND DOORS IMPACT RATED, WITH FLORIDA PRODUCT APPROVAL, FOR THE DESIGN - PRESSURES ON A-601. WINDOW HEADS: FIRST FLOOR 8'-0", SECOND FLOOR 7'-2" A.F.F.; GARAGE WINDOW - 8'-0" ABOVE THE GARAGE SLAB. - 6. - ROOFING: STANDING SEAM METAL WITH FLORIDA PRODUCT APPROVAL, ON SELF-ADHERED - UNDERLAYMENT OVER 19/32" PLYWOOD DECK (FBC-R R905.10). - 7. - BUILDING HEIGHT IS MEASURED FROM THE D.F.E. (10.00' NAVD) TO THE MEAN ROOF HEIGHT: 27'-1 3/8", 35'-0" - MAX. IN RSF-6 RESIDENTIAL SINGLE-FAMILY (DEMO). - 8. - FINISH GRADE 8.00' NAVD AT THE FOUNDATION (EXISTING 7.50'), SLOPING AWAY 6" IN THE FIRST 10'-0" TO - THE SWALES (FBC-R R401.3). SEE C-101. - 9. - ENTRY STAIR: 5 RISERS OF 6.4" AND 4 TREADS OF 11" FROM THE PORCH (10.67') TO THE WALK. LANAI STEPS: - 4 RISERS OF 6.8" AND 3 TREADS OF 11" TO THE POOL DECK (8.40'). HANDRAILS BOTH SIDES OF EACH, 34" TO - 38" ABOVE THE NOSINGS (FBC-R R311.7.8). - 10. - GUARDS: 36" HIGH AT THE ENTRY PORCH'S OPEN EDGE AND THE LANAI'S WEST, NORTH AND EAST SIDES, - WHERE THE SLAB IS MORE THAN 30" ABOVE GRADE. NO OPENING PASSES A 4" SPHERE (FBC-R R312.1). - LEVELS - LEVEL - ABOVE F.F. - NAVD 88 + 1. + ELEVATIONS IN FEET ARE IN NAVD 88. HEIGHTS ARE TO THE TOP OF CONCRETE OR THE TOP OF FRAMING. + 2. + FLOOD ZONE AE, PANEL 12000C0000J (DEMO). B.F.E. 9.00', D.F.E. 10.00', F.F.E. 11.00' NAVD. THE LOWEST + FLOOR IS 2'-0" ABOVE THE B.F.E. (FBC-R R322.2.1). + 3. + THE GARAGE IS BELOW THE D.F.E.: PARKING, ACCESS AND STORAGE ONLY. FLOOD DAMAGE-RESISTANT + MATERIALS BELOW THE D.F.E. FLOOD VENTS PER S-101. + 4. + STUCCO: 3 COATS, 7/8" ON LATH OVER FRAMING, 5/8" ON MASONRY, WITH CONTROL JOINTS AT 144 SQ. FT. + MAX. AND AT EVERY CHANGE OF SUBSTRATE (ASTM C926, C1063). + 5. + ALL WINDOWS AND DOORS IMPACT RATED, WITH FLORIDA PRODUCT APPROVAL, FOR THE DESIGN + PRESSURES ON A-601. WINDOW HEADS: FIRST FLOOR 8'-0", SECOND FLOOR 7'-2" A.F.F.; GARAGE WINDOW + 8'-0" ABOVE THE GARAGE SLAB. + 6. + ROOFING: STANDING SEAM METAL WITH FLORIDA PRODUCT APPROVAL, ON SELF-ADHERED + UNDERLAYMENT OVER 19/32" PLYWOOD DECK (FBC-R R905.10). + 7. + BUILDING HEIGHT IS MEASURED FROM THE D.F.E. (10.00' NAVD) TO THE MEAN ROOF HEIGHT: 27'-1 3/8", 35'-0" + MAX. IN RSF-6 RESIDENTIAL SINGLE-FAMILY (DEMO). + 8. + FINISH GRADE 8.00' NAVD AT THE FOUNDATION (EXISTING 7.50'), SLOPING AWAY 6" IN THE FIRST 10'-0" TO + THE SWALES (FBC-R R401.3). SEE C-101. + 9. + ENTRY STAIR: 5 RISERS OF 6.4" AND 4 TREADS OF 11" FROM THE PORCH (10.67') TO THE WALK. LANAI STEPS: + 4 RISERS OF 6.8" AND 3 TREADS OF 11" TO THE POOL DECK (8.40'). HANDRAILS BOTH SIDES OF EACH, 34" TO + 38" ABOVE THE NOSINGS (FBC-R R311.7.8). + 10. + GUARDS: 36" HIGH AT THE ENTRY PORCH'S OPEN EDGE AND THE LANAI'S WEST, NORTH AND EAST SIDES, + WHERE THE SLAB IS MORE THAN 30" ABOVE GRADE. NO OPENING PASSES A 4" SPHERE (FBC-R R312.1). + LEVELS + LEVEL + ABOVE F.F. + NAVD 88 - RIDGE - 32'-1 3/8" - 43.11' + RIDGE + 32'-1 3/8" + 43.11' - MEAN ROOF HEIGHT - 26'-1 3/8" - 37.11' + MEAN ROOF HEIGHT + 26'-1 3/8" + 37.11' - TOP OF PLATE, 2ND FLOOR - 20'-7 3/8" - 31.61' + TOP OF PLATE, 2ND FLOOR + 20'-7 3/8" + 31.61' - SECOND FLOOR - 11'-6 1/4" - 22.52' + SECOND FLOOR + 11'-6 1/4" + 22.52' - TOP OF TIE BEAM - 10'-0" - 21.00' + TOP OF TIE BEAM + 10'-0" + 21.00' - FIRST FLOOR (F.F.E.) - 0" - 11.00' + FIRST FLOOR (F.F.E.) + 0" + 11.00' - ENTRY PORCH AND LANAI SLAB - -4" - 10.67' + ENTRY PORCH AND LANAI SLAB + -4" + 10.67' - D.F.E. - -1'-0" - 10.00' + D.F.E. + -1'-0" + 10.00' - B.F.E. - -2'-0" - 9.00' + B.F.E. + -2'-0" + 9.00' - GARAGE SLAB - -2'-6" - 8.50' + GARAGE SLAB + -2'-6" + 8.50' - POOL DECK - -2'-7 1/4" - 8.40' + POOL DECK + -2'-7 1/4" + 8.40' - FINISH GRADE AT FOUNDATION - -3'-0" - 8.00' + FINISH GRADE AT FOUNDATION + -3'-0" + 8.00' - EXISTING GRADE - -3'-6" - 7.50' + EXISTING GRADE + -3'-6" + 7.50' diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index a3b441d..d592f7f 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -64,7 +64,9 @@ - 24.0' + + 24.0' + @@ -72,7 +74,9 @@ - 52.0' + + 52.0' + @@ -80,7 +84,9 @@ - 24.0' + + 24.0' + @@ -88,7 +94,9 @@ - 30.0' + + 30.0' + @@ -96,7 +104,9 @@ - 49.0' + + 49.0' + @@ -104,7 +114,9 @@ - 61.0' + + 61.0' + @@ -112,7 +124,12 @@ - 44'-0" + + 44'-0" + + + BUILDING + N 90°00'00" E 100.00' S 00°00'00" E 140.00' @@ -217,8 +234,8 @@ RESIDENCE AT LOT 12, BLOCK 3 SITE PLAN 2026-11-11 - AS NOTED - AB + AS NOTED + AB CD C-101 @@ -253,13 +270,13 @@ 10 20 FEET - SITE DATA + SITE DATA PARCEL LOT 12, BLOCK 3 ZONING R-1 SINGLE-FAMILY - LOT AREA + LOT AREA 14,000 SF (0.32 AC) BUILDING FOOTPRINT 2,398 SF @@ -332,7 +349,7 @@ PROPERTY LINE - ADJOINING LOT LINE + ADJOINING LOT LINE BUILDING SETBACK LINE @@ -351,10 +368,10 @@ EXISTING TREE TO REMAIN - ABBREVIATIONS + ABBREVIATIONS - AC - ACRES + AC + ACRES CONC. CONCRETE ELEV. diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index 576db28..5126fcb 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -64,7 +64,9 @@ - 24.0' + + 24.0' + @@ -72,7 +74,9 @@ - 52.0' + + 52.0' + @@ -80,7 +84,9 @@ - 24.0' + + 24.0' + @@ -88,7 +94,9 @@ - 30.0' + + 30.0' + @@ -96,7 +104,9 @@ - 49.0' + + 49.0' + @@ -104,7 +114,9 @@ - 61.0' + + 61.0' + @@ -112,7 +124,12 @@ - 44'-0" + + 44'-0" + + + BUILDING + N 90°00'00" E 100.00' S 00°00'00" E 140.00' @@ -217,8 +234,8 @@ RESIDENCE AT LOT 12, BLOCK 3 SITE PLAN 2026-11-11 - AS NOTED - AB + AS NOTED + AB CD C-101 @@ -253,13 +270,13 @@ 10 20 FEET - SITE DATA + SITE DATA PARCEL LOT 12, BLOCK 3 ZONING R-1 SINGLE-FAMILY - LOT AREA + LOT AREA 14,000 SF (0.32 AC) BUILDING FOOTPRINT 2,398 SF @@ -332,7 +349,7 @@ PROPERTY LINE - ADJOINING LOT LINE + ADJOINING LOT LINE BUILDING SETBACK LINE @@ -351,10 +368,10 @@ EXISTING TREE TO REMAIN - ABBREVIATIONS + ABBREVIATIONS - AC - ACRES + AC + ACRES CONC. CONCRETE ELEV. diff --git a/docs/dimensions.md b/docs/dimensions.md index f8cfecf..7011f74 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -39,23 +39,29 @@ Every dimension names a dimension style, which says how it is drawn and how it w measures. `d.dimensionStyle(definition)` defines one. A style is defined once, under a name no other style has, and before the first dimension that names it. -| Field | What it sets | -| ------------------ | ---------------------------------------------------------------------------------------------- | -| `name` | The style's name, held to the rules of a layer's name, and at most 255 characters. | -| `textStyle` | The text style of the text. `"Standard"` unless given. | -| `textHeight` | The height of the text. Greater than 0. | -| `arrowhead` | `"closed-filled"`, the default, or `"architectural-tick"`. `ARROWHEADS` lists them. | -| `arrowSize` | The length of an arrowhead. 0 draws none. | -| `extensionOffset` | How far from its point an extension line starts. | -| `extensionBeyond` | How far an extension line runs past the dimension line. | -| `textGap` | The gap between the dimension line and the text above it. | -| `scale` | What every size above is multiplied by. 1 unless given. | -| `units` | `"decimal"`, the default, or `"architectural"`, which writes feet and inches: `4'-1 7/16"`. | -| `precision` | A whole number from 0 to 8: the decimals, or in feet and inches the least fraction, 1/2^n. | -| `prefix`, `suffix` | Written before and after each measurement. | -| `suppressZeros` | Decimal units: `"leading"` writes 0.5 as `.5`, `"trailing"` 52.50 as `52.5`, `"both"` both. | -| `feetInchZeros` | Feet and inches: which zeros are written. `"inches"` unless given: see below. | -| `measurementScale` | What a length is multiplied by before it is written: 12 writes feet as inches. 1 unless given. | +| Field | What it sets | +| --------------------- | ----------------------------------------------------------------------------------------------- | +| `name` | The style's name, held to the rules of a layer's name, and at most 255 characters. | +| `textStyle` | The text style of the text. `"Standard"` unless given. | +| `textHeight` | The height of the text. Greater than 0. | +| `arrowhead` | `"closed-filled"`, the default, `"architectural-tick"` or `"oblique"`. `ARROWHEADS` lists them. | +| `arrowSize` | The length of an arrowhead. 0 draws none. | +| `extensionOffset` | How far from its point an extension line starts. | +| `extensionBeyond` | How far an extension line runs past the dimension line. | +| `textGap` | The gap between the dimension line and the text above it. | +| `scale` | What every size above is multiplied by. 1 unless given. | +| `units` | `"decimal"`, the default, or `"architectural"`, which writes feet and inches: `4'-1 7/16"`. | +| `precision` | A whole number from 0 to 8: the decimals, or in feet and inches the least fraction, 1/2^n. | +| `prefix`, `suffix` | Written before and after each measurement. | +| `suppressZeros` | Decimal units: `"leading"` writes 0.5 as `.5`, `"trailing"` 52.50 as `52.5`, `"both"` both. | +| `feetInchZeros` | Feet and inches: which zeros are written. `"inches"` unless given: see below. | +| `measurementScale` | What a length is multiplied by before it is written: 12 writes feet as inches. 1 unless given. | +| `fraction` | Feet and inches: `"inline"`, the default, as `4'-1 7/16"`, `"stacked"` or `"diagonal"`. | +| `fractionScale` | A stacked fraction's height as a share of the text's, from 0.25 to 1. 1 unless given. | +| `textPlacement` | `"above"` the dimension line, the default, or `"centered"` in a break of it. | +| `textFit` | A text with no room between the extension lines: `"inside"` them, the default, or `"leader"`. | +| `dimensionLineweight` | The lineweight of the dimension line, its arrowheads and a leader, in millimetres. | +| `extensionLineweight` | The lineweight of the extension lines, in millimetres. | ### Sizes and the scale @@ -70,16 +76,21 @@ them when it draws. ### How a dimension is drawn -Where a style has no field, every dimension is drawn one way: - -- The text is above the dimension line, in the middle between the extension lines, and reads - along the line. It is turned to read from the bottom or from the right of the sheet. +- The text is in the middle between the extension lines and reads along the line, turned to + read from the bottom or from the right of the sheet. Above the line, its box stands one gap + off it; `textPlacement: "centered"` puts the middle of its box on the line, which breaks a gap + either side of it. The box is the box of the text as the leading CAD app sets it: from the top + of its tallest letter or stack to the foot of its lowest letter. - The dimension line runs from one extension line to the other. - A closed filled arrowhead is as long as `arrowSize` and a third as wide, with its tip on the - extension line. An architectural tick is a stroke at 45 degrees through the end of the - dimension line, and the dimension line runs one arrow size past each extension line. + extension line. An architectural tick is a heavy stroke at 45 degrees through the end of the + dimension line, and an oblique tick the same stroke as thin as the dimension line; with + either, the dimension line runs one arrow size past each extension line. - The measurement is in decimal units of the drawing, or in feet and inches, times - `measurementScale`, with the fraction on the line. + `measurementScale`, with the fraction on the line unless `fraction` stacks it. +- The dimension line, its arrowheads and a leader take `dimensionLineweight`, and the + extension lines `extensionLineweight`. Without them, each takes the dimension's own: its + layer's. ### What a dimension needs room for @@ -89,17 +100,34 @@ font. tsdraft gives the text room for the widest it can be in any font of `FONTS refuses a dimension with closed filled arrowheads that measures no more than ```text -max(2 × arrowSize, widths × textHeight × widthFactor + lean) + 2 × textGap +text above the line: max(2 × arrowSize, text) + 2 × textGap +text centered in a break: text + 2 × arrowSize + 2 × textGap +text = widths × textHeight × widthFactor + lean ``` -each size times the style's scale. `widths` adds up a width for each character of the text: +each size times the style's scale. The text is the wider of the words above the line and below +it, with a stacked fraction counted as its longer part and a diagonal one as its two parts and a +slash. `lint` also takes the text as tsdraft lays it out in its font, where that is wider: a narrow +font does not narrow the gap of a diagonal stack. `widths` adds up a width for each character of the text: 1.1 for a figure, a point, an apostrophe, a quotation mark and a space, 1.104 for `9`, 1.239 for a hyphen and a slash, and 2 for any other character. `widthFactor` is the text style's, and `lean` is `textHeight × |tan(obliqueAngle)|` for a slanted text style. At 1" = 10' with the sizes in the example above and closed filled arrowheads, a dimension of `6.0'` has room and one of `3.8'` -does not. A dimension with ticks, or with an arrow size of 0, is drawn the same whether its -text fits or not, so it may be as short as it likes: its text then lies over the extension -lines. +does not. A dimension with ticks, or with an arrow size of 0, may be as short as it likes. Ticks turn +outward when the text does not fit: above the line, when the text is wider than the line less +two gaps; centered in it, when the line is shorter than the text and two arrow sizes. The +dimension line then breaks at each tick. + +### A text that does not fit + +With `textFit: "leader"`, a text that is wider than the line less two gaps moves out on a +leader, as the leading CAD app moves it: from the middle of the dimension line, away from the +points, to an elbow past the reach of the extension lines and a gap and a half, leaning toward +where the text reads, then along a landing to the text. Above the line the text stands a gap +over a landing as long as it and a gap either side; centered, it follows a landing two gaps +long. The ticks stay inward unless the line is shorter than two gaps. `lint` refuses what is +not laid out yet: words below the line of a text that moves out, arrowheads twice the text's +height or longer in such a style, and closed filled arrowheads with the text centered. ## The two kinds @@ -118,6 +146,10 @@ Both take `style`, the name of the dimension style, and optionally: - `text`, a text to draw in place of the measurement. `<>` in it stands for the measurement as the style writes it, so `"<> TYP"` adds to it and `"VARIES"` replaces it. Only the first `<>` is the measurement. +- `textBelow`, words under the dimension line, opposite the text: `{ textBelow: "WINDOW HEAD + HT." }` writes the measurement over the line and the words under it. The first `<>` of + `text` and `textBelow` together is the measurement. With words below, a centered text stands a + gap above the line too, and the line breaks for the wider of the two. - `id`, as any entity takes one: see [Ids](format.md#ids). A dimension is on the current layer, and is drawn in that layer's color and lineweight. It @@ -147,6 +179,11 @@ writes feet, a hyphen, inches, and the fraction in lowest terms after a space, w mark: 49.4375 is `4'-1 7/16"` at a precision of 4, and `4'-1"` at 0. A drawing in inches leaves `measurementScale` at 1, and a drawing in feet gives it 12. +`fraction: "stacked"` stacks the fraction over a bar and `"diagonal"` beside a slash, right after +the inches, at `fractionScale` of the text's height: `4'-1` and a stacked `7/16`. A stacked part +stands by its own ink, as the leading CAD app sets it, so a 7 over 16 stands a little lower than +a 1 over 16. + `feetInchZeros` says which zeros are written: | `feetInchZeros` | 48 | 6 | 0.5 | @@ -175,12 +212,12 @@ file's picture draws the arrowheads with. `toSVG` draws each dimension as the leading CAD app does, in model space, through a viewport and on a sheet, in its layer's color and lineweight. A dimension is a `` with `data-layer`, `data-entity`, `data-id` and `data-dimension`, the string it reads. Its children have a -`data-part`: `extension-line`, `dimension-line`, `arrowhead` or `text`. A drawing's extents -take its dimensions in, text included. +`data-part`: `extension-line`, `dimension-line`, `leader`, `arrowhead` or `text`, and each text +is a paragraph group as [paragraphs](paragraphs.md) are drawn, stacks included. A drawing's +extents take its dimensions in, text included. -`inspectText` takes a dimension's text for a text where the picture puts it, measured as -`measureText` measures any text, so it warns of a text that plots over it. A dimension's text -that its room holds never measures longer than that room in any font. +`inspectText` takes each line of a dimension's texts for a text where the picture puts it, so +it warns of a text that plots over it. The `tsdraft` command lists each dimension in its JSON, with its id, the number it measures and the string it reads: see [The JSON](command.md#the-json). @@ -210,6 +247,10 @@ Each of these is an error, at the builder's call and in `lint`. The rule is `dim - The precision is a whole number from 0 to 8. The leading CAD app's `AUDIT` reports any other. - `units` is `"decimal"` or `"architectural"`. `suppressZeros` is for a style in decimal units and `feetInchZeros` for one in architectural units, and a style has only its own. +- `fraction` is one of `DIMENSION_FRACTIONS`, `textPlacement` one of + `DIMENSION_TEXT_PLACEMENTS` and `textFit` one of `DIMENSION_TEXT_FITS`. A stacked fraction + and its `fractionScale`, from 0.25 to 1, are for a style in architectural units, and a + `fractionScale` for a fraction that is stacked. A lineweight is one of `LINEWEIGHTS`. - An arrowhead is one of `ARROWHEADS`. - A prefix, a suffix and a dimension's text have none of `\`, `{` and `}`, which the leading CAD app reads as the formatting of the text, and are single lines as any text is. A prefix has no `<>`. @@ -233,10 +274,13 @@ Each of these is an error, at the builder's call and in `lint`. The rule is `dim - A linear dimension measures along an angle from -360 to 360. This is tsdraft's own rule: an angle beyond a turn is refused, so that one direction has one angle. - A dimension with closed filled arrowheads has the room given above. +- A text centered in its line has the room of its width and two gaps there, unless it moves + out on a leader. Where its pieces then go is not laid out yet. +- What [A text that does not fit](#a-text-that-does-not-fit) says is not laid out yet. - A dimension is not in a block. The leading CAD app draws nothing for a dimension inside a block when it opens the file, so an insert of the block would show nothing of it. -- No block is named `_ArchTick`, in any case of its letters. The leading CAD app draws the - architectural tick with the block of that name, so a block of yours would be drawn as the tick. +- No block is named `_ArchTick` or `_Oblique`, in any case of its letters. The leading CAD app + draws the ticks with the blocks of those names, so a block of yours would be drawn as a tick. - An R12 drawing has no dimensions. `lint` warns of a prefix, a suffix or a text with `%%`, which the leading CAD app reads as the start @@ -264,8 +308,10 @@ table, the block `_ArchTick` when a style has ticks, and each dimension with its style, its text, what it reads, and the block of its picture. The picture is what the leading CAD app draws for the dimension, as that app writes it: the two -extension lines, the dimension line, two filled triangles or two inserts of `_ArchTick`, and the -text, each on the dimension's layer and in the dimension's color. That app shows the picture the +extension lines, the dimension line in one piece or more, the leader to a text moved out, two +filled triangles or two inserts of `_ArchTick` or `_Oblique`, and each text as a paragraph, each +on the dimension's layer and in the dimension's color. A dimension with words below holds its +text and them as one, `<>\XWINDOW HEAD HT.`, as that app does. That app shows the picture the file holds when it opens the drawing, and when another drawing attaches the file as an xref or inserts it as a block. It draws a new picture when the dimension's points or style change. A program that draws a dimension from its block, as most programs that read DXF do, shows the @@ -284,7 +330,7 @@ no dimension style holds nothing else for dimensions. ## What is not drawn yet -Leaders, and angular, radial, diameter and ordinate dimensions. Tolerances and alternate -units. Feet and inches, fractions and the other unit formats: a measurement is a decimal -number. A dimension tied to an entity, which follows it when it moves: a dimension's points -are the ones the code gives it. +Angular, radial, diameter, arc length and ordinate dimensions. Tolerances and alternate +units, and the unit formats but decimal and feet and inches. The other fits of a text, such as +moving the arrowheads first, and a text a drafter placed. A dimension tied to an entity, which +follows it when it moves: a dimension's points are the ones the code gives it. diff --git a/docs/format.md b/docs/format.md index f84e29d..0a31ccb 100644 --- a/docs/format.md +++ b/docs/format.md @@ -57,10 +57,12 @@ layouts existed. [Layouts](layouts.md) describes them. A drawing lists its dimension styles in `dimensionStyles`, and leaves the field out when it has none. A style has a `name`, a `textHeight`, an `arrowSize`, an `extensionOffset`, an `extensionBeyond`, a `textGap` and a `precision`, and where they are set a `textStyle`, an -`arrowhead`, a `scale`, a `prefix`, a `suffix`, `suppressZeros` and a `measurementScale`. A +`arrowhead`, a `scale`, a `prefix`, a `suffix`, `suppressZeros`, `feetInchZeros`, a +`measurementScale`, a `fraction`, a `fractionScale`, a `textPlacement`, a `textFit`, a +`dimensionLineweight` and an `extensionLineweight`. A dimension is an entity of kind `"linear-dimension"` or `"aligned-dimension"`, in `drawing.entities` or in a layout's `entities`, with its `layer`, `style`, `from` and `to`, -and a `text` where it has one. A linear one has `line`, a point of its dimension line, and an +and a `text` and a `textBelow` where it has them. A linear one has `line`, a point of its dimension line, and an `angle` where it does not measure along X, from -360 to 360; the builder keeps it from 0 up to 360. An aligned one has `offset`. Neither has a linetype or a lineweight. A drawing with no dimension has the JSON it had before dimensions existed. [Dimensions](dimensions.md) describes them. diff --git a/docs/reading.md b/docs/reading.md index ca0f9e3..e521777 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -53,7 +53,7 @@ states and keeps each object's handle, and it keeps going past what it does not `$LTSCALE`, `$PSLTSCALE`, `$MSLTSCALE`, `$DIMSCALE` and the current styles. - The tables: `layers` with their state, `linetypes`, `textStyles` and `dimensionStyles`, each style with whether it is annotative, and a dimension style with the units it writes lengths - in. Two entries of one name are both kept, in the order of the file. + in, where its text goes, how it writes a fraction, its lineweights and its arrowheads' block. Two entries of one name are both kept, in the order of the file. - `blocks`: each with its base point, its attribute definitions and its entities, below. What else a block draws is counted under `other` by kind, such as `HATCH` or `LWPOLYLINE in 3D`, and so is what stands in another plane than the block's. An entity the file marks invisible, @@ -113,7 +113,8 @@ A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers `measureMtext` lay it out as tsdraft lays out a paragraph: [Paragraphs](paragraphs.md#reading). - `dimension`: a linear or aligned dimension, with its two points, the point where its dimension line meets its second extension line, its direction, the middle of its text, what it measures, - its text, its style and the block of its picture. The other kinds of dimension are counted + its text and the words below its line, which the file holds after `\X`, its style and the + block of its picture. The other kinds of dimension are counted under `other`. - `multileader`: one with straight shafts, one root and a note, with its style, each shaft from its tip, the point where the shafts meet, the landing's direction and length, its note, where diff --git a/docs/rules.md b/docs/rules.md index f94ce5f..071c6a1 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -196,8 +196,11 @@ it would take `1e+100` for `1e+10` and report nothing. - A linear dimension measures along an angle from -360 to 360, by tsdraft's own rule, so that one direction has one angle. - A dimension is not in a block. The leading CAD app draws nothing for it when it opens the file. -- A block is not named `_ArchTick`, in any case. The leading CAD app draws a dimension's - architectural tick with the block of that name. +- A block is not named `_ArchTick` or `_Oblique`, in any case. The leading CAD app draws a + dimension's ticks with the blocks of those names. +- What a dimension style sets of how it looks is one of its lists, a stacked fraction is in + feet and inches, and a dimension leaves out what [Dimensions](dimensions.md#what-lint-reports) + says is not laid out yet. - An R12 drawing has no dimensions. - A leader names a leader style the drawing defines, and not `Standard`, which is the leading CAD app's own. A leader style's name follows the rules of a dimension style's name. Its text style, diff --git a/docs/standard.md b/docs/standard.md index 675c0ab..d1522d7 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -144,9 +144,11 @@ drawing has. is written, at most 64 characters, and `ratio` is above 0. **`dimensionStyles`**: `role` names the text role of a dimension's text, `arrowhead`, -`arrowSize`, `extensionOffset`, `extensionBeyond` and `textGap` are paper sizes, and `writing` -says how a length is written in each unit of a drawing, with `precision`, `prefix`, `suffix`, -`suppressZeros` and `measurementScale`. A drawing in a unit `writing` does not list draws no +`arrowSize`, `extensionOffset`, `extensionBeyond` and `textGap` are paper sizes, +`textPlacement`, `textFit`, `dimensionLineweight` and `extensionLineweight` set where the text +goes and the pens, and `writing` says how a length is written in each unit of a drawing, with +`precision`, `prefix`, `suffix`, `suppressZeros`, `measurementScale`, and for feet and inches +`fraction` and `fractionScale`. A drawing in a unit `writing` does not list draws no dimension in that style. The style's name in the leading CAD app is the id in capitals, `DIMS` on a layout, and with a scale's id after it in model space: `DIMS-1in-10ft`. No dimension style is named `standard`, and two names among every style at every scale that that app takes for one are an error. @@ -226,7 +228,10 @@ the library exports: `DASHED`, `HIDDEN`, `CENTER`, `PHANTOM`, `DASHDOT` and `DOT roles are `note` and `dimension`, 3/32 in, `label`, 1/8 in, `heading`, 3/16 in, and `title`, 1/4 in, each in Arial. The scales are `1in-10ft` to `1in-100ft`, labelled `1" = 10'` and so on, and `1-8in-1ft` to `3in-1ft`, labelled `1/8" = 1'-0"` and so on. The dimension style `dims` -writes feet to a tenth with `'`, inches whole with `"`, and millimetres whole. The title block +writes feet to a tenth with `'`, inches whole with `"`, and millimetres whole, with +architectural ticks and the text above the line. `feet-inches` writes feet and inches to the +nearest 1/16". `arrows`, from version 2, has closed filled arrows with the text centered in a +break of the line, as civil and structural sheets draw them, and writes feet to a hundredth. The title block `plain` and the sheet format `arch-d`, on ARCH D, are in [Title blocks](title-blocks.md#the-title-block-of-a-standard). diff --git a/examples/site-plan.ts b/examples/site-plan.ts index 04109fb..4b47864 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -390,12 +390,12 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee d.linearDimension(upLot[i - 1]!, upLot[i]!, [up, 0], { view: plan, along: "y" }); } // The building in feet and inches, as an architect dimensions it, in the standard's style - // for that: its west wall, outside it. + // for that: its west wall, outside it, with what it measures written under the line. d.linearDimension( [houseX, houseY], [houseX, houseY + house.depth], [houseX - plan.paper(3 / 8), 0], - { view: plan, along: "y", style: "feet-inches" }, + { view: plan, along: "y", style: "feet-inches", textBelow: "BUILDING" }, ); }); diff --git a/scripts/readme-drawing.ts b/scripts/readme-drawing.ts index b95ea9d..ea23790 100644 --- a/scripts/readme-drawing.ts +++ b/scripts/readme-drawing.ts @@ -193,6 +193,8 @@ function sheetPicture( } const unitsPerPixel = w / width; const wider = (pen * unitsPerPixel) / base; + // The layer of each group open around a line: a dimension's text is a group inside its own. + const open: (string | undefined)[] = []; let entity: string | undefined; const out = svg.split("\n").map((line) => { if (line.startsWith("") entity = undefined; + if (GROUPED.test(line)) open.push((entity = layer ?? entity)); + else if (/^\s*]*[^/]>$/.test(line)) open.push(entity); + else if (line.trim() === "") { + open.pop(); + entity = open.at(-1); + } const drawnOn = layer ?? entity; const role = drawnOn === undefined ? undefined : roles[drawnOn]; if (drawnOn !== undefined && !role) throw new Error(`Layer ${drawnOn} of ${name} has no role`); @@ -289,6 +295,8 @@ for (const picture of pictures) { let openGroup = ""; // The parts of a dimension or a leader, and the end of its group, are drawn as the group is. let entity: { role: Role; tag: string } | undefined; + // The groups open inside the entity's own, such as a dimension's text. + let inner = 0; for (const line of lines) { const layer = /data-layer="([^"]+)"/.exec(line)?.[1]; const own = layer === undefined ? undefined : roles[layer]; @@ -299,8 +307,12 @@ for (const picture of pictures) { const groupTag = entity?.tag ?? (role ? ` ` : ""); - if (role && GROUPED.test(line)) entity = { role, tag: groupTag }; - else if (line.trim() === "") entity = undefined; + if (entity && /^\s*]*[^/]>$/.test(line)) inner++; + else if (role && GROUPED.test(line)) entity = { role, tag: groupTag }; + else if (line.trim() === "") { + if (inner > 0) inner--; + else entity = undefined; + } if (groupTag !== openGroup) { if (openGroup) body.push(" "); if (groupTag) body.push(groupTag); diff --git a/src/arrowheads.ts b/src/arrowheads.ts index 4ce839f..ce44fc7 100644 --- a/src/arrowheads.ts +++ b/src/arrowheads.ts @@ -24,7 +24,8 @@ export interface ArrowheadInfo { * Every arrowhead a dimension style may have, by the name the leading CAD app's dimension style * dialog gives it. `"closed-filled"` is a solid arrow as long as the arrow size and a third as * wide. `"architectural-tick"` is a heavy stroke through the end of the dimension line, at 45 - * degrees to it, as long as the arrow size times the square root of 2. + * degrees to it, as long as the arrow size times the square root of 2. `"oblique"` is the same + * tick drawn as a line, as heavy as the dimension line. */ export const ARROWHEADS = { "closed-filled": {}, @@ -32,6 +33,10 @@ export const ARROWHEADS = { block: "_ArchTick", stroke: { from: [-0.5, -0.5], to: [0.5, 0.5], width: 0.15 }, }, + oblique: { + block: "_Oblique", + stroke: { from: [-0.5, -0.5], to: [0.5, 0.5], width: 0 }, + }, } as const satisfies Readonly>; /** The name of an arrowhead a dimension style may have. */ @@ -151,6 +156,7 @@ export function leaderArrowheadInfo(name: unknown): LeaderArrowheadInfo | undefi /** The blocks of every arrowhead that has one, of dimensions and of leaders. */ export const ARROWHEAD_BLOCKS: readonly string[] = [ ARROWHEADS["architectural-tick"].block, + ARROWHEADS.oblique.block, LEADER_ARROWHEADS.open.block, LEADER_ARROWHEADS.dot.block, LEADER_ARROWHEADS.none.block, @@ -171,6 +177,21 @@ export const DIMENSION_UNITS = ["decimal", "architectural"] as const; */ export const FEET_INCH_ZEROS = ["inches", "feet", "both", "neither"] as const; +/** + * How a measurement in feet and inches writes its fraction: on the line, as 4'-1 7/16"; stacked + * over a bar; or stacked diagonally, beside a slash. + */ +export const DIMENSION_FRACTIONS = ["inline", "stacked", "diagonal"] as const; + +/** Where a dimension's text is: above its line, or centered in a break of it. */ +export const DIMENSION_TEXT_PLACEMENTS = ["above", "centered"] as const; + +/** + * Where a dimension's text goes when it does not fit between the extension lines: between them + * all the same, or outside, on a leader. + */ +export const DIMENSION_TEXT_FITS = ["inside", "leader"] as const; + /** The most decimals the leading CAD app writes a measurement with. */ export const MAX_PRECISION = 8; diff --git a/src/dimensions.ts b/src/dimensions.ts index a0add8d..76bffc1 100644 --- a/src/dimensions.ts +++ b/src/dimensions.ts @@ -17,10 +17,20 @@ import { type Arrowhead, } from "./arrowheads.ts"; import { blockHandles } from "./blocks.ts"; +import { STANDARD_FONT } from "./fonts.ts"; +import { + layoutDimensionText, + type ParagraphLayout, + type ParagraphToMeasure, +} from "./paragraphs.ts"; import { written } from "./format.ts"; import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; import { + arrowRoomProblem, + DIMENSION_CENTERED_WIDE, + DIMENSION_LEADER_ARROWS, + DIMENSION_LEADER_BELOW, dimensionMeasureProblem, dimensionStyleNameProblem, idKey, @@ -73,6 +83,12 @@ export interface DimensionPictureHandles { readonly dimensionLine: string; readonly arrowheads: readonly [string, string]; readonly text: string; + /** The pieces of the dimension line: the first is `dimensionLine`. */ + readonly dimensionLines: readonly [string, string, string, string]; + /** The lines of the leader to a text moved outside. */ + readonly leader: readonly [string, string]; + /** The text below the dimension line. */ + readonly belowText: string; } /** Where a dimension is: its id, or else its place among the entities of its space. */ @@ -100,6 +116,14 @@ export function validDimensionPictureHandles(place: DimensionPlace): DimensionPi dimensionLine: handle("dimension-line"), arrowheads: [handle("arrowhead-1"), handle("arrowhead-2")], text: handle("text"), + dimensionLines: [ + handle("dimension-line"), + handle("dimension-line-2"), + handle("dimension-line-3"), + handle("dimension-line-4"), + ], + leader: [handle("leader-1"), handle("leader-2")], + belowText: handle("text-below"), }; } @@ -123,6 +147,9 @@ export function pictureHandleList(handles: DimensionPictureHandles): string[] { handles.dimensionLine, ...handles.arrowheads, handles.text, + ...handles.dimensionLines.slice(1), + ...handles.leader, + handles.belowText, ]; } @@ -208,6 +235,8 @@ export type MeasurementFormat = Pick< | "suppressZeros" | "feetInchZeros" | "measurementScale" + | "fraction" + | "fractionScale" >; /** @@ -301,11 +330,22 @@ export function feetAndInches(length: number, format: MeasurementFormat): string const zeros = format.feetInchZeros ?? "inches"; const zeroFeet = zeros === "feet" || zeros === "both"; const zeroInches = zeros === "inches" || zeros === "both"; - const fraction = numerator > 0 ? `${numerator}/${denominator}` : ""; + const stacked = format.fraction === "stacked" || format.fraction === "diagonal"; + // A stack is written at the style's share of the height, and follows the inches with no space. + const fraction = + numerator === 0 + ? "" + : stacked + ? `{\\H${written(format.fractionScale ?? 1)}x;\\S${numerator}${format.fraction === "stacked" ? "/" : "#"}${denominator};}` + : `${numerator}/${denominator}`; const showFeet = feet > 0 || zeroFeet; const showInches = rest > 0 || zeroInches || !showFeet; const inchText = - fraction === "" ? String(inches) : inches > 0 || showFeet ? `${inches} ${fraction}` : fraction; + fraction === "" + ? String(inches) + : inches > 0 || showFeet + ? `${inches}${stacked ? "" : " "}${fraction}` + : fraction; if (!showFeet) return `${inchText}"`; return showInches ? `${feet}'-${inchText}"` : `${feet}'`; } @@ -324,8 +364,42 @@ export function measurementText(length: number, format: MeasurementFormat, text? return at < 0 ? text : `${text.slice(0, at)}${measured}${text.slice(at + 2)}`; } +/** + * The text a dimension holds in its file: its own text, and the words below its line after `\\X`, + * which the leading CAD app reads as the start of the part below. + */ +export function dimensionFileText( + dimension: Pick, +): string | undefined { + if (dimension.textBelow === undefined) return dimension.text; + return `${dimension.text ?? "<>"}\\X${dimension.textBelow}`; +} + +/** + * What a dimension draws above its line and below it: its text with the first `<>` standing for + * the measurement, cut at the first `\\X`. Undefined below when it has no words there. + */ +export function dimensionTexts( + dimension: Pick, + length: number, + format: MeasurementFormat, +): readonly [above: string, below: string | undefined] { + const drawn = measurementText(length, format, dimensionFileText(dimension)); + const at = drawn.indexOf("\\X"); + return at < 0 ? [drawn, undefined] : [drawn.slice(0, at), drawn.slice(at + 2)]; +} + +/** + * The value of the MTEXT a dimension's picture draws for a text: with the code that centers what + * is stacked in it, as the leading CAD app writes it. + */ +export function mtextOfLabel(value: string): string { + return `\\A1;${value}`; +} + /** The text of a dimension as the leading CAD app draws it, and where. */ export interface DimensionLabel { + /** What it reads, with the codes of a paragraph's value, such as a stacked fraction's. */ readonly value: string; /** The middle of the text's baseline. */ readonly at: Point; @@ -370,8 +444,15 @@ export interface DimensionPicture { readonly definitionPoint: Point; /** The two extension lines, each from near its point to past the dimension line. */ readonly extensionLines: readonly (readonly [Point, Point])[]; - /** The dimension line, between the arrowheads or through the ticks. */ + /** The whole dimension line, between the arrowheads or through the ticks. */ readonly dimensionLine: readonly [Point, Point]; + /** + * The pieces of the dimension line it draws: the whole line, or one piece each side of a text + * centered in a break of it. + */ + readonly dimensionLines: readonly (readonly [Point, Point])[]; + /** The lines of the leader to a text moved outside the extension lines. Empty for none. */ + readonly leader: readonly (readonly [Point, Point])[]; /** The outline of each arrowhead, which is filled. None for an arrow size of 0. */ readonly arrowheads: readonly (readonly Point[])[]; /** @@ -381,8 +462,65 @@ export interface DimensionPicture { */ readonly arrowheadEntities: readonly ArrowheadEntity[]; readonly label: DimensionLabel; - /** The middle of the text's box, which a file holds beside the dimension. */ + /** The middle of the text's box. */ readonly textMiddle: Point; + /** + * The point a file holds beside the dimension for its text: the middle of the text's box, or + * the middle of the dimension line where words stand below it. + */ + readonly textPoint: Point; + /** How wide the text is drawn, the wider of the texts above and below the line. */ + readonly textWidth: number; + /** The words below the dimension line, and the middle of their box. */ + readonly below?: { readonly label: DimensionLabel; readonly middle: Point }; + /** + * The lineweight of the dimension line, its arrowheads and its leader, and of the extension + * lines, as group 370 holds it: -2 ByBlock, or hundredths of a millimetre. + */ + readonly lineweights: { readonly dimension: number; readonly extension: number }; +} + +/** A style's lineweight as group 370 holds it: ByBlock where it gives none. */ +function lineweightCode(weight: number | undefined): number { + if (weight === undefined) return -2; + return Math.round(weight * 100); +} + +/** The font of a dimension's text style, `Standard` where it has none, as its text is laid out. */ +export type DimensionFont = Pick; + +/** + * Each text a dimension's picture draws, as the paragraph its block holds: the text over the line, + * and the words below it. Each is laid out by `layoutDimensionText`, centered on its point. + */ +export function pictureTexts( + picture: Pick, + font: DimensionFont | undefined, +): ParagraphToMeasure[] { + const one = (label: DimensionLabel, at: Point, value: string): ParagraphToMeasure => ({ + value, + height: label.height, + font: font?.font ?? STANDARD_FONT, + widthFactor: written(font?.widthFactor ?? 1), + obliqueAngle: written(font?.obliqueAngle ?? 0), + at, + rotation: label.rotation, + align: "center", + valign: "middle", + }); + const below = picture.below; + return [ + one(picture.label, picture.textMiddle, mtextOfLabel(picture.label.value)), + ...(below === undefined + ? [] + : [ + one( + below.label, + below.middle, + below.label.value === "" ? "" : mtextOfLabel(below.label.value), + ), + ]), + ]; } const RADIANS = Math.PI / 180; @@ -469,7 +607,11 @@ function direction(degrees: number): Point { * * @param style - The dimension's style. */ -export function dimensionPicture(dimension: Dimension, style: DimensionStyle): DimensionPicture { +export function dimensionPicture( + dimension: Dimension, + style: DimensionStyle, + textStyle?: DimensionFont, +): DimensionPicture { const from: Point = [written(dimension.from[0]), written(dimension.from[1])]; const to: Point = [written(dimension.to[0]), written(dimension.to[1])]; const { angle, measurement } = dimensionMeasure(dimension); @@ -515,6 +657,54 @@ export function dimensionPicture(dimension: Dimension, style: DimensionStyle): D const info = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD); const stroke = info?.stroke; const tick = stroke !== undefined; + + const rotation = readable(angle); + const up: Point = [-Math.sin(rotation * RADIANS), Math.cos(rotation * RADIANS)]; + const quarter = direction(rotation); + const above: Point = rotation % 90 === 0 ? [-quarter[1], quarter[0]] : up; + const middle: Point = [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2]; + const [aboveText, belowText] = dimensionTexts(dimension, measurement, style); + // Each text is laid out as the paragraph the picture holds, centered on the middle of its box. + const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => + layoutDimensionText({ + value, + height: sizes.textHeight, + font, + widthFactor: written(textStyle?.widthFactor ?? 1), + obliqueAngle: written(textStyle?.obliqueAngle ?? 0), + align: "center", + valign: "middle", + }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => + layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + const topLayout = lay(mtextOfLabel(aboveText)); + const belowLayout = + belowText === undefined ? undefined : lay(belowText === "" ? "" : mtextOfLabel(belowText)); + const centered = style.textPlacement === "centered"; + const textWidth = Math.max(widest(topLayout), belowLayout ? widest(belowLayout) : 0); + // The arrowheads stay between the extension lines while they and the text fit there: a text in + // the line takes its room from theirs, and one above it needs only its own, beside arrows that + // need theirs and ticks that need none. + const fits = centered + ? span >= textWidth + 2 * size + : (tick || span > 2 * size + 2 * sizes.textGap) && textWidth <= span - 2 * sizes.textGap; + // With a leader, a text that has no room of its own between the extension lines moves out, and + // the ticks then turn outward only where the line is shorter than two gaps. + const leaderFit = style.textFit === "leader"; + const textOut = leaderFit && textWidth + 2 * sizes.textGap > span; + // Ticks that do not fit turn outward, and the dimension line breaks at each of them. Where a + // text may move out, one that stays turns them only in the line, where they and it need room. + const outward = + tick && + (textOut + ? // A line two gaps long, as its points are written, is taken as long as two gaps. + span + 1e-6 < 2 * sizes.textGap + : leaderFit + ? centered && (span < textWidth + 2 * size || span <= 2 * size + 2 * sizes.textGap) + : !fits); + const arrowheads: Point[][] = []; const arrowheadEntities: ArrowheadEntity[] = []; // The direction of the dimension line, from the first foot to the second. @@ -525,8 +715,9 @@ export function dimensionPicture(dimension: Dimension, style: DimensionStyle): D [second, -1], ] as const) { if (tick) { - // The block points along the line at the second end, and back along it at the first. - const turned = runAngle + (inward > 0 ? 180 : 0); + // The block points along the line at the second end, and back along it at the first, + // and the other way when the ticks turn outward. + const turned = runAngle + (inward > 0 !== outward ? 180 : 0); arrowheadEntities.push({ kind: "insert", block: info!.block!, @@ -559,28 +750,77 @@ export function dimensionPicture(dimension: Dimension, style: DimensionStyle): D const reach = tick ? size : -size; const dimensionLine: [Point, Point] = [move(first, run, -reach), move(second, run, reach)]; - const rotation = readable(angle); - const up: Point = [-Math.sin(rotation * RADIANS), Math.cos(rotation * RADIANS)]; - const quarter = direction(rotation); - const above: Point = rotation % 90 === 0 ? [-quarter[1], quarter[0]] : up; - const middle: Point = [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2]; - const textStyle = style.textStyle; + // A text centered in the line sits on it, unless words below take the other side: then each + // stands a gap off the line, as a text above it does. + let textMiddle = + centered && belowLayout === undefined + ? middle + : move(middle, above, sizes.textGap + boxHeight(topLayout) / 2); + let textPoint = belowLayout === undefined ? textMiddle : middle; + const belowMiddle = + belowLayout && move(middle, above, -(sizes.textGap + boxHeight(belowLayout) / 2)); + // The inner part of the line: between the ticks that turned outward, or the whole line. + const inner: readonly [Point, Point] = outward ? [first, second] : dimensionLine; + const dimensionLines: (readonly [Point, Point])[] = outward + ? [ + [first, dimensionLine[0]], + [second, dimensionLine[1]], + ] + : []; + const leader: (readonly [Point, Point])[] = []; + if (textOut) { + // The leader leaves the middle of the dimension line away from the points, leaning a tenth + // of three toward where the text reads, to an elbow past the extension lines' reach and a + // gap and a half, and the box of the text, more where the text reads from the other side. + const away = offsetTo(to, definitionPoint) >= 0 ? across : ([-across[0], -across[1]] as Point); + const half = boxHeight(topLayout) / 2; + const facing = above[0] * away[0] + above[1] * away[1] > 0; + const rise = sizes.extensionBeyond + 1.5 * sizes.textGap + (facing ? half : 3 * half); + const elbow = move(move(middle, away, rise), quarter, 0.3 * rise); + // Above the line the text stands over a landing as long as it and a gap each side; centered, + // it follows a landing two gaps long. + const landing = centered ? 2 * sizes.textGap : textWidth + 2 * sizes.textGap; + leader.push([middle, elbow], [elbow, move(elbow, quarter, landing)]); + const start = move(elbow, quarter, centered ? landing + sizes.textGap : sizes.textGap); + textPoint = centered ? start : move(start, above, sizes.textGap + half); + textMiddle = move(textPoint, quarter, textWidth / 2); + // The whole line between the ticks, which a line shorter than two gaps draws twice. + dimensionLines.push(inner, ...(outward ? [inner] : [])); + } else if (centered) { + // The line breaks a gap either side of the wider text. + const half = sizes.textGap + textWidth / 2; + dimensionLines.push([inner[0], move(middle, run, -half)], [inner[1], move(middle, run, half)]); + } else dimensionLines.push(inner); + const textStyleName = style.textStyle; + const label = (value: string, at: Point, layout: ParagraphLayout): DimensionLabel => ({ + value, + at: move(at, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + ...(textStyleName === undefined ? {} : { style: textStyleName }), + }); return { measurement, definitionPoint, extensionLines, dimensionLine, + dimensionLines, + leader, arrowheads, arrowheadEntities, - label: { - value: measurementText(measurement, style, dimension.text), - at: move(middle, above, sizes.textGap), - height: sizes.textHeight, - rotation, - direction: quarter, - ...(textStyle === undefined ? {} : { style: textStyle }), + label: label(aboveText, textMiddle, topLayout), + textMiddle, + textPoint, + textWidth, + ...(belowLayout && + belowMiddle && { + below: { label: label(belowText!, belowMiddle, belowLayout), middle: belowMiddle }, + }), + lineweights: { + dimension: lineweightCode(style.dimensionLineweight), + extension: lineweightCode(style.extensionLineweight), }, - textMiddle: move(middle, above, sizes.textGap + sizes.textHeight / 2), }; } @@ -613,11 +853,11 @@ const WIDEST_CHARACTER = 2; /** * The least a dimension with closed filled arrowheads must measure for the leading CAD app to draw * its arrowheads between the extension lines, whatever the widths of its font: more than twice the - * arrow size and twice the gap, and at least the widest its text can be and twice the gap. The - * widest is each character's width from `WIDEST_CHARACTERS` times the height and the width - * factor, and the lean of a slanted style once, the height times the tangent of its angle. - * Undefined for a style whose picture does not depend on that: one with ticks, or with an - * arrow size of 0. + * arrow size and twice the gap, and at least the widest its text can be and twice the gap. A text + * centered in the line breaks it, and needs the arrowheads' room as well as its own. The widest is + * each character's width from `WIDEST_CHARACTERS` times the height and the width factor, and the + * lean of a slanted style once, the height times the tangent of its angle. Undefined for a style + * whose picture does not depend on that: one with ticks, or with an arrow size of 0. * * @param text - The text of the dimension as that app draws it. * @param textStyle - The text style of the dimension's style, unless it is `Standard`. @@ -634,8 +874,36 @@ export function arrowRoom( for (const character of text) widths += WIDEST_CHARACTERS[character] ?? WIDEST_CHARACTER; const lean = sizes.textHeight * Math.abs(Math.tan((written(textStyle?.obliqueAngle ?? 0) * Math.PI) / 180)); - const widest = widths * sizes.textHeight * written(textStyle?.widthFactor ?? 1) + lean; - return Math.max(2 * sizes.arrowSize, widest) + 2 * sizes.textGap; + return roomBeside(style, widths * sizes.textHeight * written(textStyle?.widthFactor ?? 1) + lean); +} + +/** The least a dimension with closed filled arrowheads must measure beside a text this wide. */ +function roomBeside(style: DimensionStyle, width: number): number { + const sizes = dimensionSizes(style); + const arrows = 2 * sizes.arrowSize; + const room = style.textPlacement === "centered" ? width + arrows : Math.max(arrows, width); + return room + 2 * sizes.textGap; +} + +const STACK = /\{\\H[^;]*;\\S(\d+)([/#])(\d+);\}/g; + +/** + * A dimension's text as wide as it may draw, with the longer part for each fraction it stacks + * over a bar, and both parts and the slash for a diagonal one. + */ +function stackWidths(text: string): string { + return text.replace(STACK, (_, top: string, mark: string, bottom: string) => + mark === "#" ? `${top}/${bottom}` : top.length > bottom.length ? top : bottom, + ); +} + +/** A dimension's text with each fraction it stacks written inline, as a message shows it. */ +function inlineFractions(text: string): string { + return text.replace( + STACK, + (_, top: string, _mark: string, bottom: string, at: number) => + `${/\d/.test(text[at - 1] ?? "") ? " " : ""}${top}/${bottom}`, + ); } /** @@ -652,25 +920,54 @@ export function dimensionDrawnProblem( textStyle: TextStyle | undefined, ): string | undefined { const { measurement } = dimensionMeasure(dimension); - const drawn = measurementText(measurement, style, dimension.text); + // The arrowheads need room for the wider of the texts above and below the line. + const [above, below] = dimensionTexts(dimension, measurement, style); + let drawn = above; + let room = arrowRoom(style, stackWidths(above), textStyle); + if (below !== undefined) { + const needs = arrowRoom(style, stackWidths(below), textStyle); + if (needs !== undefined && needs > (room ?? 0)) [drawn, room] = [below, needs]; + } const problem = dimensionMeasureProblem( measurement, measurement * written(style.measurementScale ?? 1), roundedMeasurement(measurement, style), dimension.kind === "aligned-dimension", - drawn, - arrowRoom(style, drawn, textStyle), + inlineFractions(drawn), + room, ); if (problem) return problem; - const picture = dimensionPicture(dimension, style); + const picture = dimensionPicture(dimension, style, textStyle); + // The text as laid out may be wider still: a narrow font does not narrow a stack's gap. + const laid = room === undefined ? undefined : roomBeside(style, picture.textWidth); + if (laid !== undefined && measurement <= laid) { + return arrowRoomProblem(measurement, inlineFractions(drawn), laid); + } + const sizes = dimensionSizes(style); + if (picture.leader.length > 0 && dimension.textBelow !== undefined) return DIMENSION_LEADER_BELOW; + if (style.textFit === "leader" && sizes.arrowSize >= 2 * sizes.textHeight) { + return DIMENSION_LEADER_ARROWS; + } + if ( + picture.leader.length === 0 && + style.textPlacement === "centered" && + // The extension lines stand as far apart as what the dimension measures. + picture.textWidth + 2 * sizes.textGap > picture.measurement + ) { + return DIMENSION_CENTERED_WIDE; + } const numbers = [ ...picture.definitionPoint, ...picture.extensionLines.flat(2), ...picture.dimensionLine.flat(), + ...picture.dimensionLines.flat(2), + ...picture.leader.flat(2), ...picture.arrowheads.flat(2), ...picture.label.at, picture.label.height, ...picture.textMiddle, + ...picture.textPoint, + ...(picture.below ? [...picture.below.middle, ...picture.below.label.at] : []), ...picture.arrowheadEntities.flatMap((a) => a.kind === "solid" ? a.corners.flat() : [...a.at, a.scale], ), diff --git a/src/drawing.ts b/src/drawing.ts index 82be8aa..5288293 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -12,6 +12,9 @@ import { STANDARD_LEADER_STYLE, type Arrowhead, type DIMENSION_UNITS, + type DIMENSION_FRACTIONS, + type DIMENSION_TEXT_PLACEMENTS, + type DIMENSION_TEXT_FITS, type FEET_INCH_ZEROS, type LeaderArrowhead, type ZERO_SUPPRESSIONS, @@ -511,6 +514,11 @@ interface DimensionBase extends Placed { * style writes it, so `"<> TYP"` adds to it and `"VARIES"` replaces it. */ readonly text?: string; + /** + * Words drawn under the dimension line, opposite the measurement, such as `"WINDOW HEAD HT."`. + * `<>` in them stands for the measurement as it does in `text`. + */ + readonly textBelow?: string; } /** @@ -690,6 +698,30 @@ export interface DimensionStyle { readonly feetInchZeros?: (typeof FEET_INCH_ZEROS)[number]; /** What a length is multiplied by before it is written. Defaults to 1. */ readonly measurementScale?: number; + /** + * How a measurement in architectural units writes its fraction of an inch: `"inline"`, the + * default, as `4'-1 7/16"`; `"stacked"`, over a bar; or `"diagonal"`, beside a slash. + */ + readonly fraction?: (typeof DIMENSION_FRACTIONS)[number]; + /** The height of a stacked fraction as a share of the text's height, from 0.25 to 1. Defaults to 1. */ + readonly fractionScale?: number; + /** + * Where the text is: `"above"` the dimension line, the default, or `"centered"` in a break of + * it. + */ + readonly textPlacement?: (typeof DIMENSION_TEXT_PLACEMENTS)[number]; + /** + * Where the text goes when it does not fit between the extension lines: `"inside"` them all the + * same, the default, or outside on a `"leader"` from the middle of the dimension line. + */ + readonly textFit?: (typeof DIMENSION_TEXT_FITS)[number]; + /** + * In millimetres, one of `Lineweight`: how heavy the dimension line, its arrowheads and ticks + * and a leader to its text plot. Defaults to the dimension's own. + */ + readonly dimensionLineweight?: number; + /** The same for the extension lines. Defaults to the dimension's own. */ + readonly extensionLineweight?: number; } /** @@ -1456,6 +1488,24 @@ export interface DimensionStyleDefinition< readonly feetInchZeros?: FeetInchZerosIn; /** What a length is multiplied by before it is written, greater than 0. Defaults to 1. */ readonly measurementScale?: MeasurementScale; + /** + * In architectural units, how the fraction of an inch is written: `"inline"`, the default, as + * `4'-1 7/16"`, `"stacked"` over a bar, or `"diagonal"` beside a slash. + */ + readonly fraction?: U extends "architectural" ? (typeof DIMENSION_FRACTIONS)[number] : never; + /** A stacked fraction's height as a share of the text's, from 0.25 to 1. Defaults to 1. */ + readonly fractionScale?: U extends "architectural" ? number : never; + /** The text `"above"` the dimension line, the default, or `"centered"` in a break of it. */ + readonly textPlacement?: (typeof DIMENSION_TEXT_PLACEMENTS)[number]; + /** + * Where the text goes when it does not fit between the extension lines: `"inside"` them, the + * default, or outside on a `"leader"`. + */ + readonly textFit?: (typeof DIMENSION_TEXT_FITS)[number]; + /** The lineweight of the dimension line and its arrowheads, in millimetres, one of `Lineweight`. */ + readonly dimensionLineweight?: number; + /** The lineweight of the extension lines, in millimetres, one of `Lineweight`. */ + readonly extensionLineweight?: number; } /** What every dimension is drawn with. */ @@ -1471,6 +1521,11 @@ interface DimensionOptions< * `"<> TYP"`, or `"VARIES"`. */ readonly text?: DimensionText; + /** + * Words under the dimension line, opposite its text: `"WINDOW HEAD HT."`. `<>` in them stands + * for the measurement where `text` holds none. + */ + readonly textBelow?: DimensionText; /** A name for the dimension that no other entity of the drawing has. */ readonly id?: EntityId; readonly view?: ViewWithoutStandard; @@ -1519,6 +1574,8 @@ export interface StandardAlignedDimensionOptions< * `"<> TYP"`, or `"VARIES"`. */ readonly text?: DimensionText; + /** Words under the dimension line, opposite its text, as `textBelow` of a drawing's own style. */ + readonly textBelow?: DimensionText; /** A name for the dimension that no other entity of the drawing has. */ readonly id?: EntityId; } @@ -3134,6 +3191,8 @@ export class DrawingBuilder< } if (block !== undefined) this.#arrowheadBlocks.add(block); const { prefix, suffix, suppressZeros, feetInchZeros } = definition; + const { fraction, fractionScale, textPlacement, textFit } = definition; + const { dimensionLineweight, extensionLineweight } = definition; const units = definition.units ?? "decimal"; const scale = definition.scale ?? 1; const measurementScale = definition.measurementScale ?? 1; @@ -3154,6 +3213,12 @@ export class DrawingBuilder< ...(suppressZeros === undefined ? {} : { suppressZeros }), ...(feetInchZeros === undefined ? {} : { feetInchZeros }), ...(measurementScale === 1 ? {} : { measurementScale }), + ...(fraction === undefined || fraction === "inline" ? {} : { fraction }), + ...(fractionScale === undefined || fractionScale === 1 ? {} : { fractionScale }), + ...(textPlacement === undefined || textPlacement === "above" ? {} : { textPlacement }), + ...(textFit === undefined || textFit === "inside" ? {} : { textFit }), + ...(dimensionLineweight === undefined ? {} : { dimensionLineweight }), + ...(extensionLineweight === undefined ? {} : { extensionLineweight }), }); this.#dimensionStylesAudited.set(layerAuditKey(named), named); } @@ -3228,9 +3293,14 @@ export class DrawingBuilder< /** Checks what a dimension names and what it measures, and returns the dimension `make` gives. */ #dimension( options: - | { readonly style?: unknown; readonly text?: unknown; readonly view?: unknown } + | { + readonly style?: unknown; + readonly text?: unknown; + readonly textBelow?: unknown; + readonly view?: unknown; + } | undefined, - make: (style: string, text: { readonly text?: string }) => D, + make: (style: string, text: { readonly text?: string; readonly textBelow?: string }) => D, ): D { if (this.dxf === "R12") refuse("dimension", R12_ONLY.dimensions); if (this.#open) refuse("dimension", DIMENSION_IN_BLOCK); @@ -3253,11 +3323,16 @@ export class DrawingBuilder< } } const text: unknown = options?.text; - if (text !== undefined) { - const problem = dimensionTextProblem(text); + const below: unknown = options?.textBelow; + for (const words of [text, below]) { + if (words === undefined) continue; + const problem = dimensionTextProblem(words); if (problem) refuse("dimension", problem); } - const made = make(style!.name, text === undefined ? {} : { text: text as string }); + const made = make(style!.name, { + ...(text === undefined ? {} : { text: text as string }), + ...(below === undefined ? {} : { textBelow: below as string }), + }); const textStyle = style!.textStyle === undefined ? undefined : this.#textStyles.get(layerKey(style!.textStyle)); const problem = dimensionDrawnProblem(made, style!, textStyle); @@ -3326,6 +3401,8 @@ export class DrawingBuilder< if (existing !== undefined) return existing; const role = drawn.textRoles.get(idKey(fields.role))!; const { units: writes, precision, prefix, suffix, suppressZeros, feetInchZeros } = writing!; + const { fraction, fractionScale } = writing!; + const { dimensionLineweight, extensionLineweight } = fields; this.#defineDimensionStyle({ name, textStyle: this.#roleStyle(role), @@ -3343,6 +3420,12 @@ export class DrawingBuilder< ...(suppressZeros === undefined ? {} : { suppressZeros }), ...(feetInchZeros === undefined ? {} : { feetInchZeros }), measurementScale: writing!.measurementScale, + ...(fraction === "inline" ? {} : { fraction }), + ...(fractionScale === 1 ? {} : { fractionScale }), + ...(fields.textPlacement === "above" ? {} : { textPlacement: fields.textPlacement }), + ...(fields.textFit === "inside" ? {} : { textFit: fields.textFit }), + ...(dimensionLineweight === undefined ? {} : { dimensionLineweight }), + ...(extensionLineweight === undefined ? {} : { extensionLineweight }), }); return this.#dimensionStyles.get(layerKey(name))!; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 6549379..e1ef171 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -17,11 +17,14 @@ import { arrowheadEntityHandle, arrowheadsWithBlocks, dimensionAngle, + dimensionFileText, dimensionMeasure, dimensionPicture, FEET_INCH_ZEROS_CODES, validDimensionPictureHandles, validDimensionStyleHandle, + mtextOfLabel, + type DimensionLabel, type DimensionPicture, type DimensionPictureHandles, type Dimension, @@ -37,6 +40,7 @@ import type { Leader, LeaderStyle, Linetype, + Point, Text, TextStyle, Units, @@ -338,7 +342,7 @@ export function toDXFR2018( const layout = space === 0 ? undefined : sheets[space - 1]!.layout.name; pictures.set(`${space}/${index}`, { name: `*D${pictures.size + 1}`, - picture: dimensionPicture(entity, style), + picture: dimensionPicture(entity, style, styleOf(style.textStyle)), handles: validDimensionPictureHandles({ index, ...(entity.id === undefined ? {} : { id: entity.id }), @@ -448,6 +452,7 @@ export function toDXFR2018( return; } if (entity.kind === "linear-dimension" || entity.kind === "aligned-dimension") { + const picture = space === undefined ? undefined : pictures.get(`${space}/${index}`); writeDimension( g, entity, @@ -455,7 +460,8 @@ export function toDXFR2018( own, owner, paper, - space === undefined ? undefined : pictures.get(`${space}/${index}`)?.name, + picture?.name, + picture?.picture, ); return; } @@ -561,7 +567,17 @@ export function toDXFR2018( paper: false, contents: () => { // One stroke, as wide as the arrowhead's, which takes its color and its linetype - // from the dimension that draws it. + // from the dimension that draws it: a line where it has no width, which takes its + // lineweight from the dimension too. + if (stroke.width === 0) { + writeArrowheadStroke( + g, + { kind: "line", from: stroke.from, to: stroke.to }, + arrowheadEntityHandle(block), + handles.record, + ); + return; + } g(0, "LWPOLYLINE"); g(5, arrowheadEntityHandle(block)); g(330, handles.record); @@ -1078,7 +1094,7 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) if (block !== undefined) g(46, style.arrowSize); g(73, 0); // DIMTIH: the text is along the dimension line g(74, 0); // DIMTOH - g(77, 1); // DIMTAD: the text is above the dimension line + g(77, style.textPlacement === "centered" ? 0 : 1); // DIMTAD: above the line, or in it const architectural = style.units === "architectural"; g( 78, @@ -1090,17 +1106,27 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) ); // DIMZIN g(140, style.textHeight); // DIMTXT g(144, style.measurementScale ?? 1); // DIMLFAC + if (style.fractionScale !== undefined) g(146, style.fractionScale); // DIMTFAC g(147, style.textGap); // DIMGAP g(172, 1); // DIMTOFL: a dimension line between the extension lines, whatever fits - g(174, 1); // DIMTIX: the text between the extension lines, whatever fits + const leader = style.textFit === "leader"; + // DIMTIX: the text between the extension lines whatever fits, or moved out where it does not. + g(174, leader ? 0 : 1); g(271, style.precision); // DIMDEC - if (architectural) g(276, 2); // DIMFRAC: the fraction on the line, as 1 7/16 + // DIMFRAC: stacked across, stacked diagonally, or on the line, as 1 7/16. + if (architectural) g(276, FRACTION_CODES[style.fraction ?? "inline"]); g(277, architectural ? 4 : 2); // DIMLUNIT: architectural or decimal g(278, 46); // DIMDSEP: a point + if (leader) g(279, 1); // DIMTMOVE: a text moved out hangs on a leader g(340, textStyle); // DIMTXSTY if (block !== undefined) g(342, blockHandles(block).record); // DIMBLK + if (style.dimensionLineweight !== undefined) g(371, Math.round(style.dimensionLineweight * 100)); // DIMLWD + if (style.extensionLineweight !== undefined) g(372, Math.round(style.extensionLineweight * 100)); // DIMLWE } +/** `DIMFRAC` for each way a style writes a fraction of an inch. */ +const FRACTION_CODES = { stacked: 0, diagonal: 1, inline: 2 } as const; + /** * Writes a dimension. It names no block of its picture: the leading CAD app draws the picture when * it reads the file, from the dimension's points and its style. @@ -1113,10 +1139,11 @@ function writeDimension( owner: string, paper: boolean, block: string | undefined, + drawn: DimensionPicture | undefined, ): void { // `lint` refuses a dimension in a style the drawing does not have, which has no picture. const at = e.kind === "linear-dimension" ? e.line : e.to; - const picture = style ? dimensionPicture(e, style) : { definitionPoint: at, textMiddle: at }; + const picture = drawn ?? { definitionPoint: at, textPoint: at }; g(0, "DIMENSION"); g(5, handle); g(330, owner); @@ -1126,10 +1153,11 @@ function writeDimension( g(100, "AcDbDimension"); if (block !== undefined) g(2, block); point(g, 10, ...picture.definitionPoint); - point(g, 11, ...picture.textMiddle); + point(g, 11, ...picture.textPoint); // 32: the dimension has a picture of its own. 1: it is aligned. g(70, e.kind === "aligned-dimension" ? 33 : 32); - if (e.text !== undefined) g(1, dxfOnce(e.text)); + const text = dimensionFileText(e); + if (text !== undefined) g(1, dxfOnce(text)); g(71, 5); // the text is placed by its middle // What it reads, with 15 digits: the leading CAD app works it out only when it draws the picture // itself, and keeps the picture the file holds. @@ -1171,30 +1199,41 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi paper: false, anonymous: true, contents: () => { - const begin = (type: string, handle: string, subclass: string, lineweight: boolean) => { + const weights = picture.lineweights; + const begin = (type: string, handle: string, subclass: string, lineweight?: number) => { g(0, type); g(5, handle); g(330, owner); g(100, "AcDbEntity"); g(8, layer); g(62, 0); // by block - if (lineweight) g(370, -2); // by block + if (lineweight !== undefined) g(370, lineweight); g(100, subclass); }; - const lines: (readonly [readonly [number, number], readonly [number, number], string])[] = [ - [...picture.extensionLines[0]!, handles.extensionLines[0]], - [...picture.extensionLines[1]!, handles.extensionLines[1]], - [...picture.dimensionLine, handles.dimensionLine], + const lines: (readonly [ + readonly [number, number], + readonly [number, number], + string, + number, + ])[] = [ + [...picture.extensionLines[0]!, handles.extensionLines[0], weights.extension], + [...picture.extensionLines[1]!, handles.extensionLines[1], weights.extension], + ...picture.dimensionLines.map( + ([from, to], i) => [from, to, handles.dimensionLines[i]!, weights.dimension] as const, + ), + ...picture.leader.map( + ([from, to], i) => [from, to, handles.leader[i]!, weights.dimension] as const, + ), ]; - for (const [from, to, handle] of lines) { - begin("LINE", handle, "AcDbLine", true); + for (const [from, to, handle, lineweight] of lines) { + begin("LINE", handle, "AcDbLine", lineweight); point(g, 10, ...from); point(g, 11, ...to); } picture.arrowheadEntities.forEach((arrowhead, i) => { const handle = handles.arrowheads[i]!; if (arrowhead.kind === "solid") { - begin("SOLID", handle, "AcDbTrace", false); + begin("SOLID", handle, "AcDbTrace"); const [left, right, tip] = arrowhead.corners; for (const [code, corner] of [ [10, left], @@ -1206,31 +1245,36 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi } return; } - begin("INSERT", handle, "AcDbBlockReference", true); + begin("INSERT", handle, "AcDbBlockReference", weights.dimension); g(2, arrowhead.block); point(g, 10, ...arrowhead.at); for (const code of [41, 42, 43]) g(code, arrowhead.scale); if (written(arrowhead.rotation) !== 0) g(50, arrowhead.rotation); }); - const { label } = picture; - begin("MTEXT", handles.text, "AcDbMText", false); - point(g, 10, ...picture.textMiddle); - g(40, label.height); - g(41, 0); // no width to wrap at - g(46, 0); - g(71, 5); // placed by its middle - g(72, 1); // left to right - // The leading CAD app writes the text with a code that centers what is stacked in it. - writeMtextValue(g, `\\A1;${label.value}`); - g(7, textStyle); - if (written(label.rotation) !== 0) { - // 15 digits of the direction: 6 decimals would turn the text off the leading CAD app's own. - g(11, fifteenDigits(label.direction[0])); - g(21, fifteenDigits(label.direction[1])); - g(31, 0); + const text = (label: DimensionLabel, middle: Point, handle: string, value: string) => { + begin("MTEXT", handle, "AcDbMText"); + point(g, 10, ...middle); + g(40, label.height); + g(41, 0); // no width to wrap at + g(46, 0); + g(71, 5); // placed by its middle + g(72, 1); // left to right + writeMtextValue(g, value); + g(7, textStyle); + if (written(label.rotation) !== 0) { + // 15 digits of the direction: 6 decimals would turn the text off the leading CAD app's own. + g(11, fifteenDigits(label.direction[0])); + g(21, fifteenDigits(label.direction[1])); + g(31, 0); + } + g(73, 1); // line spacing at least as set + g(44, 1); + }; + text(picture.label, picture.textMiddle, handles.text, mtextOfLabel(picture.label.value)); + if (picture.below) { + const { label, middle } = picture.below; + text(label, middle, handles.belowText, label.value === "" ? "" : mtextOfLabel(label.value)); } - g(73, 1); // line spacing at least as set - g(44, 1); }, }); } diff --git a/src/extents.ts b/src/extents.ts index b4be151..79e59c6 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -9,7 +9,7 @@ import { type Matrix, type Referenced, } from "./blocks.ts"; -import { dimensionPicture, type Dimension } from "./dimensions.ts"; +import { dimensionPicture, pictureTexts, type Dimension } from "./dimensions.ts"; import type { AttributeDefinition, Block, @@ -27,7 +27,12 @@ import { layerKey, layerKeys } from "./layers.ts"; import { hasArcsOrWidths, mayCurve, polylineBox, PolylineMemo } from "./polylines.ts"; import { leaderPicture, leaderRepeats } from "./leaders.ts"; import { inStyle, measurer } from "./measure.ts"; -import { paragraphInStyle, paragraphMeasurer } from "./paragraphs.ts"; +import { + layoutDimensionText, + measured, + paragraphInStyle, + paragraphMeasurer, +} from "./paragraphs.ts"; import { filled } from "./shape.ts"; type Bounds = [number, number, number, number]; @@ -370,28 +375,26 @@ export function boxer( const style = from.dimensionStyles.get(key(e.style)); if (style === undefined) return; // Its style's prefix and suffix are read for each dimension that has the style. - const reads = (style.prefix?.length ?? 0) + (style.suffix?.length ?? 0) + (e.text?.length ?? 0); + const reads = + (style.prefix?.length ?? 0) + + (style.suffix?.length ?? 0) + + (e.text?.length ?? 0) + + (e.textBelow?.length ?? 0); // The label is put together for each dimension, so it is paid for by its whole length. const cost = Math.floor(reads / 32); if (cost > 0 && !spend(cost)) return; - const picture = dimensionPicture(e, style); - for (const line of [...picture.extensionLines, picture.dimensionLine]) { + const font = + style.textStyle === undefined ? undefined : from.textStyles.get(key(style.textStyle)); + const picture = dimensionPicture(e, style, font); + for (const line of [...picture.extensionLines, ...picture.dimensionLines, ...picture.leader]) { add(...line[0]); add(...line[1]); } for (const arrowhead of picture.arrowheads) for (const corner of arrowhead) add(...corner); - const { label } = picture; - const text: Text = { - kind: "text", - layer: e.layer, - at: label.at, - height: label.height, - value: label.value, - rotation: label.rotation, - align: "center", - ...(label.style === undefined ? {} : { style: label.style }), - }; - shape(text, from, add); + // Each text by the box of what it draws, as its block's paragraph lays it out. + for (const text of pictureTexts(picture, font)) { + for (const corner of measured(text, layoutDimensionText(text)).corners ?? []) add(...corner); + } }; /** * The box of what a leader draws, worked out once for each drawing: its shafts, its diff --git a/src/font-metrics.ts b/src/font-metrics.ts index b23bbe0..e4538cd 100644 --- a/src/font-metrics.ts +++ b/src/font-metrics.ts @@ -35,6 +35,12 @@ export interface FontMetrics { * paragraph's last line: the bottom of its ink, and never above the baseline. */ readonly bottoms: readonly number[]; + /** + * How far the top of a stack stands above the baseline of its top part where that part is the + * character alone: the height of its ink, top less bottom, below 1 for a figure lower than a + * capital. 0 for a space. + */ + readonly stackTops: readonly number[]; /** * How far past the end of a stacked fraction's ink the next character's first point lies, for * a stack of height 1. @@ -194,6 +200,20 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, ], + stackTops: [ + 0, 1, 0.33333333333, 1, 1, 1, 1, 0.33333333333, 1, 1, 0.66666666667, 0.66666666667, + 0.33333333333, 0, 0.16666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.5, 0.83333333333, 1, + 0.33333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 0.33333333333, 0, 0.33333333333, 0.66666666667, 1, 0.66666666667, 1, + 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1, 0.66666666667, 0.66666666667, 0.66666666667, + 1, 1, 0.66666666667, 0.66666666667, 1, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 1, 0.66666666667, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.5, 0.66666666667, + 1, 1, 1, 1, 0.33333333333, 0.83333333333, 1, 1, 1, 1, 1, 1, 1, 1, 0.5, 0.66666666667, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 0.91666666667, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, + 1.33333333333, + ], afterStack: 0.33333333333, }, "monotxt.shx": { @@ -317,6 +337,20 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, ], + stackTops: [ + 0, 1, 0.33333333333, 1, 1, 1, 1, 0.33333333333, 1, 1, 0.66666666667, 0.66666666667, + 0.33333333333, 0, 0.16666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.5, 0.83333333333, 1, + 0.33333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 0.33333333333, 0, 0.33333333333, 0.66666666667, 1, 0.66666666667, 1, + 0.66666666667, 1, 1, 1, 0.83333333333, 1.33333333333, 1, 1, 0.66666666667, 0.66666666667, + 0.66666666667, 1, 1, 0.66666666667, 0.66666666667, 1, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 1, 0.66666666667, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.5, + 0.66666666667, 1, 1, 1, 1, 0.33333333333, 0.83333333333, 1, 1, 1, 1, 1, 1, 1, 1, 0.5, + 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 0.91666666667, 1, 1, + 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, + 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, + ], afterStack: 0.33333333333, }, "simplex.shx": { @@ -474,6 +508,26 @@ export const FONT_METRICS: Readonly> = { 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, ], + stackTops: [ + 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, + 1.52380952381, 0.57142857143, 0.85714285714, 0.28571428571, 0, 0.09523809524, 1.52380952381, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.85714285714, 0.85714285714, 0.28571428571, + 0.85714285714, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.09523809524, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1.52380952381, 1.52380952381, 1.52380952381, 0.33333333333, 0, + 0.28571428571, 0.66666666667, 1, 0.66666666667, 1, 0.66666666667, 1, 1, 1, 1, 1.33333333333, + 1, 1, 0.66666666667, 0.66666666667, 0.66666666667, 1, 1, 0.66666666667, 0.66666666667, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 1, 0.66666666667, 1.52380952381, + 1.52380952381, 1.52380952381, 0, 0, 1, 0.95238095238, 1, 1, 1, 1, 1.38095238095, 1, 1, + 0.33333333333, 0.66666666667, 1, 1, 1, 1, 0.19047619048, 0.95238095238, 0.5, 1, 1, 1, 1, 1, 1, + 1, 0.33333333333, 0.66666666667, 1.38095238095, 1.38095238095, 1, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.33333333333, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, + 1, 1.33333333333, + ], afterStack: 0.28571428571, }, "romans.shx": { @@ -679,6 +733,26 @@ export const FONT_METRICS: Readonly> = { -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, -0.33333333333, ], + stackTops: [ + 0, 1, 0.28571428571, 1.52380952381, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, + 1.52380952381, 0.57142857143, 0.85714285714, 0.28571428571, 0, 0.09523809524, 1.52380952381, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.85714285714, 0.85714285714, 0.28571428571, + 0.85714285714, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.09523809524, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1.52380952381, 1.52380952381, 1.52380952381, 0.2380952381, 0, 0.28571428571, + 0.66666666667, 1, 0.66666666667, 1, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 1, 1, 0.66666666667, 0.66666666667, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 1, 0.66666666667, 1.52380952381, + 1.52380952381, 1.52380952381, 0, 0, 1, 0.95238095238, 1, 1, 1, 1, 1.38095238095, 1, 1, + 0.33333333333, 0.66666666667, 1, 1, 1, 1, 0.19047619048, 0.95238095238, 0.5, 1, 1, 1, 1, 1, 1, + 1, 0.33333333333, 0.66666666667, 1.38095238095, 1.38095238095, 1, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.33333333333, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, + 1.33333333333, + ], afterStack: 0.14285714286, }, "romand.shx": { @@ -883,6 +957,26 @@ export const FONT_METRICS: Readonly> = { -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, -0.33333333333, ], + stackTops: [ + 0, 1, 0.33333333333, 1.33333333333, 1.38095238095, 1, 1, 0.33333333333, 1.52380952381, + 1.52380952381, 0.57142857143, 0.80952380952, 0.33333333333, 0.04761904762, 0.14285714286, + 1.52380952381, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.85714285714, 0.85714285714, + 0.42857142857, 0.85714285714, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.09523809524, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.52380952381, 1.52380952381, 1.52380952381, + 0.28571428571, 0.04761904762, 0.33333333333, 0.66666666667, 1, 0.66666666667, 1, + 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1, 0.66666666667, 0.66666666667, 0.66666666667, + 1, 1, 0.66666666667, 0.66666666667, 1, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 1, 0.66666666667, 1.52380952381, 1.52380952381, 1.52380952381, 0, 0, 1, + 0.95238095238, 1, 1, 1, 1, 1.38095238095, 1, 1, 0.33333333333, 0.66666666667, 1, 1, 1, 1, + 0.28571428571, 0.95238095238, 1, 1, 1, 1, 1, 1, 1, 1, 0.33333333333, 0.66666666667, + 1.38095238095, 1.38095238095, 1, 1, 1.2380952381, 1.2380952381, 1.2380952381, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.33333333333, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.2380952381, 1.2380952381, 1.2380952381, 1.2380952381, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.14285714286, 1.19047619048, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.2380952381, 1, 1, 1, 1, 1, + 0.95238095238, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.95238095238, + 1, 0.71428571429, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, + ], afterStack: 0.14285714286, }, "romanc.shx": { @@ -1088,6 +1182,26 @@ export const FONT_METRICS: Readonly> = { -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, -0.33333333333, ], + stackTops: [ + 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, + 1.52380952381, 0.57142857143, 0.85714285714, 0.28571428571, 0, 0.09523809524, 1.52380952381, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.85714285714, 0.85714285714, 0.28571428571, + 0.85714285714, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.2380952381, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1.52380952381, 1.52380952381, 1.52380952381, 0.2380952381, 0, 0.28571428571, + 0.66666666667, 1, 0.66666666667, 1, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 1, 1, 0.66666666667, 0.66666666667, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 1, 0.66666666667, 1.52380952381, + 1.52380952381, 1.52380952381, 0, 0, 1, 0.95238095238, 1, 1, 1, 1, 1.38095238095, 1, 1, + 0.33333333333, 0.66666666667, 1, 1, 1, 1, 0.33333333333, 0.95238095238, 1, 1, 1, 1, 1, 1, 1, + 1, 0.33333333333, 0.66666666667, 1.38095238095, 1.38095238095, 1, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.33333333333, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.2380952381, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1, 1, 1, 1, 1, 0.95238095238, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0.95238095238, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, + 1.33333333333, + ], afterStack: 0.14285714286, }, "romant.shx": { @@ -1292,6 +1406,26 @@ export const FONT_METRICS: Readonly> = { -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, -0.27762619372, -0.33333333333, ], + stackTops: [ + 0, 1, 0.33333333333, 1.33333333333, 1.38095238095, 1, 1, 0.33333333333, 1.52380952381, + 1.52380952381, 0.57142857143, 0.80952380952, 0.33333333333, 0.04761904762, 0.14285714286, + 1.52380952381, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.85714285714, 0.85714285714, + 0.42857142857, 0.85714285714, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.2380952381, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.52380952381, 1.52380952381, 1.52380952381, + 0.2380952381, 0.04761904762, 0.33333333333, 0.66666666667, 1, 0.66666666667, 1, 0.66666666667, + 1, 1, 1, 1, 1.33333333333, 1, 1, 0.66666666667, 0.66666666667, 0.66666666667, 1, 1, + 0.66666666667, 0.66666666667, 1, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 1, 0.66666666667, 1.52380952381, 1.52380952381, 1.52380952381, 0, 0, 1, 0.95238095238, 1, 1, + 1, 1, 1.19047619048, 1, 1, 0.33333333333, 0.66666666667, 1, 1, 1, 1, 0.33333333333, + 0.95238095238, 1, 1, 1, 1, 1, 1, 1, 1, 0.33333333333, 0.66666666667, 1.38095238095, + 1.38095238095, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.33333333333, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, + 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.71428571429, + 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, + ], afterStack: 0.14285714286, }, "complex.shx": { @@ -1446,6 +1580,26 @@ export const FONT_METRICS: Readonly> = { 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, ], + stackTops: [ + 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, + 1.52380952381, 0.57142857143, 0.85714285714, 0.28571428571, 0, 0.09523809524, 1.52380952381, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.85714285714, 0.85714285714, 0.28571428571, + 0.85714285714, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.2380952381, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1.52380952381, 1.52380952381, 1.52380952381, 0.2380952381, 0, 0.28571428571, + 0.66666666667, 1, 0.66666666667, 1, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 1, 1, 0.66666666667, 0.66666666667, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 1, 0.66666666667, 1.52380952381, + 1.52380952381, 1.52380952381, 0, 0, 1, 0.95238095238, 1, 1, 1, 1, 1.38095238095, 1, 1, + 0.33333333333, 0.66666666667, 1, 1, 1, 1, 0.33333333333, 0.95238095238, 1, 1, 1, 1, 1, 1, 1, + 1, 0.33333333333, 0.66666666667, 1.38095238095, 1.38095238095, 1, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.33333333333, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, + 1, 1.33333333333, + ], afterStack: 0.28571428571, }, "italic.shx": { @@ -1602,6 +1756,26 @@ export const FONT_METRICS: Readonly> = { -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.28571428571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, ], + stackTops: [ + 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, + 1.52380952381, 0.57142857143, 0.85714285714, 0.28571428571, 0, 0.09523809524, 1.52380952381, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.85714285714, 0.85714285714, 0.28571428571, + 0.85714285714, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.2380952381, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1.52380952381, 1.52380952381, 1.52380952381, 0.2380952381, 0, 0.28571428571, + 0.66666666667, 1, 0.66666666667, 1, 0.66666666667, 1.33333333333, 1, 1, 1, 1.33333333333, 1, + 1, 0.66666666667, 0.66666666667, 0.66666666667, 1, 1, 0.66666666667, 0.66666666667, 1, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 1, 0.66666666667, 1.52380952381, + 1.52380952381, 1.47619047619, 0, 0, 1, 0.95238095238, 1, 1, 1, 1, 1.38095238095, 1, 1, + 0.33333333333, 0.66666666667, 1, 1, 1, 1, 0.33333333333, 0.95238095238, 1, 1, 1, 1, 1, 1, 1, + 1, 0.33333333333, 0.66666666667, 1.38095238095, 1.38095238095, 1, 1, 1.19047619048, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.28571428571, + 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, + 1.19047619048, 1.19047619048, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, + 0.95238095238, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, + 1, 1, 1, 1.33333333333, 1, 1.33333333333, + ], afterStack: 0.28571428571, }, "isocp.shx": { @@ -1718,6 +1892,25 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.25, 0, -0.25, ], + stackTops: [ + 0, 0.9, 0.2, 0.9, 0.9, 0.9, 0.96104624895, 0.2, 1.1, 1.1, 0.4, 0.4, 0.2, 0, 0.05, 0.9, + 0.90078740157, 0.9, 0.95019685039, 0.94142135624, 0.9, 0.94142135624, 0.94488188976, 0.9, 0.9, + 0.94905800958, 0.4, 0.6, 0.3, 0.3, 0.3, 0.93263779528, 1.27248737342, 0.9, 0.9, 0.99319805153, + 1.01390872965, 0.9, 0.9, 1.00355339059, 0.9, 0.9, 0.94142135624, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, + 0.9, 0.9, 0.97086614173, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 1.1, 0.9, 1.1, 0.15, 0, 0.15, + 0.63624368671, 0.93624368671, 0.67248737342, 0.93624368671, 0.63106601718, 0.94142135624, + 0.97248737342, 0.9, 0.9, 1.24142135624, 0.9, 0.92071067812, 0.63624368671, 0.63624368671, 0.6, + 0.93624368671, 0.93624368671, 0.6, 0.64572834646, 0.9, 0.63624368671, 0.6, 0.6, 0.6, 0.9, 0.6, + 1.13543307087, 1.9, 1.13543307087, 0, 0, 0.9, 0.9, 0.93106601718, 0.6, 0.9, 0.9, 0.9, 0.05, + 0.6, 0.78624368671, 0.5, 0.5, 0, 0.6, 0, 0.3, 0.6, 0.53631889764, 0.5, 0.15, 0.9, 0.9, 0, 0.2, + 0.5, 0.75, 0.5, 1.1, 1.1, 1.1, 0.93263779528, 1.3, 1.3, 1.3, 1.29960629921, 1.2, 1.3, 0.9, + 1.14659902577, 1.3, 1.3, 1.3, 1.2, 1.35, 1.35, 1.35, 1.25, 1.01390872965, 1.29960629921, 1.3, + 1.3, 1.3, 1.29960629921, 1.2, 0.9, 0.9, 1.3, 1.3, 1.3, 1.2, 1.3, 0.9, 0.96213203436, 1, 1, 1, + 0.99960629921, 0.9, 1, 0.66213203436, 0.83624368671, 1.03106601718, 1.03106601718, + 1.03106601718, 0.93106601718, 1, 1, 1, 0.9, 0.93377169664, 0.99960629921, 1, 1, 1, + 0.99960629921, 0.9, 0.5, 0.6, 1.03624368671, 1.03624368671, 1.03624368671, 0.93624368671, 1.3, + 0.9, 1.2, + ], afterStack: 0.14921259843, }, "isoct.shx": { @@ -1834,6 +2027,25 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.25, 0, -0.25, ], + stackTops: [ + 0, 0.9, 0.2, 0.9, 0.9, 0.9, 0.96104624895, 0.225, 1.1, 1.1, 0.4, 0.4, 0.2, 0, 0.05, 0.9, + 0.90078740157, 0.9, 0.95019685039, 0.94142135624, 0.9, 0.94142135624, 0.94488188976, 0.9, 0.9, + 0.94905800958, 0.4, 0.6, 0.3, 0.3, 0.3, 0.93263779528, 1.27248737342, 0.9, 0.9, 0.99319805153, + 1.01390872965, 0.9, 0.9, 1.00355339059, 0.9, 0.9, 0.94142135624, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, + 0.9, 0.9, 0.97086614173, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 1.1, 0.9, 1.1, 0.15, 0, 0.15, + 0.63624368671, 0.93624368671, 0.67248737342, 0.93624368671, 0.63106601718, 0.94142135624, + 0.97248737342, 0.9, 0.9, 1.24142135624, 0.9, 0.92071067812, 0.63624368671, 0.63624368671, 0.6, + 0.93624368671, 0.93624368671, 0.6, 0.64572834646, 0.9, 0.63624368671, 0.6, 0.6, 0.6, 0.9, 0.6, + 1.13543307087, 1.9, 1.13543307087, 0, 0, 0.9, 0.9, 0.93106601718, 0.6, 0.9, 0.9, 0.9, 0.05, + 0.6, 0.78624368671, 0.5, 0.5, 0, 0.6, 0, 0.3, 0.6, 0.53631889764, 0.5, 0.15, 0.9, 0.9, 0, 0.2, + 0.5, 0.75, 0.5, 1.1, 1.1, 1.1, 0.93263779528, 1.3, 1.3, 1.3, 1.29960629921, 1.2, 1.3, 0.9, + 1.14659902577, 1.3, 1.3, 1.3, 1.2, 1.3, 1.3, 1.3, 1.2, 1.01390872965, 1.29960629921, 1.3, 1.3, + 1.3, 1.29960629921, 1.2, 0.9, 0.9, 1.3, 1.3, 1.3, 1.2, 1.3, 0.9, 0.96213203436, 1, 1, 1, + 0.99960629921, 0.9, 1, 0.66213203436, 0.83624368671, 1.03106601718, 1.03106601718, + 1.03106601718, 0.93106601718, 1, 1, 1, 0.9, 0.93377169664, 0.99960629921, 1, 1, 1, + 0.99960629921, 0.9, 0.5, 0.6, 1.03624368671, 1.03624368671, 1.03624368671, 0.93624368671, 1.3, + 0.9, 1.2, + ], afterStack: 0.34921259843, }, Arial: { @@ -2001,6 +2213,36 @@ export const FONT_METRICS: Readonly> = { -0.01637107776, -0.01637107776, 0, -0.05388813097, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.29399727149, -0.27762619372, -0.29399727149, ], + stackTops: [ + 0, 1, 0.35402455662, 1.03410641201, 1.23601637108, 1.05388813097, 1.04024556617, + 0.35402455662, 1.31105047749, 1.31105047749, 0.42564802183, 0.66098226467, 0.33765347885, + 0.12346521146, 0.13983628922, 1.03410641201, 1.02114597544, 1.00409276944, 1.00409276944, + 1.02182810368, 1, 1.0034106412, 1.02114597544, 0.98703956344, 1.02114597544, 1.02114597544, + 0.724420191, 0.92223738063, 0.67735334243, 0.41814461119, 0.67735334243, 1.017053206, + 1.31241473397, 1, 1, 1.03410641201, 1, 1, 1, 1.03410641201, 1, 1, 1.017053206, 1, 1, 1, 1, + 1.03478854025, 1, 1.09549795362, 1, 1.03410641201, 1, 1.017053206, 1, 1, 1, 1, 1, + 1.27762619372, 1.03410641201, 1.27762619372, 0.54638472033, 0.27762619372, 0.19099590723, + 0.75716234652, 1.01637107776, 0.75716234652, 1.01637107776, 0.75716234652, 1.017053206, + 1.03478854025, 1, 1, 1.29399727149, 1, 1, 0.74079126876, 0.74079126876, 0.75716234652, + 1.01841746248, 1.01841746248, 0.74079126876, 0.75716234652, 0.98703956344, 0.74079126876, + 0.724420191, 0.724420191, 0.724420191, 1.01841746248, 0.724420191, 1.31105047749, + 1.31105047749, 1.31105047749, 0, 0, 1, 1.2789904502, 1.03615279673, 0.66916780355, 1, + 1.31105047749, 1.31105047749, 0.13983628922, 1.02933151432, 0.50818553888, 0.62210095498, + 0.41336971351, 0.12346521146, 1.02933151432, 0.08799454297, 0.37858117326, 0.83833560709, + 0.51227830832, 0.52455661664, 0.19099590723, 1.00204638472, 1.27762619372, 0.13983628922, + 0.30286493861, 0.51227830832, 0.51227830832, 0.62210095498, 1.05593451569, 1.05593451569, + 1.05593451569, 1.017053206, 1.25238744884, 1.25238744884, 1.25238744884, 1.21896316507, + 1.20122783083, 1.21418826739, 1, 1.30422919509, 1.25238744884, 1.25238744884, 1.25238744884, + 1.20122783083, 1.25238744884, 1.25238744884, 1.25238744884, 1.20122783083, 1, 1.21896316507, + 1.26944065484, 1.26944065484, 1.26944065484, 1.23601637108, 1.21828103684, 0.59481582538, + 1.07708049113, 1.26944065484, 1.26944065484, 1.26944065484, 1.21828103684, 1.25238744884, 1, + 1.03410641201, 1.02182810368, 1.02182810368, 1.02182810368, 1.00545702592, 1.02251023192, + 1.05115961801, 0.75716234652, 1.01432469304, 1.02182810368, 1.02182810368, 1.02182810368, + 1.02251023192, 1.00545702592, 1.00545702592, 1.00545702592, 1.00613915416, 1.017053206, + 0.98908594816, 1.02182810368, 1.02182810368, 1.02182810368, 1.00545702592, 1.02251023192, + 0.55115961801, 0.82264665757, 1.02182810368, 1.02182810368, 1.02182810368, 1.02251023192, + 1.29945429741, 1.27762619372, 1.30013642565, + ], afterStack: 0.06684856753, bold: { advances: [ @@ -2322,6 +2564,39 @@ export const FONT_METRICS: Readonly> = { -0.12769230769, -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.28, -0.28, -0.28, ], + stackTops: [ + 0, 1.06461538462, 0.40538461538, 1.00461538462, 1.36, 1.05307692308, 1.05538461538, + 0.40538461538, 1.35692307692, 1.35692307692, 0.57538461538, 0.72153846154, 0.39538461538, + 0.10538461538, 0.17923076923, 1.34692307692, 1.02461538462, 1.00230769231, 1.01, + 1.02461538462, 1.00461538462, 1.01, 1.02384615385, 1, 1.02461538462, 1.02461538462, + 0.71230769231, 0.92769230769, 0.74538461538, 0.40692307692, 0.74076923077, 1.06461538462, + 1.20692307692, 1.00461538462, 0.99538461538, 1.02, 0.99538461538, 0.99538461538, 1, + 1.02307692308, 1.00461538462, 1.00461538462, 1.01384615385, 1.00461538462, 1, 1, + 1.00230769231, 1.02461538462, 1, 1.15692307692, 1, 1.02461538462, 1, 1.01461538462, + 1.00461538462, 1.00461538462, 1.00461538462, 1.00461538462, 0.99538461538, 1.32230769231, + 1.34692307692, 1.32230769231, 0.56846153846, 0.28076923077, 0.23923076923, 0.76076923077, + 1.08615384615, 0.76, 1.08307692308, 0.76076923077, 1.08153846154, 1.02538461538, + 1.07615384615, 1.02538461538, 1.30153846154, 1.07615384615, 1.07615384615, 0.75076923077, + 0.75076923077, 0.76076923077, 1.02615384615, 1.02615384615, 0.75076923077, 0.76076923077, + 0.93384615385, 0.75, 0.74, 0.74, 0.74, 1.01538461538, 0.73153846154, 1.33076923077, + 1.38384615385, 1.33076923077, 0, 0, 1.06461538462, 1.02230769231, 1.00769230769, + 0.85230769231, 1.00461538462, 1.41923076923, 1.19076923077, 0.14461538462, 1.09153846154, + 0.74, 0.64384615385, 0.27384615385, 0.10538461538, 0.59846153846, 0.09923076923, + 0.35692307692, 0.91076923077, 0.60769230769, 0.61769230769, 0.23923076923, 1.01538461538, + 1.17538461538, 0.17923076923, 0.28076923077, 0.61, 0.74230769231, 0.64384615385, + 1.05307692308, 1.05307692308, 1.05307692308, 1.06461538462, 1.30384615385, 1.30384615385, + 1.30384615385, 1.26307692308, 1.25384615385, 1.33846153846, 1, 1.28846153846, 1.29923076923, + 1.29923076923, 1.29923076923, 1.24923076923, 1.30384615385, 1.30384615385, 1.30384615385, + 1.25384615385, 0.99538461538, 1.26307692308, 1.31384615385, 1.31384615385, 1.31384615385, + 1.27307692308, 1.26384615385, 0.63769230769, 1.34769230769, 1.31384615385, 1.31384615385, + 1.31384615385, 1.26384615385, 1.30384615385, 1.00846153846, 1.09153846154, 1.09307692308, + 1.09307692308, 1.09307692308, 1.05692307692, 1.02230769231, 1.11769230769, 0.76076923077, + 1.02615384615, 1.09307692308, 1.09307692308, 1.09307692308, 1.02230769231, 1.08307692308, + 1.08307692308, 1.08307692308, 1.01230769231, 1.08461538462, 1.04692307692, 1.09307692308, + 1.09307692308, 1.09307692308, 1.05692307692, 1.02230769231, 0.75461538462, 0.98461538462, + 1.09307692308, 1.09307692308, 1.09307692308, 1.02230769231, 1.35846153846, 1.35153846154, + 1.28769230769, + ], afterStack: 0.05461538462, bold: { advances: [ @@ -2644,6 +2919,37 @@ export const FONT_METRICS: Readonly> = { -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, -0.31828615149, -0.31369548585, -0.31828615149, ], + stackTops: [ + 0, 1.09487375669, 0.35883703137, 1, 1.32440703902, 1.10252486611, 1.06962509564, + 0.35883703137, 1.46059678653, 1.46059678653, 0.64881407804, 0.73833205815, 0.50803366488, + 0.12547819434, 0.25478194338, 1.24560061209, 1.02754399388, 1.00459066565, 1.01377199694, + 1.02754399388, 1, 1.01377199694, 1.01377199694, 1, 1.02754399388, 1.01377199694, + 0.79571537873, 1.04361132364, 0.8584544759, 0.37872991584, 0.8584544759, 1.09487375669, + 1.40856924254, 1, 1, 1.02448355011, 1, 1, 1, 1.02754399388, 1, 1, 1.01071155318, 1, 1, 1, 1, + 1.02754399388, 1, 1.28921193573, 1, 1.02754399388, 1, 1.01377199694, 1, 1, 1, 1, 1, + 1.42157612854, 1.24560061209, 1.42157612854, 0.48890589135, 0.31369548585, 0.18515684774, + 0.79571537873, 1.09028309105, 0.7895944912, 1.09487375669, 0.79571537873, 1.09028309105, + 1.10328997705, 1.08110175976, 1.09028309105, 1.4116296863, 1.08110175976, 1.08110175976, + 0.78194338179, 0.78194338179, 0.79571537873, 1.09563886764, 1.09563886764, 0.78194338179, + 0.79571537873, 1.02448355011, 0.78194338179, 0.76817138485, 0.76817138485, 0.76817138485, + 1.08645753634, 0.76817138485, 1.42157612854, 1.56694720734, 1.42157612854, 0, 0, + 1.09563886764, 1.3351185922, 1.01377199694, 0.91889824024, 1, 1.56694720734, 1.26855394032, + 0.17214996174, 1.02448355011, 0.73680183627, 0.61897475134, 0.34200459067, 0.12547819434, + 0.69854628921, 0.10175975516, 0.51338944147, 0.93267023718, 0.61132364193, 0.62356541699, + 0.18515684774, 1.0818668707, 1.25937260903, 0.25554705432, 0.22570772762, 0.6052027544, + 0.73680183627, 0.61897475134, 1.09028309105, 1.09028309105, 1.09181331293, 1.09563886764, + 1.26931905126, 1.26931905126, 1.26931905126, 1.27850038256, 1.26931905126, 1.33129303749, 1, + 1.23794950268, 1.26931905126, 1.26931905126, 1.26931905126, 1.26931905126, 1.26931905126, + 1.26931905126, 1.26931905126, 1.26931905126, 1, 1.27850038256, 1.2830910482, 1.2830910482, + 1.2830910482, 1.29227237949, 1.2830910482, 0.63657230298, 1.32899770467, 1.2830910482, + 1.2830910482, 1.2830910482, 1.2830910482, 1.26931905126, 1, 1.09946442234, 1.09487375669, + 1.09487375669, 1.09487375669, 1.09487375669, 1.08875286917, 1.16220351951, 0.79571537873, + 1.00459066565, 1.09487375669, 1.09487375669, 1.09487375669, 1.08875286917, 1.08110175976, + 1.08110175976, 1.08110175976, 1.07498087223, 1.09487375669, 1.08110175976, 1.09487375669, + 1.09487375669, 1.09487375669, 1.09487375669, 1.08875286917, 0.79877582249, 1.09716908952, + 1.09487375669, 1.09487375669, 1.09487375669, 1.08875286917, 1.39938791125, 1.3947972456, + 1.39326702372, + ], afterStack: 0.06732976282, bold: { advances: [ @@ -2961,6 +3267,37 @@ export const FONT_METRICS: Readonly> = { -0.02820512821, -0.02820512821, 0, -0.0735042735, -0.02820512821, -0.02820512821, -0.02820512821, -0.02820512821, -0.32991452991, -0.32991452991, -0.32991452991, ], + stackTops: [ + 0, 1.12393162393, 0.47435897436, 1.26153846154, 1.3264957265, 1.11025641026, 0.94957264957, + 0.51282051282, 1.29487179487, 1.29487179487, 0.62905982906, 0.88376068376, 0.51452991453, + 0.10256410256, 0.23162393162, 1.33162393162, 1.12393162393, 1.08717948718, 1.09829059829, + 1.12393162393, 1.07264957265, 1.09829059829, 1.12393162393, 1.07435897436, 1.12393162393, + 1.12393162393, 0.76581196581, 0.92307692308, 0.88547008547, 0.32991452991, 0.88547008547, + 1.05128205128, 1.21965811966, 1, 1, 1.05128205128, 1, 1, 1, 1.05128205128, 1, 1, + 1.02820512821, 1, 1, 1, 1, 1.05128205128, 1, 1.22735042735, 1, 1.05128205128, 1, + 1.02820512821, 1, 1, 1, 1, 1, 1.29401709402, 1.33162393162, 1.29401709402, 0.4641025641, + 0.47948717949, 0.26324786325, 0.79401709402, 1.10085470085, 0.79401709402, 1.10085470085, + 0.79401709402, 1.07264957265, 1.09572649573, 1.07264957265, 1.10854700855, 1.43846153846, + 1.07264957265, 1.07264957265, 0.76581196581, 0.76581196581, 0.79401709402, 1.09572649573, + 1.09572649573, 0.75811965812, 0.79401709402, 1.02820512821, 0.76837606838, 0.74017094017, + 0.74102564103, 0.74017094017, 1.07008547009, 0.74017094017, 1.29401709402, 1.29401709402, + 1.29487179487, 0, 0, 1.08290598291, 1.14188034188, 1.02735042735, 0.69743589744, 1, + 1.29401709402, 1.18376068376, 0.13931623932, 1.0452991453, 0.49914529915, 0.74102564103, + 0.47863247863, 0.10256410256, 1.0452991453, 0.07264957265, 0.47435897436, 1.0547008547, + 0.57179487179, 0.58461538462, 0.26324786325, 1.07008547009, 1.18376068376, 0.17521367521, + 0.31025641026, 0.56923076923, 0.49914529915, 0.74102564103, 1.09572649573, 1.09572649573, + 1.09829059829, 1.09316239316, 1.3641025641, 1.3641025641, 1.35042735043, 1.26068376068, + 1.27863247863, 1.37008547009, 1, 1.30769230769, 1.3641025641, 1.3641025641, 1.34786324786, + 1.27863247863, 1.3641025641, 1.3641025641, 1.34786324786, 1.27863247863, 1, 1.26068376068, + 1.39230769231, 1.39230769231, 1.37606837607, 1.28888888889, 1.30683760684, 0.5905982906, + 1.14188034188, 1.39230769231, 1.39230769231, 1.37606837607, 1.30683760684, 1.35641025641, 1, + 1.10085470085, 1.16324786325, 1.16324786325, 1.14786324786, 1.05982905983, 1.07777777778, + 1.19401709402, 0.79401709402, 1.05042735043, 1.1641025641, 1.1641025641, 1.14786324786, + 1.07777777778, 1.12820512821, 1.13504273504, 1.11965811966, 1.04957264957, 1.09487179487, + 1.03162393162, 1.1641025641, 1.1641025641, 1.14786324786, 1.05982905983, 1.07777777778, + 0.81025641026, 0.88290598291, 1.1641025641, 1.1641025641, 1.14786324786, 1.07777777778, + 1.46581196581, 1.40256410256, 1.38034188034, + ], afterStack: 0.19572649573, bold: { advances: [ @@ -3282,6 +3619,40 @@ export const FONT_METRICS: Readonly> = { -0.02084781098, -0.02084781098, 0, -0.05628908965, -0.01737317582, -0.01737317582, -0.01737317582, -0.01737317582, -0.3085476025, -0.3085476025, -0.3085476025, ], + stackTops: [ + 0, 1.02571230021, 0.39054899236, 0.85476025017, 1.26685198054, 1.0319666435, 1.0340514246, + 0.39054899236, 1.29256428075, 1.29256428075, 0.49339819319, 0.71369006254, 0.42112578179, + 0.10979847116, 0.18902015288, 1.35302293259, 0.79013203614, 0.76789437109, 0.76789437109, + 1.02154273801, 1.01737317582, 0.99930507297, 1.0319666435, 0.99930507297, 1.03544127867, + 1.02501737318, 0.70187630299, 0.9339819319, 0.74704656011, 0.34537873523, 0.74704656011, + 1.02362751911, 1.16956219597, 1, 0.98610145935, 1.03127171647, 0.98610145935, 0.98610145935, + 0.98610145935, 1.03127171647, 0.98610145935, 0.98610145935, 1.00972897846, 0.98610145935, + 0.98610145935, 0.98610145935, 0.9958304378, 1.03335649757, 0.98610145935, 1.27727588603, + 0.98610145935, 1.02849200834, 0.98610145935, 1.00972897846, 0.99861014593, 0.99861014593, + 0.98610145935, 0.98610145935, 0.98610145935, 1.27102154274, 1.35302293259, 1.27102154274, + 0.45865184156, 0.19596942321, 0.29742876998, 0.72202918694, 1.11257817929, 0.72272411397, + 1.09520500347, 0.72272411397, 1.07574704656, 1.01320361362, 1.07574704656, 1.05281445448, + 1.36205698402, 1.07574704656, 1.07574704656, 0.70396108409, 0.70396108409, 0.7255038221, + 1.01250868659, 1.03127171647, 0.70187630299, 0.723419041, 0.91035441279, 0.71091035441, + 0.6914523975, 0.69006254343, 0.6851980542, 0.99374565671, 0.6851980542, 1.29951355108, + 1.35302293259, 1.29951355108, 0, 0, 1.02710215427, 1.09381514941, 1.01181375956, 0.5830437804, + 0.98610145935, 1.35302293259, 1.18902015288, 0.17095205003, 1.22724113968, 0.58373870744, + 0.56775538568, 0.40027797081, 0.10979847116, 1.22724113968, 0.0701876303, 0.45170257123, + 0.76650451703, 0.66921473245, 0.6935371786, 0.29742876998, 0.99374565671, 1.1362056984, + 0.18902015288, 0.32036136206, 0.66365531619, 0.58860319666, 0.56775538568, 1.01806810285, + 1.0041695622, 1.02362751911, 1.02293259208, 1.29812369701, 1.29812369701, 1.29812369701, + 1.28422515636, 1.27936066713, 1.29812369701, 0.98610145935, 1.31619179986, 1.29812369701, + 1.29812369701, 1.29812369701, 1.28769979152, 1.29812369701, 1.29812369701, 1.29812369701, + 1.28769979152, 0.98610145935, 1.30090340514, 1.32175121612, 1.32175121612, 1.32175121612, + 1.3148019458, 1.31132731063, 0.62682418346, 1.08339124392, 1.32175121612, 1.32175121612, + 1.32175121612, 1.31132731063, 1.29812369701, 0.98610145935, 1.08478109798, 1.08617095205, + 1.08617095205, 1.09312022238, 1.05281445448, 1.05072967338, 1.10076441974, 0.72272411397, + 1.01320361362, 1.08686587908, 1.08686587908, 1.08964558721, 1.05142460042, 1.06879777623, + 1.06879777623, 1.07157748436, 1.03335649757, 1.1021542738, 1.03544127867, 1.08964558721, + 1.08964558721, 1.09242529534, 1.05628908965, 1.05420430855, 0.74148714385, 0.7915218902, + 1.08617095205, 1.08617095205, 1.08895066018, 1.05072967338, 1.37734537874, 1.38429464906, + 1.34190410007, + ], afterStack: 0.07157748436, bold: { advances: [ @@ -3596,6 +3967,36 @@ export const FONT_METRICS: Readonly> = { -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, -0.33612273361, -0.32845188285, -0.33612273361, ], + stackTops: [ + 0, 1.01255230126, 0.31171548117, 0.91422594142, 1.27266387727, 1.03068340307, 1.03277545328, + 0.31171548117, 1.22733612273, 1.22733612273, 0.49163179916, 0.65550906555, 0.34309623431, + 0.089958159, 0.15690376569, 1.1659693166, 1.03417015342, 1.02231520223, 1.01673640167, + 1.03417015342, 1, 1.01743375174, 1.03417015342, 1, 1.03277545328, 1.03417015342, + 0.74476987448, 0.91352859135, 0.67852161785, 0.38912133891, 0.67852161785, 1.02928870293, + 1.1450488145, 1, 1, 1.03347280335, 1, 1, 1, 1.03347280335, 1, 1, 1.01673640167, 1, 1, 1, 1, + 1.03347280335, 1, 1.15132496513, 1, 1.03347280335, 1, 1.01673640167, 1, 1, 1, 1, 1, + 1.22733612273, 1.18828451883, 1.22733612273, 0.58158995816, 0.20711297071, 0.22873082287, + 0.74755927476, 1.07391910739, 0.74755927476, 1.07391910739, 0.74755927476, 1.07252440725, + 1.06694560669, 1.05718270572, 1.04393305439, 1.38005578801, 1.05718270572, 1.05718270572, + 0.73082287308, 0.73082287308, 0.74755927476, 1.05927475593, 1.05927475593, 0.72663877266, + 0.74755927476, 0.94072524407, 0.73082287308, 0.71408647141, 0.71408647141, 0.71408647141, + 1.05020920502, 0.71408647141, 1.22733612273, 1.42817294282, 1.22733612273, 0, 0, + 1.01255230126, 1.01952580195, 1.01673640167, 0.65271966527, 1, 1.42817294282, 1.08577405858, + 0.13737796374, 1.0460251046, 0.52859135286, 0.47419804742, 0.39260808926, 0.089958159, + 0.83612273361, 0.08368200837, 0.38563458856, 0.82845188285, 0.60669456067, 0.62133891213, + 0.22873082287, 0.99023709902, 1, 0.15690376569, 0.30125523013, 0.60808926081, 0.52859135286, + 0.47419804742, 1.01534170153, 1.01534170153, 1.01394700139, 1.02928870293, 1.32078103208, + 1.32078103208, 1.32287308229, 1.25732217573, 1.22873082287, 1.21408647141, 1, 1.3179916318, + 1.32078103208, 1.32008368201, 1.32426778243, 1.22942817294, 1.32078103208, 1.32078103208, + 1.32426778243, 1.22942817294, 1, 1.25732217573, 1.33751743375, 1.33751743375, 1.34030683403, + 1.27336122734, 1.24407252441, 0.60390516039, 1.07531380753, 1.33751743375, 1.33682008368, + 1.3410041841, 1.24686192469, 1.32078103208, 1, 1.08926080893, 1.09483960948, 1.09483960948, + 1.09762900976, 1.03347280335, 1.00348675035, 1.10739191074, 0.74755927476, 1.03207810321, + 1.09483960948, 1.09483960948, 1.09762900976, 1.00348675035, 1.07810320781, 1.07810320781, + 1.08089260809, 0.98675034868, 1.07810320781, 1.01673640167, 1.09483960948, 1.09483960948, + 1.09762900976, 1.03347280335, 1.00348675035, 0.67642956764, 0.84239888424, 1.09483960948, + 1.09483960948, 1.09762900976, 1.00348675035, 1.41422594142, 1.38563458856, 1.32287308229, + ], afterStack: 0.05857740586, bold: { advances: [ @@ -3912,6 +4313,36 @@ export const FONT_METRICS: Readonly> = { -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.27669576897, -0.27669576897, -0.27669576897, ], + stackTops: [ + 0, 1, 0.38885157824, 1, 1.30087306917, 1.03828072532, 1.04163868368, 0.38885157824, + 1.32169241101, 1.32169241101, 0.62189388852, 0.78576225655, 0.43989254533, 0.12155809268, + 0.19140362659, 1.26259234385, 1.04096709201, 1.00335795836, 1.02081934184, 1.04163868368, 1, + 1.02081934184, 1.03962390866, 1, 1.04566823371, 1.03962390866, 0.75016789792, 0.99865681666, + 0.76964405641, 0.38952316991, 0.76964405641, 1.02014775017, 1.17125587643, 1, 1, 1.0362659503, + 1, 1, 1, 1.03760913365, 1, 1, 1.01410342512, 1, 1, 1, 1, 1.04163868368, 1, 1.28408327737, 1, + 1.0362659503, 1, 1.02081934184, 1, 1, 1, 1, 1, 1.30826057757, 1.26259234385, 1.30826057757, + 0.54197447952, 0.20147750168, 0.25117528543, 0.78912021491, 1.06581598388, 0.7844190732, + 1.06581598388, 0.78844862324, 1.05171255876, 1.05507051713, 1.04499664204, 1.00671591672, + 1.29079919409, 1.04499664204, 1.04499664204, 0.77098723976, 0.77098723976, 0.7918065816, + 1.04768300873, 1.04768300873, 0.75016789792, 0.78643384822, 0.9805238415, 0.77098723976, + 0.75016789792, 0.75016789792, 0.75016789792, 1.02686366689, 0.75016789792, 1.30826057757, + 1.30826057757, 1.30826057757, 0, 0, 1, 1.23304231028, 1.0194761585, 0.66689053056, 1, + 1.30826057757, 1.27871054399, 0.13096037609, 1.16118200134, 0.65681665547, 0.65815983882, + 0.47347212895, 0.12155809268, 1.16118200134, 0.08730691739, 0.51040967092, 0.83478844862, + 0.64002686367, 0.6561450638, 0.25117528543, 1.02686366689, 1.24378777703, 0.19140362659, + 0.29751511081, 0.62256548019, 0.65815983882, 0.65815983882, 1.00268636669, 1.00268636669, + 1.01880456682, 1.02014775017, 1.37609133647, 1.37609133647, 1.36265950302, 1.319677636, + 1.24378777703, 1.33378106111, 1, 1.30221625252, 1.37609133647, 1.37609133647, 1.37609133647, + 1.25721961048, 1.37609133647, 1.37609133647, 1.37609133647, 1.25721961048, 1, 1.33310946944, + 1.39691067831, 1.39691067831, 1.39691067831, 1.35392881128, 1.27803895232, 0.72128945601, + 1.13969106783, 1.39691067831, 1.39691067831, 1.39691067831, 1.27803895232, 1.37609133647, 1, + 1.0678307589, 1.14640698455, 1.14640698455, 1.14640698455, 1.11685695097, 1.02753525856, + 1.17730020148, 0.79046339825, 1.05171255876, 1.14304902619, 1.14304902619, 1.14304902619, + 1.0241773002, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, 1.0725319006, + 1.09603760913, 1.14640698455, 1.14640698455, 1.14640698455, 1.11685695097, 1.02753525856, + 0.85292142377, 0.93149764943, 1.14640698455, 1.14640698455, 1.14640698455, 1.02753525856, + 1.40228341169, 1.32169241101, 1.2834116857, + ], afterStack: 0.0557421088, bold: { advances: [ @@ -4223,6 +4654,39 @@ export const FONT_METRICS: Readonly> = { -0.02018745494, 0, -0.04830569575, -0.02018745494, -0.02018745494, -0.02018745494, -0.02018745494, -0.31867339582, -0.31506849315, -0.31867339582, ], + stackTops: [ + 0, 1.02018745494, 0.42105263158, 1.02018745494, 1.17231434751, 1.04037490988, 1.02235039654, + 0.42105263158, 1.34102379236, 1.34102379236, 0.59841384283, 0.77721701514, 0.39005046864, + 0.10886806056, 0.16005767844, 1.04542177361, 1.0151405912, 0.9978370584, 0.9978370584, + 1.0151405912, 0.9978370584, 0.99495313627, 1.0151405912, 0.9978370584, 1.0151405912, + 1.01802451334, 0.70079307859, 0.92718096611, 0.71016582552, 0.29416005768, 0.71016582552, + 1.01946647441, 1.34390771449, 1, 0.97764960346, 1.02235039654, 0.97764960346, 0.97764960346, + 0.97764960346, 1.02235039654, 0.97764960346, 0.97764960346, 1, 0.97764960346, 0.97764960346, + 0.97764960346, 0.9935111752, 1.02235039654, 0.97764960346, 1.28911319394, 0.97764960346, + 1.02235039654, 0.97764960346, 1.00072098053, 1, 1, 0.97764960346, 0.97764960346, + 0.97764960346, 1.29271809661, 1.04542177361, 1.29343907714, 0.51694304254, 0.31867339582, + 0.24873828407, 0.69358327325, 1.04542177361, 0.70007209805, 1.04542177361, 0.70079307859, + 1.02379235761, 0.99855803893, 1.02523431867, 1.02523431867, 1.34462869503, 1.02523431867, + 1.02523431867, 0.67988464311, 0.67988464311, 0.70007209805, 0.9956741168, 0.9956741168, + 0.67988464311, 0.70007209805, 0.8882480173, 0.68060562365, 0.68060562365, 0.68060562365, + 0.66041816871, 0.97909156453, 0.66041816871, 1.34390771449, 1.34390771449, 1.34390771449, 0, + 0, 1.02090843547, 1.22927180966, 1.0151405912, 0.69430425379, 0.97764960346, 1.34390771449, + 1.28622927181, 0.15645277577, 1.02235039654, 0.43330930065, 0.67916366258, 0.29271809661, + 0.10886806056, 1.02235039654, 0.06056236482, 0.44340302812, 0.77721701514, 0.51910598414, + 0.52992069214, 0.24873828407, 0.97909156453, 1.29632299928, 0.15140591204, 0.29271809661, + 0.51910598414, 0.43042537851, 0.67916366258, 1.03677000721, 1.03677000721, 1.03677000721, + 1.02162941601, 1.29560201875, 1.29560201875, 1.29271809661, 1.2429704398, 1.23143475126, + 1.22638788753, 0.97764960346, 1.28118240807, 1.29560201875, 1.29560201875, 1.29271809661, + 1.23143475126, 1.29560201875, 1.29560201875, 1.29271809661, 1.23143475126, 0.97764960346, + 1.25883201154, 1.31795241528, 1.31795241528, 1.31506849315, 1.26532083634, 1.2537851478, + 0.59192501802, 1.04325883201, 1.31867339582, 1.31867339582, 1.31578947368, 1.25450612833, + 1.29560201875, 0.97764960346, 1.03460706561, 1.01586157174, 1.01586157174, 1.01225666907, + 0.9913482336, 0.97764960346, 1.04181687094, 0.70079307859, 0.96106705119, 1.02235039654, + 1.02235039654, 1.01874549387, 0.98341744773, 1.0021629416, 1.0021629416, 0.99855803893, + 0.96322999279, 1.04542177361, 0.97764960346, 1.02235039654, 1.02235039654, 1.01874549387, + 0.9978370584, 0.98341744773, 0.57390050469, 0.75414563807, 1.02235039654, 1.02235039654, + 1.01874549387, 0.98341744773, 1.32083633742, 1.34030281182, 1.28262436914, + ], afterStack: 0.05263157895, bold: { advances: [ @@ -4540,6 +5004,39 @@ export const FONT_METRICS: Readonly> = { -0.01346801347, -0.01346801347, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.28282828283, -0.28282828283, -0.28282828283, ], + stackTops: [ + 0, 1.01750841751, 0.25656565657, 1.01481481481, 1.27138047138, 1.01750841751, 1.01750841751, + 0.25656565657, 1.28148148148, 1.28148148148, 0.41548821549, 0.55824915825, 0.43097643098, + 0.11784511785, 0.20269360269, 0.99057239057, 1.01750841751, 0.99057239057, 1.00404040404, + 1.01750841751, 0.99057239057, 1.00404040404, 1.02087542088, 0.99057239057, 1.01750841751, + 1.02087542088, 0.74814814815, 0.97912457912, 0.56228956229, 0.32390572391, 0.56228956229, + 1.01750841751, 0.98249158249, 1, 0.99528619529, 1.0202020202, 0.99326599327, 0.98653198653, + 0.98653198653, 1.0202020202, 0.98653198653, 0.98653198653, 1, 0.98653198653, 0.98653198653, 1, + 1, 1.02087542088, 0.99326599327, 1.20808080808, 0.99663299663, 1.0202020202, 0.98653198653, + 1.00336700337, 1, 1, 0.98720538721, 0.98653198653, 0.98653198653, 1.29966329966, + 0.99057239057, 1.29966329966, 0.38249158249, 0.17104377104, 0.22424242424, 0.74814814815, + 1.0303030303, 0.74814814815, 1.02962962963, 0.74814814815, 1.01683501684, 1.05050505051, + 1.01683501684, 0.99393939394, 1.27676767677, 1.01683501684, 1.0303030303, 0.73468013468, + 0.73468013468, 0.74814814815, 1.01750841751, 1.01750841751, 0.73468013468, 0.74814814815, + 0.93468013468, 0.73468013468, 0.7367003367, 0.7367003367, 0.72121212121, 1.00404040404, + 0.72121212121, 1.29427609428, 1.13198653199, 1.29427609428, 0, 0, 1.01750841751, + 0.92188552189, 1.00404040404, 0.64579124579, 0.98653198653, 1.14006734007, 1.01885521886, + 0.15151515152, 0.90841750842, 0.44915824916, 0.367003367, 0.32727272727, 0.11784511785, + 0.90841750842, 0.08686868687, 0.28215488215, 0.71986531987, 0.60269360269, 0.60942760943, + 0.22424242424, 1.00404040404, 1.17104377104, 0.20269360269, 0.3063973064, 0.59461279461, + 0.44915824916, 0.367003367, 1.02760942761, 1.02760942761, 1.02760942761, 1.01750841751, + 1.29158249158, 1.29158249158, 1.29494949495, 1.20673400673, 1.22087542088, 1.22154882155, + 0.98653198653, 1.30976430976, 1.29158249158, 1.29158249158, 1.29494949495, 1.22087542088, + 1.29158249158, 1.29158249158, 1.29494949495, 1.22087542088, 0.99326599327, 1.2202020202, + 1.30841750842, 1.30841750842, 1.31178451178, 1.22356902357, 1.23771043771, 0.56363636364, + 1.02087542088, 1.30841750842, 1.30841750842, 1.31178451178, 1.23771043771, 1.29158249158, + 0.98653198653, 1.0303030303, 1.10303030303, 1.10303030303, 1.1063973064, 1.01818181818, + 1.03232323232, 1.16094276094, 0.74814814815, 1.04107744108, 1.10303030303, 1.10303030303, + 1.1063973064, 1.03232323232, 1.08956228956, 1.08956228956, 1.09292929293, 1.01885521886, + 1.0303030303, 1.00471380471, 1.10303030303, 1.10303030303, 1.1063973064, 1.01818181818, + 1.03232323232, 0.70774410774, 0.74814814815, 1.10303030303, 1.10303030303, 1.1063973064, + 1.03232323232, 1.37239057239, 1.29966329966, 1.30168350168, + ], afterStack: 0.04107744108, bold: { advances: [ @@ -4857,6 +5354,36 @@ export const FONT_METRICS: Readonly> = { -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.27669576897, -0.27669576897, -0.27669576897, ], + stackTops: [ + 0, 1, 0.38885157824, 1, 1.30087306917, 1.03828072532, 1.04163868368, 0.38885157824, + 1.32169241101, 1.32169241101, 0.62189388852, 0.83948959033, 0.43989254533, 0.12155809268, + 0.19140362659, 1.24916051041, 1.04096709201, 1.00335795836, 1.02081934184, 1.04163868368, 1, + 1.02081934184, 1.03962390866, 1, 1.04566823371, 1.03962390866, 0.75016789792, 0.99865681666, + 0.7723304231, 0.38952316991, 0.7723304231, 1.02014775017, 1.1719274681, 1, 1, 1.0362659503, 1, + 1, 1, 1.03760913365, 1, 1, 1.01410342512, 1, 1, 1, 1, 1.04163868368, 1, 1.28475486904, 1, + 1.0362659503, 1, 1.02081934184, 1, 1, 1, 1, 1, 1.30826057757, 1.24916051041, 1.30826057757, + 0.54197447952, 0.20147750168, 0.25117528543, 0.78912021491, 1.06581598388, 0.7844190732, + 1.06581598388, 0.78844862324, 1.05171255876, 1.05507051713, 1.04499664204, 1.00671591672, + 1.29079919409, 1.04499664204, 1.04499664204, 0.77098723976, 0.77098723976, 0.7918065816, + 1.04768300873, 1.04768300873, 0.75016789792, 0.78643384822, 0.9805238415, 0.77098723976, + 0.75016789792, 0.75016789792, 0.75016789792, 1.02686366689, 0.75016789792, 1.30826057757, + 1.30826057757, 1.30826057757, 0, 0, 1, 1.23304231028, 1.0194761585, 0.6924110141, 1, + 1.30826057757, 1.27871054399, 0.13096037609, 1.16185359302, 0.66420416387, 0.65815983882, + 0.47347212895, 0.12155809268, 1.16185359302, 0.08059100067, 0.53727333781, 0.86165211551, + 0.64002686367, 0.66689053056, 0.25117528543, 1.02686366689, 1.24378777703, 0.19006044325, + 0.29751511081, 0.62256548019, 0.66420416387, 0.65815983882, 1.00268636669, 1.00268636669, + 1.01880456682, 1.02014775017, 1.37609133647, 1.37609133647, 1.37609133647, 1.33781061115, + 1.25721961048, 1.37609133647, 1, 1.30221625252, 1.37609133647, 1.37609133647, 1.37609133647, + 1.25721961048, 1.37609133647, 1.37609133647, 1.37609133647, 1.25721961048, 1, 1.33781061115, + 1.39691067831, 1.39691067831, 1.39691067831, 1.35862995299, 1.27803895232, 0.73472128946, + 1.17998656817, 1.39691067831, 1.39691067831, 1.39691067831, 1.27803895232, 1.37609133647, 1, + 1.0678307589, 1.14640698455, 1.14640698455, 1.14640698455, 1.10812625923, 1.02753525856, + 1.34318334453, 0.79046339825, 1.05171255876, 1.14304902619, 1.14304902619, 1.14304902619, + 1.0241773002, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, 1.0725319006, + 1.08730691739, 1.14640698455, 1.14640698455, 1.14640698455, 1.10812625923, 1.02753525856, + 0.86635325722, 0.93284083277, 1.14640698455, 1.14640698455, 1.14640698455, 1.02753525856, + 1.40228341169, 1.32169241101, 1.2834116857, + ], afterStack: 0.09066487576, bold: { advances: [ diff --git a/src/index.ts b/src/index.ts index 1646cd6..8513e1e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,9 @@ export { export { ARROWHEADS, DEFAULT_LEADER_ARROWHEAD, + DIMENSION_FRACTIONS, + DIMENSION_TEXT_FITS, + DIMENSION_TEXT_PLACEMENTS, LEADER_ARROWHEADS, leaderArrowheadInfo, type Arrowhead, @@ -26,11 +29,17 @@ export type { CallSite } from "./callsite.ts"; export { arrowheadHandles, dimensionAngle, + dimensionFileText, + dimensionMeasure, dimensionPicture, dimensionPictureHandles, dimensionStyleHandle, + dimensionTexts, findDimensionStyle, + mtextOfLabel, + pictureTexts, type ArrowheadEntity, + type DimensionFont, type DimensionLabel, type DimensionPicture, type DimensionPictureHandles, @@ -165,7 +174,9 @@ export { } from "./paragraph-codes.ts"; export { attachmentPlace, + layoutDimensionText, layoutParagraph, + measureDimensionText, lineSpacingStyleCode, measureParagraph, paragraphAttachment, @@ -268,6 +279,7 @@ export { layoutMtext, measureMtext } from "./read/mtext.ts"; export { BLOCK_ITEMS, CENSUS_LIMIT, + dimensionTextParts, GEOMETRY_ITEMS, READ_FORMAT, type DrawingRead, diff --git a/src/inspect.ts b/src/inspect.ts index 232c822..1d305bd 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -12,7 +12,7 @@ import { type XrefDrawings, } from "./blocks.ts"; import { callOf, type CallSite } from "./callsite.ts"; -import { dimensionPicture } from "./dimensions.ts"; +import { dimensionPicture, pictureTexts } from "./dimensions.ts"; import { leaderPicture, leaderRepeats } from "./leaders.ts"; import type { Block, @@ -28,7 +28,12 @@ import type { import { written } from "./format.ts"; import { layerKey } from "./layers.ts"; import { inStyle, measurer } from "./measure.ts"; -import { measured, paragraphInStyle, paragraphMeasurer } from "./paragraphs.ts"; +import { + layoutDimensionText, + measured, + paragraphInStyle, + paragraphMeasurer, +} from "./paragraphs.ts"; import { paperInfo } from "./papers.ts"; import { shown } from "./rules.ts"; import { filled, Strings } from "./shape.ts"; @@ -302,20 +307,35 @@ export function inspectWithin( if (style === undefined) return; // Its style's prefix and suffix are read for each dimension that has the style. const reads = - (style.prefix?.length ?? 0) + (style.suffix?.length ?? 0) + (drawn.text?.length ?? 0); + (style.prefix?.length ?? 0) + + (style.suffix?.length ?? 0) + + (drawn.text?.length ?? 0) + + (drawn.textBelow?.length ?? 0); if (!walk(Math.floor(reads / 32))) return; - const { label } = dimensionPicture(drawn, style); - const text: Text = { - kind: "text", - layer: drawn.layer, - at: label.at, - height: label.height, - value: label.value, - rotation: label.rotation, - align: "center", - ...(label.style === undefined ? {} : { style: label.style }), - }; - if (text.value.trim() !== "") keep(text, index, matrix, from, attribute); + const tables = tablesOf(from); + const font = + style.textStyle === undefined ? undefined : tables.textStyles.get(key(style.textStyle)); + // Each line of its texts is a text where its block's paragraph lays it out. + for (const text of pictureTexts(dimensionPicture(drawn, style, font), font)) { + for (const line of measured(text, layoutDimensionText(text)).lines) { + if (line.value.trim() === "") continue; + const placed = matrix ? line.corners.map(place) : line.corners; + const inner = innerBox(placed); + if (!inner) continue; + texts.push({ + entity: index, + attribute, + id, + layer, + value: line.value, + at: placed[0]!, + corners: placed, + inner: inner.corners, + height: inner.height, + box: boxOf(placed), + }); + } + } return; } if (drawn.kind === "paragraph") { diff --git a/src/lint.ts b/src/lint.ts index 2ff9974..489ae6f 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -496,7 +496,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) break; case "linear-dimension": case "aligned-dimension": - cost += long1(e.style) + long1(e.text); + cost += long1(e.style) + long1(e.text) + long1(e.textBelow); break; case "leader": cost += long1(e.style) + long1(e.textStyle); @@ -996,8 +996,8 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) else if (!dimensionStyleNames.has(layerKey(name as string))) { add("undefined-dimension-style", "error", undefinedDimensionStyleProblem(name as string)); } else style = dimensionStyles.get(layerKey(name as string)); - const text: unknown = dimension.text; - if (text !== undefined) { + for (const text of [dimension.text, dimension.textBelow] as unknown[]) { + if (text === undefined) continue; const problem = checkDimensionText(text); if (problem) { add("dimension", "error", problem); @@ -1016,7 +1016,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (!style || !sound) return; // Its style's prefix and suffix are read again for each dimension that has the style. const reads = - (style.prefix?.length ?? 0) + (style.suffix?.length ?? 0) + ((text as string)?.length ?? 0); + (style.prefix?.length ?? 0) + + (style.suffix?.length ?? 0) + + ((dimension.text as string | undefined)?.length ?? 0) + + ((dimension.textBelow as string | undefined)?.length ?? 0); if (!spend(Math.floor(reads / 32), where)) return; const textStyle = style.textStyle === undefined ? undefined : stylesByKey.get(layerKey(style.textStyle)); diff --git a/src/paragraph-codes.ts b/src/paragraph-codes.ts index a83e9a4..38bebe8 100644 --- a/src/paragraph-codes.ts +++ b/src/paragraph-codes.ts @@ -114,6 +114,10 @@ export interface RunFormat { readonly bold: boolean; /** The font of `FONTS` a `\f` or `\F` code set, or undefined for the paragraph's own. */ readonly font: Font | undefined; + /** The height as a share of the paragraph's, which `\H` sets in a dimension's text. */ + readonly size: number; + /** Where a stack sits up and down the line, which `\A` sets in a dimension's text: 0 on it, 1 centered. */ + readonly align: 0 | 1 | 2; } /** A piece of a paragraph, in the order it is drawn. */ @@ -161,6 +165,8 @@ const PLAIN: RunFormat = { strikeThrough: false, bold: false, font: undefined, + size: 1, + align: 0, }; /** @@ -214,7 +220,9 @@ function sameFormat(a: RunFormat, b: RunFormat): boolean { a.overline === b.overline && a.strikeThrough === b.strikeThrough && a.bold === b.bold && - a.font === b.font + a.font === b.font && + a.size === b.size && + a.align === b.align ); } @@ -222,9 +230,10 @@ function sameFormat(a: RunFormat, b: RunFormat): boolean { * Reads a paragraph's value in one pass, in time and memory in proportion to its length, with a * stack of its own for its braces that holds at most `PARAGRAPH_NESTING` formats: a brace past * that is counted and changes nothing. It never throws, and reads any string: what it refuses - * is `problem`, the first it met. + * is `problem`, the first it met. With `dimension`, as for the text of a dimension's picture, it + * also reads `\A0;` to `\A2;` and `\H` with a factor, such as `\H0.75x;`. */ -export function parseParagraph(value: string): ParsedParagraph { +export function parseParagraph(value: string, dimension = false): ParsedParagraph { const pieces: ParagraphPiece[] = []; let problem: string | undefined; const fail = (message: string): void => { @@ -360,6 +369,17 @@ export function parseParagraph(value: string): ParsedParagraph { fail(paragraphNoSemicolon(letter)); return n; } + // The text of a dimension's picture centers its stacks and sizes its fractions. + const argument = value.slice(at + 1, end); + if (dimension && letter === "A" && /^[012]$/.test(argument)) { + set({ ...format, align: Number(argument) as 0 | 1 | 2 }); + return end + 1; + } + const times = dimension && letter === "H" ? /^(\d+(?:\.\d+)?)x$/.exec(argument) : null; + if (times !== null && Number(times[1]) > 0) { + set({ ...format, size: format.size * Number(times[1]) }); + return end + 1; + } fail(paragraphNotLaidOut(letter as NotLaidOutCode)); return end + 1; } diff --git a/src/paragraphs.ts b/src/paragraphs.ts index 9d1bedb..125ec44 100644 --- a/src/paragraphs.ts +++ b/src/paragraphs.ts @@ -206,6 +206,11 @@ interface Face { readonly rights: readonly number[]; readonly tops: readonly number[]; readonly bottoms: readonly number[]; + /** + * How far a stack's top stands above its top part's baseline for each character alone, where + * the tables hold it: for a regular face. + */ + readonly stackTops: readonly number[] | undefined; /** Where a text starts and ends to draw, as `layoutText` reads them: 0 for a bold face. */ readonly heads: readonly number[] | undefined; readonly tails: readonly number[] | undefined; @@ -214,6 +219,8 @@ interface Face { readonly afterStack: number; /** How far below the baseline a text of it reaches. */ readonly below: number; + /** One unit of a TrueType font's design grid, in heights: how far its space reaches below the baseline. */ + readonly unit: number; } /** A face of a font of `FONT_METRICS`, regular or bold. */ @@ -232,11 +239,14 @@ function faceOf(font: string, metrics: FontMetrics, bold: boolean): Face { rights: own?.rights ?? metrics.rights, tops: own?.tops ?? metrics.tops, bottoms: own?.bottoms ?? metrics.bottoms, + stackTops: own ? undefined : metrics.stackTops, heads: own ? undefined : metrics.heads, tails: own ? undefined : metrics.tails, underline: shx ? UNDERLINE_SHX : metrics.below * scale, afterStack: metrics.afterStack, below: metrics.below * scale, + // The fonts of `FONTS` have 2,048 units to the em. + unit: 1 / ((capHeightOf(font) ?? 1) * 2048), }; } @@ -281,10 +291,12 @@ function partOf(value: string, face: Face): Part { } left ??= face.lefts[index]!; ink = advance + face.rights[index]!; - // A space reaches neither up nor down: a part of spaces only stands as wide as they are. + // A space reaches neither up nor down: a part of spaces only stands as wide as they are. A + // stacked character reaches its own ink's top, which may be below a capital's. if (character !== " ") { - top = Math.max(top, face.tops[index]!); - bottom = Math.min(bottom, face.bottoms[index]!); + const below = face.bottoms[index]!; + top = Math.max(top, face.stackTops ? face.stackTops[index]! + below : face.tops[index]!); + bottom = Math.min(bottom, below); } advance += face.advances[index]!; } @@ -309,6 +321,8 @@ interface StackShape { readonly top: number; readonly bottom: number; readonly advance: number; + /** The height its parts are drawn at. */ + readonly size: number; } function stackShape( @@ -328,12 +342,14 @@ function stackShape( // The top part's baseline at a digit's top, and the slash's middle at the bottom part's ink // top, or a digit's where it has none. const digit = face.tops[indexOf("0")]!; - const up = digit * size; - const after = (top.ink + SLASH_GAP) * across; + // The top part stands on the bottom part's ink, as tall as it is from top to bottom. + const up = (bottom.top > bottom.bottom ? bottom.top - bottom.bottom : digit) * size; + // The gap after the top part is not widened or narrowed with the letters. + const after = top.ink * across + SLASH_GAP * size; parts.push({ value: top.value, x: -top.left * across, up, top: top.top }); parts.push({ value: bottom.value, x: after - bottom.left * across, up: 0, top: bottom.top }); const middle: Point = [ - (top.ink + SLASH_GAP / 2) * across, + top.ink * across + (SLASH_GAP / 2) * size, (bottom.top > 0 ? bottom.top : digit) * size, ]; const turn = (SLASH_ANGLE * Math.PI) / 180; @@ -346,7 +362,7 @@ function stackShape( [middle[0] + half[0], middle[1] + half[1]], ]; ink = after + bottom.ink * across; - rise = up + top.top * size; + rise = up + (top.top - top.bottom) * size; } else { const wide = Math.max(top.ink, bottom.ink); const bar = (bottom.top - bottom.bottom + STACK_GAP) * size; @@ -367,7 +383,7 @@ function stackShape( ]; } ink = wide * across; - rise = up + top.top * size; + rise = up + (top.top - top.bottom) * size; } return { parts, @@ -376,6 +392,19 @@ function stackShape( top: rise, bottom: bottom.bottom * size, advance: ink + face.afterStack * across, + size, + }; +} + +/** A stack moved down the line by `by`. */ +function lowered(shape: StackShape, by: number): StackShape { + const down = (p: Point): Point => [p[0], p[1] - by]; + return { + ...shape, + parts: shape.parts.map((part) => ({ ...part, up: part.up - by })), + stroke: shape.stroke && [down(shape.stroke[0]), down(shape.stroke[1])], + top: shape.top - by, + bottom: shape.bottom - by, }; } @@ -466,6 +495,23 @@ export function layoutParagraph(paragraph: ParagraphToMeasure): ParagraphLayout return layOut(settingsOf(paragraph), parseParagraph(paragraph.value)); } +/** + * Lays out the text of a dimension's picture as `layoutParagraph` lays out a paragraph, with the + * codes such a text holds: `\A1;`, which centers its stacks, and `\H` with a factor, which sizes + * a fraction. + */ +export function layoutDimensionText(paragraph: ParagraphToMeasure): ParagraphLayout { + return layOut( + { ...settingsOf(paragraph), dimension: true }, + parseParagraph(paragraph.value, true), + ); +} + +/** The text of a dimension's picture where it plots, as `measureParagraph` gives a paragraph. */ +export function measureDimensionText(paragraph: ParagraphToMeasure): ParagraphMeasure { + return measured(paragraph, layoutDimensionText(paragraph)); +} + /** What a paragraph's layout reads of it apart from its value, with each number as written. */ interface Settings { readonly height: number; @@ -479,6 +525,11 @@ interface Settings { readonly font: string | undefined; readonly align: ParagraphAlign | undefined; readonly valign: ParagraphVerticalAlign | undefined; + /** + * True for the text of a dimension's picture, whose box ends below the last line's characters + * and below where a stack sets its lowest part, and not at a stacked part's ink. + */ + readonly dimension?: boolean; } /** A paragraph's settings, from its numbers as the writers write them, as a file holds them. */ @@ -710,12 +761,29 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { if ((blank(top) && top.ink > bottom.ink) || (blank(bottom) && bottom.ink > top.ink)) { approximate = true; } - const shape = stackShape(top, bottom, piece.separator, face, height, widthFactor); + const stacked = stackShape( + top, + bottom, + piece.separator, + face, + height * piece.format.size, + widthFactor, + ); + // A centered stack's bar, or the middle of its slash, is half a height above the line. + let shape = stacked; + if (piece.format.align !== 0) { + const stroke = stacked.stroke; + if (piece.format.align === 1 && stroke !== undefined && piece.separator !== "^") { + shape = lowered(stacked, Math.max(0, (stroke[0][1] + stroke[1][1]) / 2 - height / 2)); + } else approximate = true; + } const value = `${piece.top}${piece.separator}${piece.bottom}`; word.items[word.count++] = { kind: "stack", shape, face, value }; continue; } if (face.shx && piece.diameter) approximate = true; + // Characters at a size of their own are not laid out yet. + if (piece.format.size !== 1) approximate = true; const { format } = piece; const key = keyOf(format, face); let from = 0; @@ -748,10 +816,15 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { /** How far the lean moves where the line starts: by its first character's bottom. */ let startLean = 0; let end = 0; + // What the box of a dimension's text takes below the baseline: how far its characters reach, + // and how far below the line a stack sets its lowest part's baseline. + let runDown = 0; + let drop = 0; for (const item of built.items) { if (item.kind === "stack") { stackUp = Math.max(stackUp, item.shape.top); down = Math.min(down, item.shape.bottom); + for (const part of item.shape.parts) drop = Math.max(drop, -part.up); start ??= item.x; end = item.x + item.shape.ink; continue; @@ -759,6 +832,13 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const run = item; up = Math.max(up, (run.format.overline ? Math.max(run.top, OVERLINE) : run.top) * height); down = Math.min(down, run.bottom * height); + runDown = Math.min( + runDown, + run.bottom * height, + settings.dimension && !run.face.shx && valueOf(run).includes(" ") + ? -run.face.unit * height + : 0, + ); if (start === undefined) { let index = tableIndex( (run.head?.[0] ?? run.source.slice(run.from, run.to)).codePointAt(0) ?? 32, @@ -780,7 +860,8 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { built, top, below: stackUp > up ? 0 : AT_LEAST_BELOW * height, - down, + // A dimension's box reaches where a stack sets its lowest part only when the stack reaches highest. + down: settings.dimension ? runDown - (stackUp > up ? drop : 0) : down, start: start ?? 0, end, leanedStart: (start ?? 0) + startLean - shift, @@ -877,7 +958,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { add(item.value); const at = item.x + offset; for (const part of item.shape.parts) { - run(part.value, at + part.x, baseline + part.up, height, item.face, part.top); + run(part.value, at + part.x, baseline + part.up, item.shape.size, item.face, part.top); } const drawnStroke = item.shape.stroke; if (drawnStroke) { diff --git a/src/read/check.ts b/src/read/check.ts index a4af9ec..b24bd37 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -164,6 +164,7 @@ const ENTITY: Readonly> = { textAt: "point", "measurement?": "number", "text?": "string", + "textBelow?": "string", style: "string", "block?": "string", "blockHandle?": "string", @@ -268,6 +269,14 @@ const DRAWING_READ: Fields = { "precision?": "number", "lengthFactor?": "number", "suffix?": "string", + "textVertical?": "number", + "textInside?": "number", + "textMove?": "number", + "fraction?": "number", + "fractionScale?": "number", + "dimensionLineweight?": "number", + "extensionLineweight?": "number", + "arrowheadBlock?": "string", }, }, }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index b2563da..14ebd71 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -445,7 +445,10 @@ class DxfReader { readonly layers: ReadLayer[] = []; readonly linetypes: ReadLinetype[] = []; readonly textStyles: ReadTextStyle[] = []; - readonly dimensionStyles: (ReadDimensionStyle & { textStyleHandle?: string })[] = []; + readonly dimensionStyles: (ReadDimensionStyle & { + textStyleHandle?: string; + arrowheadHandle?: string; + })[] = []; /** Each block record's name, by its handle. */ readonly blockRecords = new Map(); readonly blocks: BlockDraft[] = []; @@ -692,6 +695,13 @@ class DxfReader { ["lengthUnits", 277], ["precision", 271], ["lengthFactor", 144], + ["textVertical", 77], + ["textInside", 174], + ["textMove", 279], + ["fraction", 276], + ["fractionScale", 146], + ["dimensionLineweight", 371], + ["extensionLineweight", 372], ]; const style: Record = { handle, name: recordName }; style.annotative = annotative(r); @@ -703,6 +713,8 @@ class DxfReader { if (suffix !== undefined && suffix !== "") style.suffix = suffix; const textStyle = handleAt(r, 340); if (textStyle !== undefined) style.textStyleHandle = textStyle; + const arrowhead = handleAt(r, 342); + if (arrowhead !== undefined) style.arrowheadHandle = arrowhead; this.dimensionStyles.push(style as unknown as ReadDimensionStyle); return; } @@ -1262,10 +1274,19 @@ class DxfReader { for (const style of this.textStyles) { if (style.handle !== undefined) styleNames.set(style.handle, style.name); } - const dimensionStyles = this.dimensionStyles.map(({ textStyleHandle, ...style }) => { - const textStyle = textStyleHandle === undefined ? undefined : styleNames.get(textStyleHandle); - return textStyle === undefined ? style : { ...style, textStyle }; - }); + const dimensionStyles = this.dimensionStyles.map( + ({ textStyleHandle, arrowheadHandle, ...style }) => { + const textStyle = + textStyleHandle === undefined ? undefined : styleNames.get(textStyleHandle); + const arrowheadBlock = + arrowheadHandle === undefined ? undefined : this.blockRecords.get(arrowheadHandle); + return { + ...style, + ...(textStyle !== undefined && { textStyle }), + ...(arrowheadBlock !== undefined && arrowheadBlock !== "" && { arrowheadBlock }), + }; + }, + ); this.#startsOfTexts(); this.#leaderStyles(styleNames); this.#blockHandles(); diff --git a/src/read/entities.ts b/src/read/entities.ts index e175367..263950d 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -12,6 +12,7 @@ import type { ReadPolyline, ReadTextPlacement, } from "./model.ts"; +import { dimensionTextParts } from "./model.ts"; import { facing, first, @@ -323,6 +324,7 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re const measurement = num(r, 42) ?? (r12 ? undefined : 1); const text = first(r, 1); const block = name(r, 2); + const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); const entity: ReadDimension = { ...base, kind: "dimension", @@ -333,7 +335,7 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re ...(angle !== 0 && { angle }), textAt: point(r, 11), ...(measurement !== undefined && { measurement }), - ...(text !== undefined && text !== "" && { text: textOnce(text) }), + ...parts, style: name(r, 3) ?? "Standard", ...(block !== undefined && block !== "" && { block }), }; @@ -478,7 +480,7 @@ export function costOf(e: ReadEntity): number { case "mtext": return own + 1 + chars(e.value) + chars(e.style); case "dimension": - return own + 4 + chars(e.text) + chars(e.style) + chars(e.block); + return own + 4 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "multileader": { let points = 3; for (const shaft of e.shafts) points += shaft.length; diff --git a/src/read/model.ts b/src/read/model.ts index 2dd77ea..8f101a3 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -165,6 +165,22 @@ export interface ReadDimensionStyle { readonly lengthFactor?: number; /** `DIMPOST`. */ readonly suffix?: string; + /** `DIMTAD`: 0 centers the text in a break of the dimension line, 1 puts it above. */ + readonly textVertical?: number; + /** `DIMTIX`: 1 keeps the text between the extension lines whatever fits. */ + readonly textInside?: number; + /** `DIMTMOVE`: 1 hangs a text that does not fit on a leader. */ + readonly textMove?: number; + /** `DIMFRAC`: 0 stacks a fraction across a bar, 1 diagonally, and 2 writes it on the line. */ + readonly fraction?: number; + /** `DIMTFAC`: the height of a stacked fraction as a share of the text's. */ + readonly fractionScale?: number; + /** `DIMLWD`, the dimension line's lineweight as group 370 holds one: -2 ByBlock. */ + readonly dimensionLineweight?: number; + /** `DIMLWE`, the extension lines' lineweight, likewise. */ + readonly extensionLineweight?: number; + /** The block `DIMBLK` draws each arrowhead with, such as `_ArchTick`. Missing for closed filled. */ + readonly arrowheadBlock?: string; } /** An attribute definition of a block, placed as a text is. */ @@ -332,6 +348,20 @@ export interface ReadMtext extends ReadEntityBase { readonly lineSpacingStyle: "at-least" | "exactly"; } +/** + * A dimension's text as a file holds it, cut at its first `\\X` into what it draws over its line + * and below it. A text of `<>` alone over the line is the measurement, and is left out. + */ +export function dimensionTextParts(held: string): { + readonly text?: string; + readonly textBelow?: string; +} { + const at = held.indexOf("\\X"); + if (at < 0) return held === "" ? {} : { text: held }; + const text = held.slice(0, at); + return { ...(text !== "<>" && { text }), textBelow: held.slice(at + 2) }; +} + /** A linear or an aligned dimension. */ export interface ReadDimension extends ReadEntityBase { readonly kind: "dimension"; @@ -353,6 +383,8 @@ export interface ReadDimension extends ReadEntityBase { readonly measurement?: number; /** The text it draws in place of its measurement, where `<>` stands for it. */ readonly text?: string; + /** The words it draws below its line, which the file holds after `\\X` in its text. */ + readonly textBelow?: string; /** Its dimension style, `Standard` when the file names none. */ readonly style: string; /** The block of its picture, `*D` and a number, when it has one. */ diff --git a/src/rules.ts b/src/rules.ts index 3f0838e..fd75318 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -10,6 +10,10 @@ import { paperInfo, PLOT_STYLE_TABLES, type Paper, type PlotStyleTable } from ". import { ARROWHEAD_BLOCKS, arrowheadInfo, + DEFAULT_ARROWHEAD, + DIMENSION_FRACTIONS, + DIMENSION_TEXT_FITS, + DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, MAX_PRECISION, @@ -165,7 +169,7 @@ const POLYLINE_WIDTH = "A polyline's width cannot be less than 0. The leading CAD app reads a negative width of every side as 0, and keeps a negative width of one side with no AUDIT error"; const DONUT_HOLE = "A donut's hole cannot be less than 0 across"; const ARROWHEAD_BLOCK = - "Block names cannot be _ArchTick, _Open, _Dot or _None, in any case of their letters. The leading CAD app draws the architectural tick of a dimension and the arrowheads of a leader with the blocks of those names"; + "Block names cannot be _ArchTick, _Oblique, _Open, _Dot or _None, in any case of their letters. The leading CAD app draws the ticks of a dimension and the arrowheads of a leader with the blocks of those names"; const STANDARD_DIMENSION_STYLE_DEFINED = 'The dimension style "Standard" is in every drawing and cannot be defined. The leading CAD app keeps the first style of a name and skips a second'; const STANDARD_DIMENSION_STYLE_USED = @@ -184,6 +188,15 @@ const PRECISION = const ZERO_SUPPRESSION = 'suppressZeros must be "leading", "trailing" or "both"'; const DIMENSION_UNITS_MESSAGE = 'units must be "decimal" or "architectural"'; const FEET_INCH_ZEROS_MESSAGE = 'feetInchZeros must be "inches", "feet", "both" or "neither"'; +const DIMENSION_FRACTION_MESSAGE = 'fraction must be "inline", "stacked" or "diagonal"'; +const FRACTION_SCALE_MESSAGE = + "fractionScale must be a number from 0.25 to 1: the height of a stacked fraction as a share of the text's"; +const FRACTION_OF_UNITS = + 'fraction and fractionScale are for a style in "architectural" units, which writes a fraction of an inch'; +const FRACTION_SCALE_INLINE = + 'fractionScale sizes a fraction that is "stacked" or "diagonal". A fraction on the line is as high as the text'; +const TEXT_PLACEMENT_MESSAGE = 'textPlacement must be "above" or "centered"'; +const TEXT_FIT_MESSAGE = 'textFit must be "inside" or "leader"'; const ZEROS_OF_UNITS = 'suppressZeros is for a style in decimal units, and feetInchZeros for one in "architectural" units, which writes feet and inches'; const DIMENSION_FORMATTING = @@ -481,7 +494,7 @@ export type BlockName = string extends N : NameCheck; /** The blocks the leading CAD app draws arrowheads with. */ -type TickBlock = "_ArchTick" | "_Open" | "_Dot" | "_None"; +type TickBlock = "_ArchTick" | "_Oblique" | "_Open" | "_Dot" | "_None"; /** * Resolves to `N` when it is a valid name for a dimension style to be used by, and to the error @@ -2529,6 +2542,73 @@ export function dimensionStyleProblem(style: unknown): string | undefined { const problem = measurementScaleProblem(s.measurementScale); if (problem) return `measurementScale: ${problem}`; } + return dimensionStyleLookProblem(s); +} + +/** Returns what is wrong with a dimension style's `fraction`, or undefined. */ +export function fractionProblem(value: unknown): string | undefined { + return (DIMENSION_FRACTIONS as readonly unknown[]).includes(value) + ? undefined + : DIMENSION_FRACTION_MESSAGE; +} + +/** Returns what is wrong with a dimension style's `fractionScale`, or undefined. */ +export function fractionScaleProblem(value: unknown): string | undefined { + return typeof value === "number" && written(value) >= 0.25 && written(value) <= 1 + ? undefined + : FRACTION_SCALE_MESSAGE; +} + +/** Returns what is wrong with a dimension style's `textPlacement`, or undefined. */ +export function textPlacementProblem(value: unknown): string | undefined { + return (DIMENSION_TEXT_PLACEMENTS as readonly unknown[]).includes(value) + ? undefined + : TEXT_PLACEMENT_MESSAGE; +} + +/** Returns what is wrong with a dimension style's `textFit`, or undefined. */ +export function textFitProblem(value: unknown): string | undefined { + return (DIMENSION_TEXT_FITS as readonly unknown[]).includes(value) ? undefined : TEXT_FIT_MESSAGE; +} + +/** + * Returns what is wrong with what a dimension style sets of how its dimensions look, or undefined: + * its fraction and the fraction's height, where its text goes and its lineweights. + */ +export function dimensionStyleLookProblem(s: Record): string | undefined { + if (s.fraction !== undefined) { + const problem = fractionProblem(s.fraction); + if (problem) return problem; + } + if (s.fractionScale !== undefined) { + const problem = fractionScaleProblem(s.fractionScale); + if (problem) return problem; + } + // A fraction on the line, at the text's own height, is what every style writes. + const stacked = s.fraction !== undefined && s.fraction !== "inline"; + const scaled = s.fractionScale !== undefined && written(s.fractionScale as number) !== 1; + if ((stacked || scaled) && s.units !== "architectural") return FRACTION_OF_UNITS; + if (scaled && !stacked) return FRACTION_SCALE_INLINE; + if (s.textPlacement !== undefined) { + const problem = textPlacementProblem(s.textPlacement); + if (problem) return problem; + } + if (s.textFit !== undefined) { + const problem = textFitProblem(s.textFit); + if (problem) return problem; + } + if ( + s.textFit === "leader" && + s.textPlacement === "centered" && + (s.arrowhead ?? DEFAULT_ARROWHEAD) === "closed-filled" + ) + return LEADER_CENTERED_ARROWS; + for (const field of ["dimensionLineweight", "extensionLineweight"] as const) { + const value = s[field]; + if (value === undefined) continue; + if (typeof value === "number" && (LINEWEIGHTS as readonly number[]).includes(value)) continue; + return `${field}: ${LINEWEIGHT}`; + } return undefined; } @@ -2590,6 +2670,19 @@ export function dimensionTextProblem(text: unknown): string | undefined { return text.includes("<>") && text.includes("[]") ? DIMENSION_TEXT_ALTERNATE : undefined; } +/** What is wrong with words below a dimension's line whose text moves out on a leader. */ +export const DIMENSION_LEADER_BELOW = + "its text does not fit between its extension lines and moves out on a leader, and where words below the line then go is not laid out yet, so tsdraft refuses it. Give it more room, or leave textBelow out"; +/** What is wrong with a text that moves out on a leader beside arrowheads larger than it. */ +export const DIMENSION_LEADER_ARROWS = + "its style moves a text that does not fit out on a leader, and its arrowheads are twice as long as its text is high or longer, where the leading CAD app may keep the text and move the arrowheads instead, which is not laid out yet, so tsdraft refuses it. Use a smaller arrow size"; +/** What is wrong with a text centered in a dimension line it is wider than. */ +export const DIMENSION_CENTERED_WIDE = + "its text, centered in its line, needs more room than the line has between its extension lines, and where the line's pieces then go is not laid out yet, so tsdraft refuses it. Give it more room, a smaller text, or the text above the line"; +/** What is wrong with a style whose closed arrowheads may turn outward round a text it moves out. */ +const LEADER_CENTERED_ARROWS = + 'textFit "leader" with closed filled arrowheads and the text "centered" turns the arrowheads outward where tsdraft does not know the room they need, which is not laid out yet, so tsdraft refuses it. Use a tick, or the text "above"'; + /** What is wrong with a dimension in a block. */ export const DIMENSION_IN_BLOCK = "a dimension cannot be in a block. The leading CAD app draws nothing for a dimension inside a block when it opens the file, so an insert of the block would show nothing of it. Draw it in model space or on a layout"; @@ -2687,12 +2780,18 @@ export function dimensionMeasureProblem( if (digits > MEASUREMENT_DIGITS) { return `it reads ${rounded}, which is ${digits} digits at a precision of ${decimals.length}. The leading CAD app works out the 16th digit of a measurement from its own arithmetic on the points, so it may end in another digit: it writes 99,999,999.5 at a precision of 8 as 99999999.50000002. Use a smaller precision or measurement scale`; } - if (room !== undefined && measurement <= room) { - return `its text may not fit between its extension lines: it measures ${written(measurement)}, and its text, ${JSON.stringify(text)}, and its arrowheads may need ${written(room)}. The leading CAD app then turns closed filled arrowheads outward, by the width of the text in its font, which tsdraft does not hold. Give it more room, a smaller text or arrow size, or the arrowhead "architectural-tick", which is drawn the same either way`; - } + if (room !== undefined && measurement <= room) return arrowRoomProblem(measurement, text, room); return undefined; } +/** + * What is wrong with a dimension that measures no more than its closed filled arrowheads and its + * text need, as `arrowRoom` gives the room. + */ +export function arrowRoomProblem(measurement: number, text: string, room: number): string { + return `its text may not fit between its extension lines: it measures ${written(measurement)}, and its text, ${JSON.stringify(text)}, and its arrowheads may need ${written(room)}. The leading CAD app then turns closed filled arrowheads outward, by the width of the text in its font, which tsdraft does not hold. Give it more room, a smaller text or arrow size, or the arrowhead "architectural-tick", which is drawn the same either way`; +} + // Leaders. const STANDARD_LEADER_STYLE_DEFINED = diff --git a/src/shape.ts b/src/shape.ts index d3a2779..f68727b 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -486,11 +486,11 @@ function shapes(all: boolean, typed = all): Shapes { ), "linear-dimension": fields( { kind, layer: string, style: ruled(string), from: point, to: point, line: point }, - { id: ruled(string), angle: number, text: ruled(string) }, + { id: ruled(string), angle: number, text: ruled(string), textBelow: ruled(string) }, ), "aligned-dimension": fields( { kind, layer: string, style: ruled(string), from: point, to: point, offset: number }, - { id: ruled(string), text: ruled(string) }, + { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, ), // A rule of `lint` reports the note, the shafts and the leader's own fields, whatever their type. leader: fields( @@ -596,6 +596,12 @@ function shapes(all: boolean, typed = all): Shapes { suppressZeros: ruled(string), feetInchZeros: ruled(string), measurementScale: ruled(number), + fraction: ruled(string), + fractionScale: ruled(number), + textPlacement: ruled(string), + textFit: ruled(string), + dimensionLineweight: ruled(numberOrName), + extensionLineweight: ruled(numberOrName), }, ), ); diff --git a/src/standard/default.ts b/src/standard/default.ts index 02fe6ff..225d3ca 100644 --- a/src/standard/default.ts +++ b/src/standard/default.ts @@ -23,7 +23,7 @@ const architectural = (id: string, label: string, inches: number) => export const BUILT_IN_DOCUMENT = { id: "tsdraft", - version: "1", + version: "2", paperUnits: "in", minTextHeight: 0.0625, linetypeScale: 0.5, @@ -117,6 +117,21 @@ export const BUILT_IN_DOCUMENT = { }, description: 'Feet and inches to the nearest 1/16", as 4\'-1 7/16"', }, + arrows: { + role: "dimension", + arrowhead: "closed-filled", + arrowSize: 0.125, + extensionOffset: 0.0625, + extensionBeyond: 0.125, + textGap: 0.0625, + textPlacement: "centered", + writing: { + ft: { precision: 2, suffix: "'" }, + in: { precision: 0, suffix: '"' }, + mm: { precision: 0 }, + }, + description: "Closed filled arrows, with the text centered in a break of the line", + }, }, titleBlocks: { plain: { diff --git a/src/standard/define.ts b/src/standard/define.ts index f130dea..70b180f 100644 --- a/src/standard/define.ts +++ b/src/standard/define.ts @@ -146,7 +146,7 @@ const plainDrawing = (): Drawing => (plain ??= remember(frozen(plainTitleBlock() * standard. A change to what it states needs a new version, which the CHANGELOG gives, and then * this hash. */ -const BUILT_IN_HASH = "6594f10d73a998d20b826bf3eb76bb0a7dad8cd367f69d4afb67062c30787947"; +const BUILT_IN_HASH = "1362b9bbdeb7f2e7ef79c87edb2e234329d86488513561beb27c351ffd9b214c"; let builtIn: Standard | undefined; /** The built-in standard, made once. */ diff --git a/src/standard/document.ts b/src/standard/document.ts index 7434773..28bec93 100644 --- a/src/standard/document.ts +++ b/src/standard/document.ts @@ -3,6 +3,9 @@ // literal through `CheckDocument`, and every value when the code runs. import type { Arrowhead, + DIMENSION_FRACTIONS, + DIMENSION_TEXT_FITS, + DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, LeaderArrowhead, @@ -170,6 +173,8 @@ export interface WritingDocument extends Commented { readonly suppressZeros?: string; readonly feetInchZeros?: string; readonly measurementScale?: number; + readonly fraction?: string; + readonly fractionScale?: number; } export interface DimensionStyleFieldsDocument extends Commented { @@ -180,6 +185,10 @@ export interface DimensionStyleFieldsDocument extends Commented { readonly extensionOffset?: number; readonly extensionBeyond?: number; readonly textGap?: number; + readonly textPlacement?: string; + readonly textFit?: string; + readonly dimensionLineweight?: number; + readonly extensionLineweight?: number; readonly writing?: { readonly [U in Units]?: WritingDocument }; readonly description?: string; } @@ -338,6 +347,8 @@ export interface StandardWriting { readonly suffix?: string; readonly suppressZeros?: (typeof ZERO_SUPPRESSIONS)[number]; readonly feetInchZeros?: (typeof FEET_INCH_ZEROS)[number]; + readonly fraction: (typeof DIMENSION_FRACTIONS)[number]; + readonly fractionScale: number; readonly measurementScale: number; } @@ -348,6 +359,10 @@ export interface StandardDimensionStyleFields { readonly extensionOffset?: number; readonly extensionBeyond?: number; readonly textGap?: number; + readonly textPlacement?: (typeof DIMENSION_TEXT_PLACEMENTS)[number]; + readonly textFit?: (typeof DIMENSION_TEXT_FITS)[number]; + readonly dimensionLineweight?: number; + readonly extensionLineweight?: number; readonly writing?: { readonly [U in Units]?: StandardWriting }; readonly description?: string; } @@ -359,6 +374,10 @@ export interface StandardDimensionStyle { readonly extensionOffset: number; readonly extensionBeyond: number; readonly textGap: number; + readonly textPlacement: (typeof DIMENSION_TEXT_PLACEMENTS)[number]; + readonly textFit: (typeof DIMENSION_TEXT_FITS)[number]; + readonly dimensionLineweight?: number; + readonly extensionLineweight?: number; readonly writing: { readonly [U in Units]?: StandardWriting }; /** Its name in the leading CAD app on a layout, when it is not its id in capitals. */ readonly layoutName?: string; diff --git a/src/standard/lint.ts b/src/standard/lint.ts index 46b5baa..7c25742 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -357,6 +357,12 @@ export function lintStandard( writing.feetInchZeros ?? (writing.units === "architectural" ? "inches" : "none"), ], ["measurementScale", style.measurementScale ?? 1, writing.measurementScale], + ["fraction", style.fraction ?? "inline", writing.fraction], + ["fractionScale", style.fractionScale ?? 1, writing.fractionScale], + ["textPlacement", style.textPlacement ?? "above", fields.textPlacement], + ["textFit", style.textFit ?? "inside", fields.textFit], + ["dimensionLineweight", style.dimensionLineweight, fields.dimensionLineweight], + ["extensionLineweight", style.extensionLineweight, fields.extensionLineweight], ]; for (const [field, value, own] of expected) { const same = diff --git a/src/standard/literal.ts b/src/standard/literal.ts index a43b537..2d9633a 100644 --- a/src/standard/literal.ts +++ b/src/standard/literal.ts @@ -1,5 +1,10 @@ // The compile-time half of `defineStandard`: the names a document resolves to, with its parent's, // and the check of each literal in the document, whose message is the runtime check's. +import type { + DIMENSION_FRACTIONS, + DIMENSION_TEXT_FITS, + DIMENSION_TEXT_PLACEMENTS, +} from "../arrowheads.ts"; import type { ArrowheadOf, AttributeTag, @@ -123,6 +128,8 @@ type SectionNames = export type NamesOf = { readonly [S in Section]: SectionNames }; type Str = V extends string ? R : unknown; +/** A value of a list, or the list where it is another: a string as wide as JSON gives passes. */ +type OneOf = string extends V ? V : V extends U ? V : U; type Num = V extends number ? R : unknown; /** `Problem` when a name breaks a rule, and `never` when it is valid. */ @@ -302,7 +309,9 @@ type Writing = { > : F extends "measurementScale" ? Num> - : unknown; + : F extends "fraction" + ? Str> + : unknown; }; /** A name a standard gives a dimension style in the leading CAD app. */ @@ -322,11 +331,15 @@ type StyleFields = { ? Num> : F extends "textGap" ? Num> - : F extends "writing" - ? { readonly [U in keyof E[F]]: Writing } - : F extends "discipline" - ? Discipline - : unknown; + : F extends "textPlacement" + ? Str> + : F extends "textFit" + ? Str> + : F extends "writing" + ? { readonly [U in keyof E[F]]: Writing } + : F extends "discipline" + ? Discipline + : unknown; }; type DimensionStyle = { diff --git a/src/standard/shape.ts b/src/standard/shape.ts index a6c81ce..3437fd8 100644 --- a/src/standard/shape.ts +++ b/src/standard/shape.ts @@ -7,6 +7,9 @@ import { ARROWHEADS, DEFAULT_ARROWHEAD, DEFAULT_LEADER_ARROWHEAD, + DIMENSION_FRACTIONS, + DIMENSION_TEXT_FITS, + DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, LEADER_ARROWHEADS, @@ -19,6 +22,11 @@ import { DEFAULT_PLOT_STYLE_TABLE, PAPERS, PLOT_STYLE_TABLES } from "../papers.t import { arrowheadProblem, attributeTagProblem, + dimensionStyleLookProblem, + fractionProblem, + fractionScaleProblem, + textFitProblem, + textPlacementProblem, blockNameProblem, dimensionPrefixProblem, dimensionStyleNameProblem, @@ -451,8 +459,25 @@ const WRITING = record( description: "Each measurement is written times this", default: 1, }, + fraction: { + node: string({ enum: DIMENSION_FRACTIONS }, fractionProblem), + description: + "In architectural units, how the fraction of an inch is written: inline, as 4'-1 7/16\", stacked over a bar, or diagonal, beside a slash", + default: "inline", + }, + fractionScale: { + node: number({ minimum: 0.25, maximum: 1 }, fractionScaleProblem), + description: "The height of a stacked fraction as a share of the text's, from 0.25 to 1", + default: 1, + }, }, - (value) => zerosOfUnitsProblem(value.units, value.suppressZeros, value.feetInchZeros), + (value) => + zerosOfUnitsProblem(value.units, value.suppressZeros, value.feetInchZeros) ?? + dimensionStyleLookProblem({ + units: value.units, + fraction: value.fraction, + fractionScale: value.fractionScale, + }), ); const unitsOf = (what: string): Node => @@ -488,6 +513,27 @@ const STYLE_FIELDS = { "How far an extension line runs past the dimension line", ), textGap: size(textGapProblem, "The gap between the text and the dimension line"), + textPlacement: { + node: string({ enum: DIMENSION_TEXT_PLACEMENTS }, textPlacementProblem), + description: "The text above the dimension line, or centered in a break of it", + default: "above", + }, + textFit: { + node: string({ enum: DIMENSION_TEXT_FITS }, textFitProblem), + description: + "Where a text goes that does not fit between the extension lines: inside them all the same, or out on a leader", + default: "inside", + }, + dimensionLineweight: { + node: number({ enum: LINEWEIGHTS }, lineweightValueProblem), + description: + "The lineweight of the dimension line, its arrowheads and a leader to its text, in millimetres. Defaults to the dimension's own", + }, + extensionLineweight: { + node: number({ enum: LINEWEIGHTS }, lineweightValueProblem), + description: + "The lineweight of the extension lines, in millimetres. Defaults to the dimension's own", + }, writing: { node: unitsOf("a dimension style's writing"), description: diff --git a/src/svg.ts b/src/svg.ts index 2bd889b..1f4e68e 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -8,7 +8,7 @@ import { type Referenced, type XrefDrawings, } from "./blocks.ts"; -import { dimensionPicture, type Dimension } from "./dimensions.ts"; +import { dimensionPicture, pictureTexts, type Dimension } from "./dimensions.ts"; import { sweep, type DimensionStyle, @@ -49,12 +49,14 @@ import { leaderPicture, type LeaderPicture } from "./leaders.ts"; import { builtInLinetype, LINEWEIGHTS, lineweightCode } from "./linetypes.ts"; import { drawnValue, inStyle, layoutText } from "./measure.ts"; import { + layoutDimensionText, paragraphInStyle, paragraphMeasurer, paragraphTurn, placer, type ParagraphLayout, } from "./paragraphs.ts"; +import { arrowheadInfo, DEFAULT_ARROWHEAD } from "./arrowheads.ts"; import { DEFAULT_PLOT_STYLE_TABLE, paperInfo } from "./papers.ts"; import { shown as quoted, turning, viewportProblem } from "./rules.ts"; import { filled } from "./shape.ts"; @@ -644,6 +646,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const where = () => entityAt(i, e, space); drawingAt = where; if (e.kind !== "insert") { + // A dimension's texts are joined before it is drawn, so their length is paid for first. + if (e.kind === "linear-dimension" || e.kind === "aligned-dimension") { + if (!write((e.text?.length ?? 0) + (e.textBelow?.length ?? 0))) refuse(where()); + } const element = drawn(e, marks(e, i), pen(look, styled(e), { name: e.layer }, where), look); if (!write(element.length + line)) refuse(where()); return element; @@ -1233,9 +1239,10 @@ function paragraphToSvg( } /** - * A dimension as a group: its extension lines and its dimension line, which take the dashes - * of its pen, its arrowheads, filled, and its text. A dimension whose style the drawing does - * not have is an empty group. + * A dimension as a group: its extension lines, the pieces of its dimension line and the leader to + * a text moved out, which take the dashes of its pen and the lineweights its style gives them, + * its arrowheads, filled, or a tick with no width as a line, and each text as the paragraph its + * block holds. A dimension whose style the drawing does not have is an empty group. */ function dimensionToSvg( e: Dimension, @@ -1248,41 +1255,57 @@ function dimensionToSvg( room: number, ): string { if (style === undefined) return ``; - const picture = dimensionPicture(e, style); + const picture = dimensionPicture(e, style, textStyle); const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); - const line = (part: string, [from, to]: readonly [Point, Point]): string => + // A style's lineweight, as group 370 holds it, over the dimension's own. + const weighed = (code: number): Pen => (code < 0 ? pen : { ...pen, lineweight: code }); + const line = (part: string, [from, to]: readonly [Point, Point], drawn: Pen): string => entityToSvg( { kind: "line", layer: e.layer, from, to }, `data-part="${part}"`, - pen, + drawn, look, undefined, matrix, room, ); - const { label } = picture; - const text: Text = { - kind: "text", - layer: e.layer, - at: label.at, - height: label.height, - value: label.value, - rotation: label.rotation, - align: "center", - }; + const extension = weighed(picture.lineweights.extension); + const dimension = weighed(picture.lineweights.dimension); + const thin = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke?.width === 0; const parts = [ - ...picture.extensionLines.map((ends) => line("extension-line", ends)), - line("dimension-line", picture.dimensionLine), + ...picture.extensionLines.map((ends) => line("extension-line", ends, extension)), + ...picture.dimensionLines.map((ends) => line("dimension-line", ends, dimension)), + ...picture.leader.map((ends) => line("leader", ends, dimension)), ...picture.arrowheads.map((corners) => { + if (thin) return line("arrowhead", [corners[0]!, corners[1]!], dimension); const points = corners .map(at) .map(([x, y]) => `${fmt(x)},${fmt(y)}`) .join(" "); return ``; }), - entityToSvg(text, `data-part="text"`, pen, look, textStyle, matrix, room), + ...pictureTexts(picture, textStyle).map((text) => + paragraphToSvg( + { + kind: "paragraph", + layer: e.layer, + at: text.at!, + height: text.height, + value: text.value, + rotation: text.rotation ?? 0, + align: "center", + valign: "middle", + }, + () => layoutDimensionText(text), + `data-part="text"`, + pen, + look, + matrix, + room, + ), + ), ]; - return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; + return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } /** diff --git a/standard.json b/standard.json index da10423..74b78cb 100644 --- a/standard.json +++ b/standard.json @@ -1,7 +1,7 @@ { "$schema": "https://cdn.jsdelivr.net/npm/tsdraft@0.5.3/standard.schema.json", "id": "tsdraft", - "version": "1", + "version": "2", "title": "tsdraft", "paperUnits": "in", "minTextHeight": 0.0625, @@ -255,6 +255,42 @@ } }, "dimensionStyles": { + "arrows": { + "role": "dimension", + "arrowhead": "closed-filled", + "arrowSize": 0.125, + "extensionOffset": 0.0625, + "extensionBeyond": 0.125, + "textGap": 0.0625, + "textPlacement": "centered", + "textFit": "inside", + "writing": { + "in": { + "units": "decimal", + "precision": 0, + "suffix": "\"", + "measurementScale": 1, + "fraction": "inline", + "fractionScale": 1 + }, + "ft": { + "units": "decimal", + "precision": 2, + "suffix": "'", + "measurementScale": 1, + "fraction": "inline", + "fractionScale": 1 + }, + "mm": { + "units": "decimal", + "precision": 0, + "measurementScale": 1, + "fraction": "inline", + "fractionScale": 1 + } + }, + "description": "Closed filled arrows, with the text centered in a break of the line" + }, "dims": { "role": "dimension", "arrowhead": "architectural-tick", @@ -262,23 +298,31 @@ "extensionOffset": 0.0625, "extensionBeyond": 0.125, "textGap": 0.0625, + "textPlacement": "above", + "textFit": "inside", "writing": { "in": { "units": "decimal", "precision": 0, "suffix": "\"", - "measurementScale": 1 + "measurementScale": 1, + "fraction": "inline", + "fractionScale": 1 }, "ft": { "units": "decimal", "precision": 1, "suffix": "'", - "measurementScale": 1 + "measurementScale": 1, + "fraction": "inline", + "fractionScale": 1 }, "mm": { "units": "decimal", "precision": 0, - "measurementScale": 1 + "measurementScale": 1, + "fraction": "inline", + "fractionScale": 1 } } }, @@ -289,16 +333,22 @@ "extensionOffset": 0.0625, "extensionBeyond": 0.125, "textGap": 0.0625, + "textPlacement": "above", + "textFit": "inside", "writing": { "in": { "units": "architectural", "precision": 4, - "measurementScale": 1 + "measurementScale": 1, + "fraction": "inline", + "fractionScale": 1 }, "ft": { "units": "architectural", "precision": 4, - "measurementScale": 12 + "measurementScale": 12, + "fraction": "inline", + "fractionScale": 1 } }, "description": "Feet and inches to the nearest 1/16\", as 4'-1 7/16\"" diff --git a/standard.schema.json b/standard.schema.json index 5eeb508..0f611c2 100644 --- a/standard.schema.json +++ b/standard.schema.json @@ -278,7 +278,7 @@ }, "arrowhead": { "type": "string", - "enum": ["closed-filled", "architectural-tick"], + "enum": ["closed-filled", "architectural-tick", "oblique"], "description": "One of ARROWHEADS", "default": "closed-filled" }, @@ -302,6 +302,34 @@ "minimum": 0, "description": "The gap between the text and the dimension line, on paper" }, + "textPlacement": { + "type": "string", + "enum": ["above", "centered"], + "description": "The text above the dimension line, or centered in a break of it", + "default": "above" + }, + "textFit": { + "type": "string", + "enum": ["inside", "leader"], + "description": "Where a text goes that does not fit between the extension lines: inside them all the same, or out on a leader", + "default": "inside" + }, + "dimensionLineweight": { + "type": "number", + "enum": [ + 0, 0.05, 0.09, 0.13, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.53, 0.6, 0.7, 0.8, + 0.9, 1, 1.06, 1.2, 1.4, 1.58, 2, 2.11 + ], + "description": "The lineweight of the dimension line, its arrowheads and a leader to its text, in millimetres. Defaults to the dimension's own" + }, + "extensionLineweight": { + "type": "number", + "enum": [ + 0, 0.05, 0.09, 0.13, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.53, 0.6, 0.7, 0.8, + 0.9, 1, 1.06, 1.2, 1.4, 1.58, 2, 2.11 + ], + "description": "The lineweight of the extension lines, in millimetres. Defaults to the dimension's own" + }, "writing": { "$ref": "#/$defs/writings", "description": "How a length is written in each unit of a drawing. A drawing in a unit it does not list cannot draw a dimension in the style", @@ -360,7 +388,7 @@ }, "arrowhead": { "type": "string", - "enum": ["closed-filled", "architectural-tick"], + "enum": ["closed-filled", "architectural-tick", "oblique"], "description": "One of ARROWHEADS" }, "arrowSize": { @@ -383,6 +411,32 @@ "minimum": 0, "description": "The gap between the text and the dimension line, on paper" }, + "textPlacement": { + "type": "string", + "enum": ["above", "centered"], + "description": "The text above the dimension line, or centered in a break of it" + }, + "textFit": { + "type": "string", + "enum": ["inside", "leader"], + "description": "Where a text goes that does not fit between the extension lines: inside them all the same, or out on a leader" + }, + "dimensionLineweight": { + "type": "number", + "enum": [ + 0, 0.05, 0.09, 0.13, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.53, 0.6, 0.7, 0.8, + 0.9, 1, 1.06, 1.2, 1.4, 1.58, 2, 2.11 + ], + "description": "The lineweight of the dimension line, its arrowheads and a leader to its text, in millimetres. Defaults to the dimension's own" + }, + "extensionLineweight": { + "type": "number", + "enum": [ + 0, 0.05, 0.09, 0.13, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.53, 0.6, 0.7, 0.8, + 0.9, 1, 1.06, 1.2, 1.4, 1.58, 2, 2.11 + ], + "description": "The lineweight of the extension lines, in millimetres. Defaults to the dimension's own" + }, "writing": { "$ref": "#/$defs/writings", "description": "How a length is written in each unit of a drawing. A drawing in a unit it does not list cannot draw a dimension in the style" @@ -916,7 +970,7 @@ }, "blockName": { "type": "string", - "pattern": "^(?! )(?![\\s\\S]* $)(?!(?:_[Aa][Rr][Cc][Hh][Tt][Ii][Cc][Kk]|_[Oo][Pp][Ee][Nn]|_[Dd][Oo][Tt]|_[Nn][Oo][Nn][Ee])$)[\\u0020-\\u0021\\u0023-\\u0029\\u002b\\u002d-\\u002e\\u0030-\\u0039\\u0040-\\u005b\\u005d\\u005f\\u0061-\\u007b\\u007d-\\u007e\\u00a0-\\u05ff\\u0604-\\u06dc\\u06de-\\u070e\\u0710-\\u17b3\\u17b6-\\u200a\\u2010-\\u2029\\u202f-\\u205f\\u2065-\\u2069\\u2070\\u2072-\\u207e\\u2080-\\u208f\\u2095-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2118\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u2140-\\u2144\\u214a-\\u214d\\u214f-\\u217f\\u2189-\\u2bff\\u2c2f\\u2c5f\\u2c70\\u2c7e-\\u2c7f\\u2ce5-\\u2cff\\u2d26-\\u2d2f\\u2d66-\\u2d6e\\u2d70-\\u2d7f\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf-\\ud7ff\\ue000-\\ue7ff\\ue900-\\ufefe\\uff00-\\ufff8\\ufffc-\\uffff]{1,255}$", + "pattern": "^(?! )(?![\\s\\S]* $)(?!(?:_[Aa][Rr][Cc][Hh][Tt][Ii][Cc][Kk]|_[Oo][Bb][Ll][Ii][Qq][Uu][Ee]|_[Oo][Pp][Ee][Nn]|_[Dd][Oo][Tt]|_[Nn][Oo][Nn][Ee])$)[\\u0020-\\u0021\\u0023-\\u0029\\u002b\\u002d-\\u002e\\u0030-\\u0039\\u0040-\\u005b\\u005d\\u005f\\u0061-\\u007b\\u007d-\\u007e\\u00a0-\\u05ff\\u0604-\\u06dc\\u06de-\\u070e\\u0710-\\u17b3\\u17b6-\\u200a\\u2010-\\u2029\\u202f-\\u205f\\u2065-\\u2069\\u2070\\u2072-\\u207e\\u2080-\\u208f\\u2095-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2118\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u2140-\\u2144\\u214a-\\u214d\\u214f-\\u217f\\u2189-\\u2bff\\u2c2f\\u2c5f\\u2c70\\u2c7e-\\u2c7f\\u2ce5-\\u2cff\\u2d26-\\u2d2f\\u2d66-\\u2d6e\\u2d70-\\u2d7f\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf-\\ud7ff\\ue000-\\ue7ff\\ue900-\\ufefe\\uff00-\\ufff8\\ufffc-\\uffff]{1,255}$", "description": "The block of block that the builder inserts at [0, 0] on each sheet" }, "xref": { @@ -1047,6 +1101,19 @@ "exclusiveMinimum": 0, "description": "Each measurement is written times this", "default": 1 + }, + "fraction": { + "type": "string", + "enum": ["inline", "stacked", "diagonal"], + "description": "In architectural units, how the fraction of an inch is written: inline, as 4'-1 7/16\", stacked over a bar, or diagonal, beside a slash", + "default": "inline" + }, + "fractionScale": { + "type": "number", + "minimum": 0.25, + "maximum": 1, + "description": "The height of a stacked fraction as a share of the text's, from 0.25 to 1", + "default": 1 } }, "required": ["precision"], @@ -1093,7 +1160,7 @@ }, "name": { "type": "string", - "pattern": "^(?! )(?![\\s\\S]* $)(?!(?:_[Aa][Rr][Cc][Hh][Tt][Ii][Cc][Kk]|_[Oo][Pp][Ee][Nn]|_[Dd][Oo][Tt]|_[Nn][Oo][Nn][Ee])$)[\\u0020-\\u0021\\u0023-\\u0029\\u002b\\u002d-\\u002e\\u0030-\\u0039\\u0040-\\u005b\\u005d\\u005f\\u0061-\\u007b\\u007d-\\u007e\\u00a0-\\u05ff\\u0604-\\u06dc\\u06de-\\u070e\\u0710-\\u17b3\\u17b6-\\u200a\\u2010-\\u2029\\u202f-\\u205f\\u2065-\\u2069\\u2070\\u2072-\\u207e\\u2080-\\u208f\\u2095-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2118\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u2140-\\u2144\\u214a-\\u214d\\u214f-\\u217f\\u2189-\\u2bff\\u2c2f\\u2c5f\\u2c70\\u2c7e-\\u2c7f\\u2ce5-\\u2cff\\u2d26-\\u2d2f\\u2d66-\\u2d6e\\u2d70-\\u2d7f\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf-\\ud7ff\\ue000-\\ue7ff\\ue900-\\ufefe\\uff00-\\ufff8\\ufffc-\\uffff]{1,255}$", + "pattern": "^(?! )(?![\\s\\S]* $)(?!(?:_[Aa][Rr][Cc][Hh][Tt][Ii][Cc][Kk]|_[Oo][Bb][Ll][Ii][Qq][Uu][Ee]|_[Oo][Pp][Ee][Nn]|_[Dd][Oo][Tt]|_[Nn][Oo][Nn][Ee])$)[\\u0020-\\u0021\\u0023-\\u0029\\u002b\\u002d-\\u002e\\u0030-\\u0039\\u0040-\\u005b\\u005d\\u005f\\u0061-\\u007b\\u007d-\\u007e\\u00a0-\\u05ff\\u0604-\\u06dc\\u06de-\\u070e\\u0710-\\u17b3\\u17b6-\\u200a\\u2010-\\u2029\\u202f-\\u205f\\u2065-\\u2069\\u2070\\u2072-\\u207e\\u2080-\\u208f\\u2095-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2118\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u2140-\\u2144\\u214a-\\u214d\\u214f-\\u217f\\u2189-\\u2bff\\u2c2f\\u2c5f\\u2c70\\u2c7e-\\u2c7f\\u2ce5-\\u2cff\\u2d26-\\u2d2f\\u2d66-\\u2d6e\\u2d70-\\u2d7f\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf-\\ud7ff\\ue000-\\ue7ff\\ue900-\\ufefe\\uff00-\\ufff8\\ufffc-\\uffff]{1,255}$", "description": "The xref's name" }, "path": { diff --git a/test/bounded.test.ts b/test/bounded.test.ts index aba3dd8..dca3e0a 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2047,6 +2047,24 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint // A dimension style whose prefix every dimension reads. if (random() < 0.3) (drawing.dimensionStyles as Data[])[0]!.prefix = long; if (random() < 0.2) (drawing.dimensionStyles as Data[])[0]!.arrowhead = "A".repeat(1_000_000); + // Dimensions whose long words below each reads again, short or not, in a style that may move + // a text out on a leader or center it in the line. + if (random() < 0.3) { + const style = (drawing.dimensionStyles as Data[])[0]!; + style.textFit = pick(["inside", "leader"]); + style.textPlacement = pick(["above", "centered"]); + (pick([drawing, layout]).entities as Data[]).push( + ...Array.from({ length: pick([1, 300]) }, (_, i) => ({ + kind: "linear-dimension", + layer: "0", + style: style.name, + from: [0, i], + to: [pick([0.01, 10]), i], + line: [0, i + 1], + textBelow: pick([long, "A\\P".repeat(5_000)]), + })), + ); + } // A leader style whose arrowhead or text style every leader reads. if (random() < 0.2) { const style = (drawing.leaderStyles as Data[])[0]!; diff --git a/test/dimensions.test.ts b/test/dimensions.test.ts index ec36750..406d867 100644 --- a/test/dimensions.test.ts +++ b/test/dimensions.test.ts @@ -13,7 +13,9 @@ import { fromJSON, inspectText, measureText, + readDXF, fromPaper, + layoutDimensionText, idHandle, lint, toDXF, @@ -474,7 +476,7 @@ test("a dimension is checked when it is drawn, and lint finds the same in a draw d.alignedDimension(from, [20, 0], -5, { style: "TICKS", id: "again", text: "<> TYP" }); d.block("B", {}, () => d.line([0, 0], [1, 0])); // @ts-expect-error: the leading CAD app draws the architectural tick with the block of this name. - assert.throws(() => d.block("_archtick", {}, () => {}), /architectural tick/); + assert.throws(() => d.block("_archtick", {}, () => {}), /ticks of a dimension/); }); assert.deepEqual(lint(made), []); assert.deepEqual(lint(fromJSON(toJSON(made))), []); @@ -547,6 +549,72 @@ test("closed arrowheads need room for the widest the text can be, and for the le assert.deepEqual(lint(d.build()), []); }); +test("closed arrowheads need room for the wider text, and a stacked fraction for its longer part", () => { + const d = createDrawing({ units: "in" }); + const stacked = { + textHeight: 3 / 32, + arrowSize: 1 / 8, + extensionOffset: 1 / 16, + extensionBeyond: 1 / 8, + textGap: 1 / 16, + scale: 12, + units: "architectural", + precision: 4, + fraction: "stacked", + } as const; + d.dimensionStyle({ ...stacked, name: "STACKED" }); + d.linearDimension([0, 0], [7.4375, 0], [0, 5], { style: "STACKED" }); + assert.throws( + () => d.linearDimension([0, 10], [6.4375, 10], [0, 15], { style: "STACKED" }), + /its text, "6 7\/16\\"", and its arrowheads may need 6\.45\b/, + ); + assert.throws( + () => + d.linearDimension([0, 20], [7.4375, 20], [0, 25], { style: "STACKED", textBelow: "TO STUD" }), + /its text, "TO STUD"/, + ); + // A text centered in the line breaks it, and needs the arrowheads' room as well as its own. + d.dimensionStyle({ ...stacked, name: "CENTERED", textPlacement: "centered" }); + d.linearDimension([0, 30], [6.5, 30], [0, 35], { style: "STACKED" }); + assert.throws( + () => d.linearDimension([0, 40], [6.5, 40], [0, 45], { style: "CENTERED" }), + /may need 8\.2125\b/, + ); + // A narrow font does not narrow a diagonal stack's gap, so the room is the text as laid out too. + d.textStyle({ name: "NARROW", font: "Courier New", widthFactor: 0.15 }); + d.dimensionStyle({ + ...stacked, + name: "NARROW", + textStyle: "NARROW", + textHeight: 1, + scale: 1, + measurementScale: 0.7, + feetInchZeros: "neither", + fraction: "diagonal", + textPlacement: "centered", + }); + assert.throws( + () => d.linearDimension([0, 50], [1.06, 50], [0, 52], { style: "NARROW" }), + /its text, "3\/4\\"", and its arrowheads may need 1\.065897/, + ); +}); + +test("a dimension's stack is lowered until its bar or its slash's middle is half a height up, never raised", () => { + // As the leading CAD app plots `\\A1;` before a stack: sheet dimension-looks of cad-plots.ts. + const laid = (stack: string, size: number, font: "Arial" | "Times New Roman" = "Arial") => { + const value = `\\A1;4{\\H${size}x;\\S${stack};}`; + const { lines, strokes } = layoutDimensionText({ value, height: 1, font, at: [0, 0] }); + const { from, to } = strokes[0]!; + const { baseline, runs } = lines[0]!; + return { middle: (from[1] + to[1]) / 2 - baseline, below: runs.at(-1)!.baseline - baseline }; + }; + assert.ok(Math.abs(laid("1/2", 1).middle - 0.5) < 1e-9); + assert.ok(Math.abs(laid("1#2", 1).middle - 0.5) < 1e-9); + // A small one whose slash's middle is lower stays on the line (case STACK-100.03125-1-0.5-TR). + assert.ok(laid("1#32", 0.5, "Times New Roman").middle < 0.5); + assert.equal(laid("1#32", 0.5, "Times New Roman").below, 0); +}); + test("every number a dimension draws is under 1e100, and its angle is less than a turn either way", () => { const d = createDrawing({ units: "ft" }); const tick = { ...sizes, arrowhead: "architectural-tick" } as const; @@ -736,6 +804,9 @@ test("a dimension is written with its style, its points and the block of its pic dimensionLine: "14E64A214426A5", arrowheads: ["14D80EF3992A9B", "14DB0EF39935B2"], text: "12C57C2A4861EF", + dimensionLines: ["14E64A214426A5", "1A23E71AA31D32", "1A22E71AA31F7D", "1A25E71AA31254"], + leader: ["1C6E99C485049E", "1C7199C48501B7"], + belowText: "1A5AD40549288F", }); assert.equal(dimensionPictureHandles({ index: 1 }).record, "16DCBD6115A74B"); assert.equal(dimensionPictureHandles({ index: 0, layout: "a-101" }).record, "1D645DAA891E34"); @@ -833,10 +904,12 @@ test("toSVG draws a dimension's lines, arrowheads and text, and the extents take assert.equal(group[1]!.match(/data-part="extension-line"/g)?.length, 2); assert.equal(group[1]!.match(/data-part="dimension-line"/g)?.length, 1); assert.equal(group[1]!.match(/]*data-part="arrowhead"/g)?.length, 2); - // Centered on the middle of the dimension line, one gap above it, as long as it plots. + // The paragraph its block holds, centered on the middle of the dimension line one gap above it: + // an SHX text drawn from where its strokes start, as long as it plots. + assert.match(group[1]!, //); assert.match( group[1]!, - /]*textLength="[^"]+"[^>]*data-part="text">52\.00<\/text>/, + /]*textLength="3\.666667"[^>]*data-part="text">52\.00<\/text>/, ); assert.match(group[1]!, /x1="-1" y1="-10" x2="53" y2="-10"/); // From the end of the dimension line past the first extension line to the top of the text. @@ -893,3 +966,83 @@ test("two text styles lint refuses for their names are still written with a hand assert.ok(handles.length > 10); assert.equal(new Set(handles).size, handles.length); }); + +test("what a style sets of how its dimensions look is checked as literals and when the code runs", () => { + const d = createDrawing({ units: "ft" }); + const style = { name: "S", ...sizes } as const; + const feet = { ...style, units: "architectural", precision: 4 } as const; + // @ts-expect-error: a decimal measurement has no fraction to stack. + assert.throws(() => d.dimensionStyle({ ...style, fraction: "stacked" }), /architectural/); + // @ts-expect-error: and none to size. + assert.throws(() => d.dimensionStyle({ ...style, fractionScale: 0.75 }), /architectural/); + // @ts-expect-error: the leading CAD app stacks across or diagonally, or not at all. + assert.throws(() => d.dimensionStyle({ ...feet, fraction: "tall" }), /fraction must be/); + assert.throws( + () => d.dimensionStyle({ ...feet, fraction: "stacked", fractionScale: 0.1 }), + /0\.25/, + ); + assert.throws(() => d.dimensionStyle({ ...feet, fractionScale: 0.75 }), /sizes a fraction/); + // @ts-expect-error: the text is above the line or centered in it. + assert.throws(() => d.dimensionStyle({ ...style, textPlacement: "below" }), /textPlacement/); + // @ts-expect-error: a short text stays inside or moves out on a leader. + assert.throws(() => d.dimensionStyle({ ...style, textFit: "beside" }), /textFit/); + assert.throws(() => d.dimensionStyle({ ...style, dimensionLineweight: 0.33 }), /lineweight/); + assert.throws( + () => d.dimensionStyle({ ...style, textFit: "leader", textPlacement: "centered" }), + /closed filled arrowheads/, + ); + d.dimensionStyle({ ...feet, fraction: "inline", fractionScale: 1 }); + // A text centered in a line needs its width and two gaps between the extension lines, whatever + // the ticks reach past them. + d.dimensionStyle({ ...style, name: "C", arrowhead: "oblique", textPlacement: "centered" }); + assert.throws( + () => d.linearDimension([0, 0], [6, 0], [0, 2], { style: "C", text: "VERIFY" }), + /centered in its line/, + ); + d.linearDimension([0, 0], [7, 0], [0, 2], { style: "C", text: "VERIFY" }); +}); + +test("a stacked fraction, words below the line and a text moved out are drawn and read back", async () => { + const style = { ...sizes, textHeight: 0.125, arrowSize: 0.125, textGap: 0.0625 } as const; + const feet = { units: "architectural", precision: 4, measurementScale: 12 } as const; + assert.equal( + measurementText(4.119792, { ...feet, fraction: "stacked", fractionScale: 0.75 }), + `4'-1{\\H0.75x;\\S7/16;}"`, + ); + assert.equal( + measurementText(4.119792, { ...feet, fraction: "diagonal" }), + `4'-1{\\H1x;\\S7#16;}"`, + ); + const d = createDrawing({ units: "ft" }); + d.textStyle({ name: "NOTES", font: "Arial" }); + d.dimensionStyle({ + ...style, + name: "S", + textStyle: "NOTES", + arrowhead: "oblique", + textFit: "leader", + }); + d.linearDimension([0, 0], [10, 0], [0, 2], { style: "S", textBelow: "WINDOW HEAD HT." }); + d.linearDimension([0, 5], [0.1, 5], [0, 7], { style: "S", id: "short" }); + const drawing = d.build(); + const [below, short] = drawing.entities.map((e) => + dimensionPicture(e as never, drawing.dimensionStyles![0]!, drawing.textStyles![0]), + ); + // The words stand a gap under the line, and the file holds the line's middle for the text. + assert.equal(below!.below?.label.value, "WINDOW HEAD HT."); + assert.ok(below!.below!.middle[1] < 2 && below!.textMiddle[1] > 2); + assert.deepEqual(below!.textPoint, [5, 2]); + // A text with no room moves out on a leader of two lines from the middle of the dimension line. + assert.equal(short!.leader.length, 2); + assert.deepEqual(short!.leader[0]![0], [0.05, 7]); + const dxf = toDXF(drawing); + assert.ok(dxf.includes("\r\n1\r\n<>\\XWINDOW HEAD HT.\r\n")); + const read = await readDXF(dxf, { geometry: true }); + const [first] = read.model.entities as readonly { + readonly text?: string; + readonly textBelow?: string; + }[]; + assert.deepEqual([first!.text, first!.textBelow], [undefined, "WINDOW HEAD HT."]); + assert.equal(read.dimensionStyles.find((s) => s.name === "S")?.textMove, 1); + assert.equal(read.dimensionStyles.find((s) => s.name === "S")?.arrowheadBlock, "_Oblique"); +}); diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index 48e79c5..b417412 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -64,6 +64,8 @@ test("a paragraph's codes draw what the DXF Reference gives them", () => { strikeThrough: false, bold: false, font: undefined, + size: 1, + align: 0, }; assert.deepEqual(formats, [ ["U", { ...plainFormat, underline: true }], @@ -243,16 +245,16 @@ test("a paragraph is laid out where the leading CAD app sets its lines and runs" [-0.15208, 0.61968, 0.58392, 1.354], ), ); - // A slash stack raises its top part a digit's top, and centers the slash at its bottom part's. + // A slash stack stands its top part on its bottom part's ink, and centers the slash at its top. const slash = layoutParagraph({ value: "\\S1#A;", height: 1, ...arial }); assert.ok( near( slash.lines[0]!.runs.map((run) => run.baseline), - [-1.00409, -2.00819], + [-1.00409, -2.00409], ), ); const [from, to] = [slash.strokes[0]!.from, slash.strokes[0]!.to]; - assert.ok(near([(from[1] + to[1]) / 2], [-1.00819])); + assert.ok(near([(from[1] + to[1]) / 2], [-1.00409])); // An underline lies at the descent of a TrueType font and a fifth of a height in an SHX font. for (const [font, below] of [ ["Arial", -0.29604], diff --git a/test/read-agreement.ts b/test/read-agreement.ts index 06a0f87..4afe2fe 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -367,8 +367,13 @@ export function readProblems( if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { say(`${label}: text ${JSON.stringify(got.text)}`); } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { + say(`${label}: text below ${JSON.stringify(got.textBelow)}`); + } if (!style) return; - const picture = dimensionPicture(want, style); + const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); + const picture = dimensionPicture(want, style, font); // The leading CAD app works the point of the dimension line out again as it draws the // picture, and places the text by its letters, so a read by that // app is held to where the line is. @@ -377,8 +382,8 @@ export function readProblems( `${label}: its line meets the second extension line at ${got.line}, expected ${picture.definitionPoint}`, ); } - if (by === "tsdraft" && !nearPoint(got.textAt, picture.textMiddle)) { - say(`${label}: its text at ${got.textAt}, expected ${picture.textMiddle}`); + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { + say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); } const measurement = dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); diff --git a/test/shape.test.ts b/test/shape.test.ts index e8ff3bd..356431c 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -117,6 +117,7 @@ const kinds: { line: [0, -6], angle: 15, text: "<> TYP", + textBelow: "CLR.", id: "g", }, "aligned-dimension": { @@ -127,6 +128,7 @@ const kinds: { to: [30, 10], offset: 8, text: "VARIES", + textBelow: "<> O.C.", id: "h", }, leader: { @@ -171,7 +173,7 @@ const full: Required & { readonly textStyles: readonly [Required]; // A style in decimal units leaves zeros out, and one in architectural units writes them. readonly dimensionStyles: readonly [ - Required>, + Required>, Required>, ]; readonly leaderStyles: readonly [Required]; @@ -209,6 +211,10 @@ const full: Required & { units: "decimal", suppressZeros: "trailing", measurementScale: 2, + textPlacement: "centered", + textFit: "leader", + dimensionLineweight: 0.5, + extensionLineweight: 0.25, }, { name: "ARCH", @@ -226,6 +232,12 @@ const full: Required & { units: "architectural", feetInchZeros: "both", measurementScale: 12, + fraction: "stacked", + fractionScale: 0.75, + textPlacement: "above", + textFit: "inside", + dimensionLineweight: 0.35, + extensionLineweight: 0.18, }, ], leaderStyles: [ diff --git a/test/standard.test.ts b/test/standard.test.ts index bd9039e..a161724 100644 --- a/test/standard.test.ts +++ b/test/standard.test.ts @@ -341,7 +341,7 @@ test("a child replaces an entry whole under its parent's spelling, and null remo // @ts-expect-error: the removed layer is not in the child's type. void child.layers["C-ROAD-CNTR"]; assert.equal(child.layers["A-WALL"].color, 2); - assert.deepEqual(child.chain, [{ id: "tsdraft", version: "1", hash: BUILT_IN_STANDARD.hash }]); + assert.deepEqual(child.chain, [{ id: "tsdraft", version: "2", hash: BUILT_IN_STANDARD.hash }]); assert.equal(child.title, "acme"); assert.equal(child.minTextHeight, BUILT_IN_STANDARD.minTextHeight); assert.ok( @@ -398,8 +398,8 @@ test("a child replaces an entry whole under its parent's spelling, and null remo `paperUnits: A standard that extends nothing must have the field "paperUnits"`, `minTextHeight: A standard that extends nothing must have the field "minTextHeight"`, ]); - assert.deepEqual(problems({ ...base, id: "tsdraft" }), [ - `extends: The standard "tsdraft" version "1" extends itself`, + assert.deepEqual(problems({ ...base, id: "tsdraft", version: "2" }), [ + `extends: The standard "tsdraft" version "2" extends itself`, ]); assert.match( problems({ ...base, minTextHeight: 0.1 })[0]!, @@ -819,7 +819,7 @@ test("the hash is what the merged document states for a check", () => { const checked = defineStandard(BUILT_IN_DOCUMENT as never); assert.equal(JSON.stringify(checked), JSON.stringify(BUILT_IN_STANDARD)); assert.deepEqual(lint(BUILT_IN_STANDARD.titleBlocks.plain.block!), []); - assert.equal(BUILT_IN_STANDARD.version, "1"); + assert.equal(BUILT_IN_STANDARD.version, "2"); }); test("SHA-256 gives the digests of FIPS 180-4 and of node:crypto", () => { From 29098f65e97009290c57edb1c0d4dbbe744dbe8f Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 19 Nov 2026 20:23:15 -0500 Subject: [PATCH 06/35] Paragraph text: numbered and lettered lists, tab stops and a paragraph's own format Paragraph text lays out numbered and lettered lists, tab stops and a paragraph's own format, as the leading CAD app does. - `list(items, { marks, subMarks, indent })` writes a numbered or lettered list in two levels: each item a paragraph of its own, its mark, a tab and its text, hanging under its mark as CAD programs write a list. `paragraphFormat(properties)` writes a `\p` code: first-line, left and right indents, tab stops, justification (left, centered, right, justified, distributed), room before and after the paragraph, and its own line spacing, by a factor or exactly. - A paragraph's value may hold a tab and `\p` codes, in heights after `x` and in drawing units without, as a firm's drawings hold them. A code sets the paragraph it stands in and each after it until another changes it. - `layoutParagraph` lays them out where the leading CAD app plots them: indents, tab stops from the left of the box and every four heights past the last, the next letter's ink on its stop and the words after it wrapped as a line that starts there, justified and distributed lines grown at their spaces or gaps, each word, space or letter then a run of its own, and the spacing, the room and the box of a paragraph's own. The preview, `toPDF`, `inspectText` and the extents draw and measure them. - `lint` and the builder refuse a `\p` option they do not know, a tab stop that aligns by its right, its center or a decimal point, and spacing at least a size, `sa`; a literal value with one is a compile error. - Both writers write a tab, as `^I` in DXF, and `readDXF` reads it back. `ParagraphPiece` gains a `properties` piece, which `ParagraphProperties` describes. - The example sheet's general notes are one numbered list. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 17 +- GUIDE.md | 15 +- README.md | 27 +- docs/assets/site-plan-dark.svg | 140 +++--- docs/assets/site-plan-light.svg | 140 +++--- docs/paragraphs.md | 98 +++- examples/site-plan.ts | 26 +- src/dxf-r2018.ts | 4 +- src/index.ts | 6 + src/paragraph-codes.ts | 302 +++++++++++- src/paragraphs.ts | 849 ++++++++++++++++++++++++++------ src/pdf.ts | 12 +- src/rules.ts | 136 ++++- src/svg.ts | 3 +- test/bounded.test.ts | 10 + test/paragraphs.test.ts | 104 +++- test/rules.test.ts | 11 +- 17 files changed, 1488 insertions(+), 412 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 901e261..ad62c7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,22 @@ it, from the font tables' new column `stackTops`: a 7 over a 16 stands lower than a capital. A slash stack stands its top part on its bottom part's ink, and its gap is not widened with the letters. Every other number of the tables is as it was. - +- Lists, tab stops and a paragraph's own format in paragraph text. `list(items, options)` writes a + numbered or lettered list in two levels, each item hanging under its mark as CAD programs write + one, and `paragraphFormat(properties)` a `\p` code: a paragraph's first-line, left and right + indents, tab stops, justification left, centered, right, justified or distributed, room before + and after it, and its own line spacing, by a factor or exactly. A value may hold a tab and + `\p` codes, in heights after `x` and in drawing units without, as a firm's drawing holds them; + a code sets the paragraph it stands in and each after it until another changes it. + `layoutParagraph` lays them out as the leading CAD app does: indents, tab stops from the left + of the box and every four heights past the last, the next letter's ink on its stop and the words + after it wrapped as a line that starts there, justified lines grown at each space and + distributed ones at each gap, each word and space or letter then a run of its own, and the + spacing, the room and the box of a paragraph's own. `lint` and the builder refuse a `\p` option they do not + know, a tab stop that aligns by its right, its center or a decimal point, and spacing at least + a size, `sa`, as the type of a literal value does. Both writers write a tab, as `^I` in DXF, + and `readDXF` reads it back. `ParagraphPiece` gains a `properties` piece, which + `ParagraphProperties` describes. The example sheet's general notes are one numbered list. - `readDXF` leaves out of a block's and a space's `entities` an entity the file marks invisible, group 60, and counts it under `other` as `invisible`. A dynamic block's definition and each `*U` block that holds one of its states keep the entities of every state, with those of the states diff --git a/GUIDE.md b/GUIDE.md index ea9f3e5..26a396c 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -230,21 +230,24 @@ A note of more than one line is a paragraph, which wraps at its width and which as one. Never break a note into texts of one line: ```ts -import { layoutParagraph, underline } from "tsdraft"; +import { layoutParagraph, list, underline } from "tsdraft"; -d.paragraph(`1. ${underline("VERIFY")} ALL DIMENSIONS IN THE FIELD.\n2. DO NOT SCALE.`, { +const notes = list([`${underline("VERIFY")} ALL DIMENSIONS IN THE FIELD.`, "DO NOT SCALE."]); +d.paragraph(notes, { at: [1, 20], // the upper left corner of its box width: 4, height: 0.1, }); -layoutParagraph({ value: "...", height: 0.1, width: 4 }).lines.length; // how many lines it takes +layoutParagraph({ value: notes, height: 0.1, width: 4 }).lines.length; // how many lines it takes ``` -A line feed starts a new paragraph. `measureParagraph` gives its lines and its box, from the +A line feed starts a new paragraph. `list` writes numbered or lettered notes in two levels, each +hanging under its mark as CAD programs set a list, and `paragraphFormat` a paragraph's indents, +tab stops, justification and spacing. `measureParagraph` gives its lines and its box, from the widths `measureText` uses, and `inspectText` checks each line as a text. `underline`, `bold`, `stack`, `superscript` and `subscript` write the codes for what they name, and `plain(text)` -escapes text from elsewhere. `lint` refuses a code tsdraft does not lay out, such as a tab, a -list's indents or a change of height, and names it. +escapes text from elsewhere. `lint` refuses a code tsdraft does not lay out, such as columns or +a change of height, and names it. [docs/paragraphs.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/paragraphs.md) has the codes. diff --git a/README.md b/README.md index a321849..69b64aa 100644 --- a/README.md +++ b/README.md @@ -158,17 +158,20 @@ d.donut([10, 10], 0.5); // a filled dot [Polylines](docs/polylines.md) has the rest. A paragraph is one text whose lines wrap at a width, which a CAD user edits as one. A line feed -starts a new paragraph, and small helpers write the codes for an underline, bold, a stacked -fraction and a superscript: +starts a new paragraph, and small helpers write the codes for a numbered list, an underline, +bold, a stacked fraction and a superscript: ```ts -import { stack, underline } from "tsdraft"; - -d.paragraph(`GENERAL NOTES\n1. ${underline("VERIFY")} ALL DIMENSIONS. GAP 3${stack("1", "2")}"`, { - at: [1, 20], // the upper left corner of its box - width: 4, - height: 0.1, -}); +import { list, stack, underline } from "tsdraft"; + +d.paragraph( + `GENERAL NOTES\n${list([`${underline("VERIFY")} ALL DIMENSIONS.`, `GAP 3${stack("1", "2")}"`])}`, + { + at: [1, 20], // the upper left corner of its box + width: 4, + height: 0.1, + }, +); ``` `measureParagraph` gives its lines and its box. [Paragraphs](docs/paragraphs.md) has the codes @@ -243,14 +246,14 @@ included, can break code written for the one before. [CHANGELOG.md](CHANGELOG.md starts each breaking change with `Breaking:`. It draws layers, lines, polylines with arcs and widths, rectangles, revision clouds, donuts, -circles, arcs, single-line text and paragraph text that wraps to a width, with -linetypes and lineweights, text styles and justification, blocks with attributes and inserts +circles, arcs, single-line text and paragraph text that wraps to a width, with lists and tab +stops, linetypes and lineweights, text styles and justification, blocks with attributes and inserts of them, references to DWG files as xrefs, linear and aligned dimensions in decimal units or feet and inches with stacked fractions, words below the line and text on a leader, leaders, layouts with a page setup and viewports, which can freeze their own layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have lists, tab stops, columns or overlines in paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one +It does not yet have columns or overlines in paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index d592f7f..c992dc0 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -298,89 +298,71 @@ 61.0' GENERAL NOTES - 1. - - PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD - SURVEY WAS MADE FOR THIS PLAN. + + 1. + PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD + SURVEY WAS MADE FOR THIS PLAN. + 2. + DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE + FOUNDATION WALL. + 3. + SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY + LINE TO THE NEAREST WALL. + 4. + THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. + 5. + LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. + 6. + GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE + STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. + 7. + PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL + THE LOT IS STABILIZED. + 8. + PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. + 9. + WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. + 10. + REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING + CONSTRUCTION. - 2. - - DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE - FOUNDATION WALL. - - 3. - - SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY LINE - TO THE NEAREST WALL. - - 4. - - THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. - - 5. - - LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. - - 6. - - GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE - STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. - - 7. - - PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL - THE LOT IS STABILIZED. - - 8. - - PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. - - 9. - - WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. - - 10. - - REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING - CONSTRUCTION. - - LEGEND - - - PROPERTY LINE - - ADJOINING LOT LINE - - BUILDING SETBACK LINE - - BUILDING FOOTPRINT - - EDGE OF PAVEMENT OR CONCRETE - - STREET CENTERLINE + LEGEND + + + PROPERTY LINE + + ADJOINING LOT LINE + + BUILDING SETBACK LINE + + BUILDING FOOTPRINT + + EDGE OF PAVEMENT OR CONCRETE + + STREET CENTERLINE - + - PROPERTY CORNER + PROPERTY CORNER - - - + + + - EXISTING TREE TO REMAIN - ABBREVIATIONS - - AC - ACRES - CONC. - CONCRETE - ELEV. - ELEVATION - F.F.E. - FINISHED FLOOR ELEVATION - MAX. - MAXIMUM - SF - SQUARE FEET + EXISTING TREE TO REMAIN + ABBREVIATIONS + + AC + ACRES + CONC. + CONCRETE + ELEV. + ELEVATION + F.F.E. + FINISHED FLOOR ELEVATION + MAX. + MAXIMUM + SF + SQUARE FEET diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index 5126fcb..2097b78 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -298,89 +298,71 @@ 61.0' GENERAL NOTES - 1. - - PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD - SURVEY WAS MADE FOR THIS PLAN. + + 1. + PROPERTY LINES ARE DRAWN FROM THE RECORDED PLAT. NO FIELD + SURVEY WAS MADE FOR THIS PLAN. + 2. + DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE + FOUNDATION WALL. + 3. + SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY + LINE TO THE NEAREST WALL. + 4. + THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. + 5. + LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. + 6. + GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE + STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. + 7. + PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL + THE LOT IS STABILIZED. + 8. + PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. + 9. + WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. + 10. + REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING + CONSTRUCTION. - 2. - - DIMENSIONS ARE IN FEET, MEASURED TO THE OUTSIDE FACE OF THE - FOUNDATION WALL. - - 3. - - SETBACKS ARE MEASURED AT RIGHT ANGLES FROM THE PROPERTY LINE - TO THE NEAREST WALL. - - 4. - - THE FINISHED FLOOR ELEVATION IS ON AN ASSUMED DATUM. - - 5. - - LOCATE ALL UNDERGROUND UTILITIES BEFORE DIGGING. - - 6. - - GRADE THE LOT TO DRAIN AWAY FROM THE BUILDING AND TOWARD THE - STREET. KEEP RUNOFF OFF THE ADJOINING LOTS. - - 7. - - PUT EROSION CONTROL IN PLACE BEFORE CLEARING, AND KEEP IT UNTIL - THE LOT IS STABILIZED. - - 8. - - PROTECT THE EXISTING TREES SHOWN. NO TREE IS TO BE REMOVED. - - 9. - - WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT. - - 10. - - REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING - CONSTRUCTION. - - LEGEND - - - PROPERTY LINE - - ADJOINING LOT LINE - - BUILDING SETBACK LINE - - BUILDING FOOTPRINT - - EDGE OF PAVEMENT OR CONCRETE - - STREET CENTERLINE + LEGEND + + + PROPERTY LINE + + ADJOINING LOT LINE + + BUILDING SETBACK LINE + + BUILDING FOOTPRINT + + EDGE OF PAVEMENT OR CONCRETE + + STREET CENTERLINE - + - PROPERTY CORNER + PROPERTY CORNER - - - + + + - EXISTING TREE TO REMAIN - ABBREVIATIONS - - AC - ACRES - CONC. - CONCRETE - ELEV. - ELEVATION - F.F.E. - FINISHED FLOOR ELEVATION - MAX. - MAXIMUM - SF - SQUARE FEET + EXISTING TREE TO REMAIN + ABBREVIATIONS + + AC + ACRES + CONC. + CONCRETE + ELEV. + ELEVATION + F.F.E. + FINISHED FLOOR ELEVATION + MAX. + MAXIMUM + SF + SQUARE FEET diff --git a/docs/paragraphs.md b/docs/paragraphs.md index 4519422..cbc779f 100644 --- a/docs/paragraphs.md +++ b/docs/paragraphs.md @@ -61,6 +61,8 @@ these: | `\S2^ ;` and `\S^2;` | A superscript and a subscript | | `%%d`, `%%p`, `%%c` | A degree sign, a plus-or-minus sign and a diameter sign | | `\U+XXXX` | The character of that code point | +| A tab | A move to the next tab stop | +| `\pxi-3,l3,t3;` | The indents, tab stops, justification, room and spacing of the paragraph | `%%` before any other character draws as it is: `100%%%` draws three percent signs, and `%%%d` a percent sign and a degree sign. @@ -72,7 +74,7 @@ a subscript does. Its parts are as tall as the text around them. Helpers write the codes, so a value reads as what it draws: ```ts -import { bold, plain, stack, subscript, superscript, underline } from "tsdraft"; +import { bold, list, plain, stack, subscript, superscript, underline } from "tsdraft"; d.paragraph( `${bold("GENERAL NOTES", "Arial")} @@ -89,10 +91,41 @@ d.paragraph( - `stack(top, bottom, divider)` stacks two parts: over a level bar for `"/"`, the default, beside a slash for `"#"`, and with no bar for `"^"`. - `superscript(text)` and `subscript(text)` set a part above the line, and at its foot. +- `list(items, { marks, subMarks, indent })` writes a numbered or lettered list in two levels, as + CAD programs write one: each item a paragraph of its own, its mark, a tab and its text, under a + hanging indent of `indent` heights, 3 by default. An item is a string, or `{ text, items }` with + the items of the level under it, indented as far again. `marks` is `"1."`, the default, `"1)"`, + `"A."` or `"a."`, and `subMarks` `"A."` by default. The items are joined by `\P`. +- `paragraphFormat(properties)` writes a `\p` code that sets what it gives, in heights: `indent`, + the first line's indent from the left indent; `left` and `right`, the indents; `tabs`, the tab + stops from the left of the box, and `[]` for none; `justification`, `"left"`, `"center"`, + `"right"`, `"justified"` or `"distributed"`; `before` and `after`, the room before and after the + paragraph; and `spacing`, `{ style: "m", value }` for a factor of the paragraph's own spacing or + `{ style: "e", value }` for its lines exactly that far apart. - `plain(text)` escapes what would start a code: a backslash, a brace, and the second percent sign of `%%d`, `%%p` and `%%c`, written as `\U+0025`, so a value that comes from elsewhere draws as it is. +A `\p` code sets what it gives of the paragraph it stands in, wherever in it, and of every +paragraph after it until another code changes it. So the text after a list keeps the list's +indents and tab stops; start it with `paragraphFormat({ indent: 0, left: 0, tabs: [] })`: + +```ts +d.paragraph( + `GENERAL NOTES\\P${list([ + "VERIFY ALL DIMENSIONS IN THE FIELD.", + { + text: "DO NOT SCALE THE DRAWINGS.", + items: ["USE THE DIMENSIONS SHOWN.", "ASK THE ENGINEER."], + }, + ])}\\P${paragraphFormat({ indent: 0, left: 0, tabs: [] })}END OF NOTES`, + { at: [1, 20], width: 4, height: 0.1 }, +); +``` + +With `x`, as the helpers write it, a `\p` code's numbers are in heights of the text; without it, +in drawing units, as a firm's drawing may hold them. + ## What `lint` refuses `lint` refuses a value it cannot lay out as the leading CAD app does, and the builder refuses the @@ -111,12 +144,14 @@ message names the code. keeps it. The type of a literal value refuses it in a font a `\f` or `\F` code sets, as far as that code's group reaches; in the style's font only `lint` and the builder refuse it, since the type does not know the style's font. A read `MTEXT` that holds one is laid out as approximate. -- A control character, a tab among them, a character above U+FFFF and the private-use characters +- A control character but a tab, a character above U+FFFF and the private-use characters U+E800 to U+E8FF, which a text cannot hold either. The type of a literal value refuses all but a character above U+FFFF, which only `lint` and the builder refuse: TypeScript reads a template literal type by characters and never splits the two halves of one, so no type can find it. -- The codes tsdraft does not lay out yet: `\p`, a paragraph's indents, tab stops and alignment, - which numbered and lettered lists are made of; `\N`, columns; `\H` the height, `\W` the width +- In `\p`, an option it does not know, a tab stop that aligns text by its right, its center or a + decimal point, `tr`, `tc` and `td`, and spacing at least a size, `sa`, which tsdraft does not + lay out. +- The codes tsdraft does not lay out yet: `\N`, columns; `\H` the height, `\W` the width factor, `\Q` the oblique angle, `\T` the spacing and `\A` the alignment of the characters after it; `\C` and `\c` color; `\O`, an overline, which sits at a TrueType font's ascent, which tsdraft's tables do not hold; `\X`, which only a dimension's text holds; and `\M+NXXXX`, a @@ -163,11 +198,29 @@ from the widths and the ink of each character that `FONT_METRICS` holds: - A line starts at the left of its first character's ink and ends at the right of its last one's. It keeps the spaces it starts with and drops those it ends with. `"left"` puts that start on `at`, `"right"` that end, and `"center"` the middle of the two: the width moves no line. -- A line breaks only at a space, and only to keep the next word inside the width: the word stays - when the advances up to it, from the line's first point, and its own ink come to no more than - the width. The left of the line's first letter has no part in it. A word wider than the width - stays whole and passes it. In a word that holds a stack, what follows the last stack stands - for the word, or the stack where it ends the word. +- A line breaks only at a space or before a tab, and only to keep the next word inside the + width: the word stays when the advances up to it, from the line's first point, and its own ink + come to no more than the width. The left of the line's first letter has no part in it. A word + wider than the width stays whole and passes it. In a word that holds a stack, what follows the + last stack stands for the word, or the stack where it ends the word. A tab goes with the word + after it where the line wraps. +- With a width, a paragraph's first line starts at its left indent plus its first-line indent, + never left of the box, its other lines at its left indent, and its words wrap at its right + indent. A word that reaches the width itself leaves a line that starts at an indent or holds a + tab. Without a width, no indent moves a line. +- A tab moves the pen to a stop, measured from the left of the box: of the left indent and the + paragraph's stops, the first that leaves the next letter's first point past the pen, and then + the next multiple of `4h`. A stop at or past the right indent moves it nowhere. The next letter's + ink starts on the stop. Without a width only the left indent and the multiples of `4h` are stops, + counted from the line's first letter, and a tab before that letter moves nothing. After a tab, + the wrap measures the words as a line that starts on the stop. +- `"left"`, `"center"` and `"right"`, from `align` or from the paragraph's justification, set a + line flush left at its start, centered between its start and the right indent, or flush right + at the right indent, and without a width about `at`. A justified line grows each space after + its last tab alike to end at the right indent, but a paragraph's last line, which stands by + `align`. A distributed line grows each gap between two letters or stacks after its last tab + alike, every line, and stands centered without a width. A grown line draws each word and space, + or each letter, as a run of its own. - With `"at-least"` spacing, each line takes `lineSpacing` times its ascent, a third of the height of what reaches highest, and `h/3`. Its ascent is how far its letters reach above the baseline, at least `h`, as an `Å` or a stack reaches further: a plain line takes `5h/3`. The first line's @@ -175,12 +228,20 @@ from the widths and the ink of each character that `FONT_METRICS` holds: - With `"exactly"`, the first baseline is `h` below the top of the box and each next one `lineSpacing` times `5h/3` below it, whatever the lines hold, and the box ends `h/3` below the last. +- A paragraph's own spacing takes the place of both. A factor `f` gives each line `f` times `5/4` + of its ascent and the third of a height below it, `5h/3` for a line of capitals, and the box + ends no further below the last line's top than that. Exactly `v` sets each baseline `v` below + its line's top and the next line `5v/3` below, and the box ends `2v/3` below the last baseline, + less `4/3` of what `v` passes `h` by. +- The room before a paragraph comes before its first line, the first paragraph's too, and is a + quarter of a height at least; the room after one comes before the next. Once a `\p` code has + `x`, the numbers of each code after it are in heights too. - The style's width factor scales everything along a line. In a TrueType font its oblique angle moves where a line starts by its first letter's bottom, and where it ends by its ascent, times the angle's tangent. -- An underline runs from a run's first character to the end of its last one's advance, at the - font's descent in a TrueType font and `h/5` below the baseline in an SHX font. A - strike-through runs `h/2` above it. +- An underline runs from a run's first character to the end of its last one's advance, and + through a tab from the pen to the stop, at the font's descent in a TrueType font and `h/5` below + the baseline in an SHX font. A strike-through runs `h/2` above it. - A bold run is in its font's bold face, with that face's own widths and ink. - A fraction's top part has its ink's top at the top of the stack and its baseline `h/6` above a bar as long as the wider part's ink, and the bottom part its ink `h/6` below the bar and its @@ -191,8 +252,11 @@ from the widths and the ink of each character that `FONT_METRICS` holds: `approximate` is true where tsdraft's numbers are an estimate: a value with a code it does not lay out or a character outside its tables, a font that is not one of `FONTS`, an oblique angle in -an SHX font, `%%c` in an SHX font, which draws a diameter sign of its own, and a stack in a -TrueType font other than Arial, whose digits and capitals may stand lower than its `A`. +an SHX font, `%%c` in an SHX font, which draws a diameter sign of its own, a stack in a +TrueType font other than Arial, whose digits and capitals may stand lower than its `A`, a +negative indent or room, a `\p` number past `1e15` drawing units, which is held there, tab stops +given out of order, a paragraph's own spacing by a factor outside 0.25 to 4 or exactly 0 or +less, and a justified or distributed line in an SHX font. `inspectText` checks each line of a paragraph as it checks a text: one that plots over another text, runs past the outline it starts in, or off the paper. @@ -221,6 +285,6 @@ when the font is not the style's own or the value holds a code tsdraft does not ## Not yet -Numbered and lettered lists with hanging indents, tab stops, columns, the codes that change the -height, width, slant, spacing, alignment or color of the characters after them, an overline, -stacked parts in lower case, and attributes of more than one line. +Columns, the codes that change the height, width, slant, spacing, alignment or color of the +characters after them, an overline, stacked parts in lower case, tab stops that align text by its +right, its center or a decimal point, and attributes of more than one line. diff --git a/examples/site-plan.ts b/examples/site-plan.ts index 4b47864..1172d3b 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -55,9 +55,9 @@ // justified to its point with `align` and `valign`. Columns are laid out by the length // `measureText` gives a text in its role. The title block's texts, below, are the one // exception. -// - A general note is one paragraph, which wraps at the width of the column of notes and which a -// drafter edits as one. `layoutParagraph` gives its lines, so its first line sits on its -// number's row and the next note starts under its last line. +// - The general notes are one paragraph, a numbered list whose items hang under their numbers and +// wrap at the width of the column of notes, which a drafter edits as one. `layoutParagraph` +// gives its lines, so its first line sits on the row and the next block starts under its last. // - A symbol is a block, drawn once and inserted where it is needed. The tree and the property // corner are in the plan and in the legend, so each is inserted in model space and on the // layout. A block's entities are on layer 0, so each insert draws on its own layer. @@ -84,7 +84,9 @@ import { createDrawing, defineStandard, layoutParagraph, + list, measureText, + paragraphFormat, toDXF, toSVG, type Drawing, @@ -727,17 +729,13 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee "WORK IN THE PUBLIC RIGHT-OF-WAY NEEDS ITS OWN PERMIT.", "REPLACE ANY SIDEWALK OR PAVEMENT DAMAGED DURING CONSTRUCTION.", ]; - const indent = widthOf("00. ", "label"); - const width = column.width - indent; - notes.forEach((note, i) => { - d.text([column.left, row], `${i + 1}.`, { role: "label" }); - // The note's first baseline is on its number's row, and the next note starts a line and a - // third below its last. - const { lines } = layoutParagraph({ value: note, ...roles.label, width }); - const [first, last] = [lines[0]!.baseline, lines.at(-1)!.baseline]; - d.paragraph(note, { role: "label", at: [column.left + indent, row - first], width }); - row += last - first - leading - leading / 3; - }); + // One paragraph, a numbered list whose items hang under their numbers, a third of a line + // apart. Its first baseline is on the row, and the next block starts under its last. + const value = `${paragraphFormat({ after: 1 / 3 })}${list(notes)}`; + const { lines } = layoutParagraph({ value, ...roles.label, width: column.width }); + const [first, last] = [lines[0]!.baseline, lines.at(-1)!.baseline]; + d.paragraph(value, { role: "label", at: [column.left, row - first], width: column.width }); + row += last - first - leading; }); // The legend shows each line of the plan on its own layer, and each symbol as the block diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index e1ef171..5550f78 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -1281,10 +1281,10 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi /** * Writes the value of an MTEXT, which the leading CAD app decodes once: in groups 3 of - * `TEXT_CHUNK` characters, and the rest in group 1. + * `TEXT_CHUNK` characters, and the rest in group 1, with a tab as `^I`. */ function writeMtextValue(g: Group, value: string): void { - const text = dxfOnce(value); + const text = dxfOnce(value).replaceAll("\t", "^I"); let at = 0; while (text.length - at > TEXT_CHUNK) { // A caret and what it escapes stay in one group. diff --git a/src/index.ts b/src/index.ts index 8513e1e..176c23b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -160,6 +160,8 @@ export { CENTER, DASHDOT, DASHED, DOT, HIDDEN, LINEWEIGHTS, PHANTOM } from "./li export { lineSpacing, measureText, type TextMeasure, type TextToMeasure } from "./measure.ts"; export { bold, + list, + paragraphFormat, parseParagraph, plain, PARAGRAPH_NESTING, @@ -168,7 +170,11 @@ export { superscript, underline, type BoldFont, + type ListItem, + type ListMarks, + type ParagraphJustification, type ParagraphPiece, + type ParagraphProperties, type ParsedParagraph, type RunFormat, } from "./paragraph-codes.ts"; diff --git a/src/paragraph-codes.ts b/src/paragraph-codes.ts index 38bebe8..e7254cd 100644 --- a/src/paragraph-codes.ts +++ b/src/paragraph-codes.ts @@ -10,7 +10,7 @@ export const PARAGRAPH_NESTING = 16; const QUOTED = 64; export const PARAGRAPH_CONTROL = - "A paragraph's value holds no control characters. paragraph() takes a line feed as a paragraph break and holds it as \\P, and tabs are not laid out yet"; + "A paragraph's value holds no control characters but a tab, written as itself. paragraph() takes a line feed as a paragraph break and holds it as \\P"; export const PARAGRAPH_ASTRAL = "A paragraph cannot hold emoji or other characters above U+FFFF, because the leading CAD app cannot read them from DXF"; export const PARAGRAPH_PRIVATE_USE = @@ -32,7 +32,6 @@ export const PARAGRAPH_STACK_PART = /** What each code a paragraph may hold but tsdraft does not lay out yet does. */ export const PARAGRAPH_NOT_LAID_OUT = { - p: "sets the indents, tab stops and alignment of a paragraph", H: "sets the height of the characters after it", W: "sets the width factor of the characters after it", Q: "sets the oblique angle of the characters after it", @@ -55,6 +54,18 @@ export function paragraphNotLaidOut( return `The paragraph code \\${code}, which ${PARAGRAPH_NOT_LAID_OUT[code]}, is not laid out yet, so tsdraft refuses it`; } +export function paragraphPropertyUnknown( + option: O, +): `The paragraph code \\p has the option "${O}", which tsdraft does not know: it takes i, l, r, b and a with a number, t with numbers or z, q with l, c, r, j or d, and s with m or e and a number` { + return `The paragraph code \\p has the option "${quoted(option) as O}", which tsdraft does not know: it takes i, l, r, b and a with a number, t with numbers or z, q with l, c, r, j or d, and s with m or e and a number`; +} + +export const PARAGRAPH_SPACING_AT_LEAST = + "The paragraph code \\p sets its lines at least a size apart, sa, which is not laid out yet, so tsdraft refuses it. Give sm and a factor, or se and the size exactly"; + +export const PARAGRAPH_TAB_KIND = + "The paragraph code \\p sets a tab stop that aligns text by its right, its center or a decimal point, which is not laid out yet, so tsdraft refuses it. Give the stop as a number alone"; + export function paragraphUnknownCode( code: C, ): `The paragraph code \\${C} is not one tsdraft knows. Write \\\\ for a backslash` { @@ -120,8 +131,37 @@ export interface RunFormat { readonly align: 0 | 1 | 2; } +/** How a paragraph's lines stand across its box, as a `\pq` code sets it. */ +export type ParagraphJustification = "left" | "center" | "right" | "justified" | "distributed"; + +/** + * What a `\p` code sets of the paragraph it is in, each number in heights of the paragraph's + * text. What it leaves out stays as it was. + */ +export interface ParagraphProperties { + /** `i`: where the first line starts, from `left`. */ + readonly indent?: number; + /** `l`: where every line but the first starts, from the left of the box. */ + readonly left?: number; + /** `r`: how far short of the right of the box the lines stop. */ + readonly right?: number; + /** `t`: where each tab stops, from the left of the box, as given; `tz` gives none. */ + readonly tabs?: readonly number[]; + /** `q`. */ + readonly justification?: ParagraphJustification; + /** `b` and `a`: the room before and after the paragraph. */ + readonly before?: number; + readonly after?: number; + /** `s`: the spacing of its lines, `m` a factor of the paragraph's own and `e` exactly. */ + readonly spacing?: { readonly style: "m" | "e"; readonly value: number }; + /** True for `x`: the numbers are in heights of the text, and otherwise in drawing units. */ + readonly heights?: boolean; +} + /** A piece of a paragraph, in the order it is drawn. */ export type ParagraphPiece = + /** What a `\p` code sets, where it stands. */ + | { readonly kind: "properties"; readonly properties: ParagraphProperties } /** * Characters drawn in one format, with no break among them. `diameter` is true when they hold * a diameter sign written `%%c`, which an SHX font draws as a sign of its own. @@ -193,7 +233,7 @@ const TOGGLES: Readonly> = { }; /** The codes tsdraft does not lay out that end with a `;`. */ -const ENDED = new Set(["p", "H", "W", "Q", "T", "A", "C", "c"]); +const ENDED = new Set(["H", "W", "Q", "T", "A", "C", "c"]); function isHex(code: number): boolean { return (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102); @@ -206,9 +246,12 @@ function hexAt(value: string, at: number): number { return parseInt(value.slice(at, at + 4), 16); } +/** A tab, which a paragraph's characters may hold, and a stacked part may not. */ +const TAB = 9; + /** What is wrong with a character a paragraph holds, or undefined. */ -function characterProblem(code: number): string | undefined { - if (code < 0x20 || code === 0x7f) return PARAGRAPH_CONTROL; +function characterProblem(code: number, tab = false): string | undefined { + if ((code < 0x20 && !(tab && code === TAB)) || code === 0x7f) return PARAGRAPH_CONTROL; if (code >= 0xd800 && code <= 0xdfff) return PARAGRAPH_ASTRAL; if (code >= 0xe800 && code <= 0xe8ff) return PARAGRAPH_PRIVATE_USE; return undefined; @@ -293,7 +336,7 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap continue; } } - const wrong = characterProblem(c); + const wrong = characterProblem(c, true); if (wrong) fail(wrong); // A pair of surrogates is one character above U+FFFF. const pair = @@ -301,8 +344,8 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap c <= 0xdbff && value.charCodeAt(i + 1) >= 0xdc00 && value.charCodeAt(i + 1) <= 0xdfff; - // A control character draws nothing. - if (!(c < 0x20 || c === 0x7f)) run += pair ? value.slice(i, i + 2) : character; + // A control character but a tab draws nothing. + if (!((c < 0x20 && c !== TAB) || c === 0x7f)) run += pair ? value.slice(i, i + 2) : character; i += pair ? 2 : 1; } flush(); @@ -338,6 +381,18 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap case "f": case "F": return font(letter, at + 1); + case "p": { + const end = value.indexOf(";", at + 1); + if (end < 0) { + fail(paragraphNoSemicolon(letter)); + return n; + } + const read = readProperties(value.slice(at + 1, end)); + if (read.problem) fail(read.problem); + flush(); + pieces.push({ kind: "properties", properties: read.properties }); + return end + 1; + } case "S": return stack(at + 1); case "U": @@ -447,7 +502,8 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap taken = PERCENT_CODES[value[k + 2]!]!; k += 3; } else k++; - const wrong = characterProblem(taken.charCodeAt(0)); + // A tab is a character a stacked part may not hold, which `stackable` refuses. + const wrong = characterProblem(taken.charCodeAt(0), true); if (wrong) fail(wrong); if (separator === undefined) top += taken; else bottom += taken; @@ -469,6 +525,135 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap } } +/** The justification each letter of a `\pq` code names. */ +const JUSTIFICATIONS: Readonly> = { + l: "left", + c: "center", + r: "right", + j: "justified", + d: "distributed", +}; + +/** A number of a `\p` code: a sign, then digits with a point among them or before them. */ +const PROPERTY_NUMBER = /-?(?:\d+(?:\.\d*)?|\.\d+)/y; + +/** + * Reads what a `\p` code sets, from the text between `\p` and its `;`: an `x` first, then + * options one after another, a comma between them or not. Each takes a letter and what follows + * it: `i`, `l`, `r`, `b` and `a` a number, `q` one of `l`, `c`, `r`, `j` and `d`, `s` one of + * `m`, `e` and `a` and a number, and `t` `z` or numbers with a comma between each. It reads in + * one pass and never throws. + */ +export function readProperties(body: string): { + readonly properties: ParagraphProperties; + readonly problem: string | undefined; +} { + const out: { -readonly [K in keyof ParagraphProperties]: ParagraphProperties[K] } = {}; + let problem: string | undefined; + const n = body.length; + let k = 0; + if (body.startsWith("x")) { + out.heights = true; + k = 1; + } + const number = (): number | undefined => { + PROPERTY_NUMBER.lastIndex = k; + const found = PROPERTY_NUMBER.exec(body); + if (!found) return undefined; + k += found[0].length; + const read = Number(found[0]); + return Number.isFinite(read) ? read : undefined; + }; + while (k < n && problem === undefined) { + const from = k; + const letter = body[k++]!; + if (letter === ",") continue; + let ok = true; + switch (letter) { + case "i": + case "l": + case "r": + case "b": + case "a": { + const read = number(); + if (read === undefined) ok = false; + else { + const field = ({ i: "indent", l: "left", r: "right", b: "before", a: "after" } as const)[ + letter + ]; + out[field] = read; + } + break; + } + case "q": { + const justification = JUSTIFICATIONS[body[k] ?? ""]; + if (justification === undefined) ok = false; + else { + out.justification = justification; + k++; + } + break; + } + case "s": { + const style = body[k]; + if (style === "a") { + problem = PARAGRAPH_SPACING_AT_LEAST; + break; + } + if (style !== "m" && style !== "e") { + ok = false; + break; + } + k++; + const read = number(); + if (read === undefined) ok = false; + else out.spacing = { style, value: read }; + break; + } + case "t": { + if (body[k] === "z") { + k++; + out.tabs = []; + break; + } + if (body[k] === "r" || body[k] === "c" || body[k] === "d") { + problem = PARAGRAPH_TAB_KIND; + break; + } + const tabs: number[] = []; + let read = number(); + if (read === undefined) { + ok = false; + break; + } + tabs.push(read); + // A comma before a number gives another stop; before a letter, another option. + while (body[k] === ",") { + const next = body[k + 1] ?? ""; + if (next === "r" || next === "c" || next === "d") { + problem = PARAGRAPH_TAB_KIND; + break; + } + if (!/[-.0-9]/.test(next)) break; + k++; + read = number(); + if (read === undefined) { + ok = false; + break; + } + tabs.push(read); + } + out.tabs = tabs; + break; + } + default: + ok = false; + } + if (!ok) problem = paragraphPropertyUnknown(body.slice(from, from + 2)); + } + return { properties: out, problem }; +} + /** * True for a part of a stack whose ink's top and bottom the font tables hold: digits or capitals, * which reach a capital's height and stand on the baseline, with `.`, `,`, `+` or `-` beside @@ -561,3 +746,102 @@ export function superscript(text: string): string { export function subscript(text: string): string { return `\\S^${part(text)};`; } + +/** A number of a `\p` code as its grammar reads it: up to 6 decimals, never with an exponent. */ +function propertyNumber(value: number): string { + if (!Number.isFinite(value) || Math.abs(value) >= 1e15) { + throw new RangeError(`A paragraph's format takes numbers below 1e15, not ${value}`); + } + const rounded = Math.round(value * 1e6) / 1e6; + return rounded === 0 ? "0" : String(rounded); +} + +/** The letter `q` takes for each justification. */ +const JUSTIFICATION_LETTERS: Readonly> = { + left: "l", + center: "c", + right: "r", + justified: "j", + distributed: "d", +}; + +/** + * A `\p` code that sets what `properties` gives of the paragraph it starts and of each after it, + * in heights of the text: written with `x`. `tabs: []` sets no stops, `tz`. + * + * ```ts + * d.paragraph(`${paragraphFormat({ justification: "center" })}TITLE`, { at: [0, 0], width: 4 }); + * ``` + */ +export function paragraphFormat(properties: Omit): string { + const options: string[] = []; + const add = (letter: string, value: number | undefined): void => { + if (value !== undefined) options.push(`${letter}${propertyNumber(value)}`); + }; + add("i", properties.indent); + add("l", properties.left); + add("r", properties.right); + if (properties.tabs) { + options.push( + properties.tabs.length === 0 ? "tz" : `t${properties.tabs.map(propertyNumber).join(",")}`, + ); + } + if (properties.justification) options.push(`q${JUSTIFICATION_LETTERS[properties.justification]}`); + add("b", properties.before); + add("a", properties.after); + if (properties.spacing) add(`s${properties.spacing.style}`, properties.spacing.value); + return `\\px${options.join(",")};`; +} + +/** How a list marks its items, by its first: `"1."`, `"1)"`, `"A."` or `"a."`. */ +export type ListMarks = "1." | "1)" | "A." | "a."; + +/** An item of a list, with the items of the level under it. */ +export interface ListItem { + readonly text: string; + readonly items?: readonly string[]; +} + +/** The mark of the item `n`, from 1: a number, or letters from A to Z, then AA, AB and on. */ +function mark(marks: ListMarks, n: number): string { + if (marks === "1." || marks === "1)") return `${n}${marks[1]}`; + let letters = ""; + for (let k = n; k > 0; k = Math.floor((k - 1) / 26)) { + letters = String.fromCharCode(65 + ((k - 1) % 26)) + letters; + } + return `${marks === "a." ? letters.toLowerCase() : letters}.`; +} + +/** + * A numbered or lettered list in two levels, as the leading CAD app writes one: each item a + * paragraph of its own, its mark, a tab and its text, under a hanging indent of `indent` heights, + * 3 by default, and each item of the level under it indented as far again. The items are joined + * by `\P`, so the value lays out alike in `d.paragraph` and in `layoutParagraph`. What follows a list in the same paragraph value keeps its indents and tab stops + * until `paragraphFormat({ indent: 0, left: 0, tabs: [] })` sets them back. + * + * ```ts + * d.paragraph(`GENERAL NOTES\\P${list(["VERIFY ALL DIMENSIONS.", { text: "DO NOT SCALE.", items: ["SEE A-101."] }])}`, { + * at: [0, 0], + * width: 4, + * }); + * ``` + */ +export function list( + items: readonly (string | ListItem)[], + options: { + readonly marks?: ListMarks; + readonly subMarks?: ListMarks; + readonly indent?: number; + } = {}, +): string { + const { marks = "1.", subMarks = "A.", indent = 3 } = options; + const level = (depth: number): string => + paragraphFormat({ indent: -indent, left: indent * depth, tabs: [indent * depth] }); + const out: string[] = []; + items.forEach((item, i) => { + const { text, items: under = [] } = typeof item === "string" ? { text: item } : item; + out.push(`${level(1)}${mark(marks, i + 1)}\t${text}`); + under.forEach((sub, k) => out.push(`${level(2)}${mark(subMarks, k + 1)}\t${sub}`)); + }); + return out.join("\\P"); +} diff --git a/src/paragraphs.ts b/src/paragraphs.ts index 125ec44..980b4f4 100644 --- a/src/paragraphs.ts +++ b/src/paragraphs.ts @@ -5,7 +5,13 @@ import type { LineSpacingStyle, ParagraphAlign, ParagraphVerticalAlign, Point } import { FONT_METRICS, type FontMetrics } from "./font-metrics.ts"; import { capHeightOf, fontInfo, STANDARD_FONT } from "./fonts.ts"; import { fontMetrics, tableIndex, UNKNOWN } from "./measure.ts"; -import { parseParagraph, type ParsedParagraph, type RunFormat } from "./paragraph-codes.ts"; +import { + parseParagraph, + type ParagraphJustification, + type ParagraphPiece, + type ParsedParagraph, + type RunFormat, +} from "./paragraph-codes.ts"; import { LINE_SPACING_RANGE } from "./rules.ts"; import { fifteenDigits, written } from "./format.ts"; import { Strings } from "./shape.ts"; @@ -54,6 +60,32 @@ import { Strings } from "./shape.ts"; // a TrueType font but those of `STACKS_MEASURED`, and one whose part of spaces is the wider. // - A line that ends in a stack and drops the spaces after it is placed by its first point and not // by the left of its first character's ink, at any attachment. +// - A `\p` code sets what it gives of the paragraph it stands in, wherever in it, and of each +// later one until another changes it: in heights after `x`, in drawing units without. With a +// width, a paragraph's first line starts at its left indent plus its first-line indent from the +// left of the box, never left of it, its other lines at its left indent, and its words wrap at +// its right indent. Without a width no indent moves a line. +// - A tab ends a word and starts the next, which takes it along where the line wraps. It takes the +// pen to a stop, from the left of the box: of the left indent and each stop given, the first +// past the pen by the next character's left, and else the first multiple of `DEFAULT_TAB` past +// the pen; one at or past the right indent takes it nowhere. The next character's ink starts on +// the stop. Without a width only the left indent and the multiples are stops, and a tab before +// the line's first character takes the pen nowhere. +// - After a tab the wrap measures the words as a line that starts on the stop, and a word that +// reaches the width itself leaves a line that starts at an indent or holds a tab. +// - A line stands by its paragraph's justification, or the attachment's: from its start, ending at +// the right indent, or centered between the two, and about the point without a width. +// Justified, each line but the paragraph's last grows each space after its last tab alike, to +// end at the right indent; the last stands by the attachment. Distributed, every line grows +// each gap after its last tab between two characters or stacks alike, and is centered without +// a width. A grown line draws each word and space, or each character, as a run of its own. +// - `\pb` leaves room before each paragraph, the first among them, and no less than +// `BEFORE_LEAST`, and `\pa` after each but the last. Once a code has `x`, the numbers of each +// after it are heights too. `\psm` spaces each line `MULTIPLE` times its A and D, times its factor, and the box +// ends the lesser of that and A and D below the last line's top. `\pse` sets each baseline its +// size below its line's top and each next line 5/3 of it below, and the box ends 2/3 of it +// below the last baseline, less 4/3 of what it passes the height by. +// - A tab's underline runs from the pen to its stop. /** How far past the width a word may reach and stay: the tables' rounding, and no more. */ const SLACK = 1e-9; const UNDERLINE_SHX = 0.2; @@ -73,6 +105,17 @@ const STACKS_MEASURED: ReadonlySet = new Set(["Arial"]); const AT_LEAST_BELOW = 1 / 3; const EXACT_PITCH = 5 / 3; const EXACT_BELOW = 1 / 3; +/** A paragraph's own factor of spacing, `\psm`, spaces its lines this much more than its A and D. */ +const MULTIPLE = 5 / 4; +/** How far apart a tab's stops are, in heights, past those a paragraph gives. */ +const DEFAULT_TAB = 4; +/** How far past the pen a stop must be to take it, in heights: the tables' rounding. */ +const STOP_SLACK = 1e-9; +const TAB = 9; +/** A line's gaps when it is not stretched. */ +const NO_GAPS: readonly number[] = []; +/** The least room a paragraph's `\pb` leaves before it, in heights. */ +const BEFORE_LEAST = 1 / 4; /** A paragraph to lay out. A `Paragraph` and its `TextStyle` spread into one object are one. */ export interface ParagraphToMeasure { @@ -133,7 +176,10 @@ export interface ParagraphStroke { /** One line of a paragraph. */ export interface ParagraphLine { - /** What it draws: its characters in order, and each stack as its parts either side of its divider. */ + /** + * What it draws: its characters in order, each tab as a tab, and each stack as its parts either + * side of its divider. + */ readonly value: string; readonly runs: readonly ParagraphRun[]; /** Its baseline, up from `at`. */ @@ -430,20 +476,40 @@ interface Built { bottom: number; } +/** A stack a line holds, at its first point `x`. */ +interface Stacked { + readonly kind: "stack"; + readonly x: number; + readonly shape: StackShape; + readonly face: Face; + readonly value: string; +} + +/** Where a tab of a line takes the pen, from `from` to `to`, in the format it is in. */ +interface Tabbed { + readonly kind: "tab"; + readonly from: number; + readonly to: number; + readonly format: RunFormat; + readonly face: Face; +} + /** What a line holds as it is built, in drawing units from its first point. */ interface Line { - readonly items: ( - | Built - | { - readonly kind: "stack"; - readonly x: number; - readonly shape: StackShape; - readonly face: Face; - readonly value: string; - } - )[]; + readonly items: (Built | Stacked | Tabbed)[]; /** True when it ends in a stack and the spaces after the stack were dropped. */ spaced: boolean; + /** The paragraph it is in, by its index in the properties `resolve` gives. */ + readonly paragraph: number; + /** True for the first line of its paragraph. */ + readonly first: boolean; + /** Where it starts, from the left of the box: its paragraph's indent, in drawing units. */ + readonly origin: number; + /** + * Where its first point stands from the left of the box, once its first character is placed: + * so that the left of that character's ink, or a tab or a space, is at `origin`. + */ + at: number | undefined; } /** Where the next character of a line goes, and what it continues. */ @@ -454,6 +520,25 @@ interface Pen { key: string | undefined; /** Where the last character's ink ends. */ ink: number; + /** A tab the next character ends, which goes to a stop once that character is known. */ + tab: PendingTab | undefined; + /** + * What the wrap adds to a word's reach, from the line's start: after a tab, from where the line + * would start for the words to stand as they do from the stop. + */ + gap: number; + /** True once the line has a character or a stack. */ + started: boolean; + /** True once a tab of the line has gone to its stop. */ + tabbed: boolean; +} + +/** A tab, from where the pen stood, from the left of the box, in the format it is in. */ +interface PendingTab { + readonly from: number; + readonly started: boolean; + readonly format: RunFormat; + readonly face: Face; } /** A word's characters of one format, the stretch of `source` from `from` to `to`, or a stack. */ @@ -486,9 +571,92 @@ function valueOf(run: Built): string { return run.head === undefined ? last : [...run.head, last].join(""); } +/** What the `\p` codes set of one paragraph, in drawing units, with what it carries from the last. */ +interface Resolved { + readonly indent: number; + readonly left: number; + readonly right: number; + readonly tabs: readonly number[]; + readonly justification: ParagraphJustification | undefined; + readonly before: number; + readonly after: number; + /** A factor of its own spacing for `m`, or the spacing exactly in drawing units for `e`. */ + readonly spacing: { readonly style: "m" | "e"; readonly value: number } | undefined; +} + +const UNSET: Resolved = { + indent: 0, + left: 0, + right: 0, + tabs: [], + justification: undefined, + before: 0, + after: 0, + spacing: undefined, +}; + +/** + * What each paragraph of a value sets, in order: a paragraph takes what the one before it had, + * and then what each of its own `\p` codes sets, wherever in it the code stands. A number is in + * heights of the text after `x`, and in drawing units without it. + */ +/** The most a `\p` number may come to, in drawing units, so that no sum of them overflows. */ +const PROPERTY_MOST = 1e15; + +/** A `\p` number within `PROPERTY_MOST`; `resolve` marks one it moved approximate. */ +function held(value: number): number { + return Math.min(PROPERTY_MOST, Math.max(-PROPERTY_MOST, value)); +} + +/** A code's tab stops in drawing units, in order and each once. */ +function stopsOf(tabs: readonly number[], unit: number): number[] { + const sorted = tabs.map((tab) => held(tab * unit)).sort((a, b) => a - b); + return sorted.filter((tab, k) => k === 0 || tab !== sorted[k - 1]); +} + +function resolve(pieces: readonly ParagraphPiece[], height: number): Resolved[] { + const out: Resolved[] = []; + let current = UNSET; + /** True once a code has had `x`: the codes after it are in heights too. */ + let heights = false; + const finish = (): void => { + out.push(current); + }; + for (const piece of pieces) { + if (piece.kind === "break") { + finish(); + continue; + } + if (piece.kind !== "properties") continue; + const p = piece.properties; + heights ||= p.heights === true; + const unit = heights ? height : 1; + const size = (value: number | undefined, was: number): number => + value === undefined ? was : held(value * unit); + current = { + indent: size(p.indent, current.indent), + left: size(p.left, current.left), + right: size(p.right, current.right), + tabs: p.tabs ? stopsOf(p.tabs, unit) : current.tabs, + justification: p.justification ?? current.justification, + before: size(p.before, current.before), + after: size(p.after, current.after), + spacing: p.spacing + ? { + style: p.spacing.style, + value: held(p.spacing.style === "e" ? p.spacing.value * unit : p.spacing.value), + } + : current.spacing, + }; + } + finish(); + return out; +} + /** - * Lays a paragraph out about its point, in time in proportion to its value: its lines broken at - * its width and at each `\P`, each run of each line where it draws, and its strokes. It reads any + * Lays a paragraph out about its point, in time in proportion to its value, with a search of its + * paragraph's tab stops, sorted once for each `\p` code, for each tab: its lines broken at its + * width and at each `\P`, each run of each line where it draws, and its strokes. It reads any * value and never throws. */ export function layoutParagraph(paragraph: ParagraphToMeasure): ParagraphLayout { @@ -557,10 +725,34 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const own = fontMetrics(settings.font); const ownFont = settings.font ?? STANDARD_FONT; const given = settings.width; - const wrapAt = given > 0 ? given + SLACK * height : Infinity; const tangent = Math.tan((obliqueAngle * Math.PI) / 180); const lean = Number.isFinite(tangent) ? tangent : 0; let approximate = settings.font === undefined || parsed.problem !== undefined; + const properties = resolve(parsed.pieces, height); + // Spacing outside what a paragraph's own may be, indents and room below nothing, numbers held + // to `PROPERTY_MOST` and tab stops out of order are laid out but not measured. + // Each code is looked at once, since what it sets carries into the paragraphs after it. + let heights = false; + for (const piece of parsed.pieces) { + if (piece.kind !== "properties" || approximate) continue; + const p = piece.properties; + heights ||= p.heights === true; + const unit = heights ? height : 1; + const { tabs, spacing } = p; + const most = (value: number | undefined) => + value !== undefined && Math.abs(value * unit) >= PROPERTY_MOST; + const below = (value: number | undefined) => value !== undefined && value < 0; + if ( + [p.indent, p.left, p.right, p.before, p.after].some(most) || + [p.left, p.right, p.before, p.after].some(below) || + tabs?.some((tab, k) => most(tab) || (k > 0 && tab < tabs[k - 1]!)) || + (spacing?.style === "m" && + !(spacing.value >= LINE_SPACING_RANGE[0] && spacing.value <= LINE_SPACING_RANGE[1])) || + (spacing?.style === "e" && !(spacing.value > 0 && !most(spacing.value))) + ) { + approximate = true; + } + } // The faces of the call, by font and weight. A paragraph names at most the fonts of `FONTS`. const faces = new Map(); @@ -576,27 +768,116 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const keyOf = (format: RunFormat, face: Face): string => `${face.font}|${face.bold}|${format.underline}|${format.overline}|${format.strikeThrough}`; - const lines: Line[] = []; - let line: Line = { items: [], spaced: false }; - lines.push(line); - const pen: Pen = { x: 0, key: undefined, ink: 0 }; + /** Where a line of a paragraph starts from the left of the box: none without a width. */ + const originOf = (p: Resolved, first: boolean): number => + given > 0 ? Math.max(0, p.left + (first ? p.indent : 0)) : 0; + /** How far from the left of the box a line's words may reach. */ + const limitOf = (p: Resolved): number => (given > 0 ? given - p.right : Infinity); + + let lines: Line[] = []; + let paragraph = 0; + /** A line of the paragraph `paragraph`. */ + const newLine = (first: boolean): Line => { + const p = properties[paragraph] ?? UNSET; + const made: Line = { + items: [], + spaced: false, + paragraph, + first, + origin: originOf(p, first), + at: undefined, + }; + lines.push(made); + return made; + }; + let line = newLine(true); + let limit = limitOf(properties[0] ?? UNSET); + const pen: Pen = { + x: 0, + key: undefined, + ink: 0, + tab: undefined, + gap: 0, + started: false, + tabbed: false, + }; const word: Parts = { items: [], count: 0 }; const spaces: Parts = { items: [], count: 0 }; + /** The words placed in the paragraph so far. */ let words = 0; + /** + * The stop a tab takes the pen to, from the left of the box, from where it stands, for a next + * character whose ink starts `lefts` past its first point: of the left indent and then each + * stop given, the first that puts that point past the pen, and then the first multiple of + * `DEFAULT_TAB` heights past the pen. Without a width a paragraph has no stops of its own but the left indent, and a tab + * before the line's first character takes it to no multiple. + */ + const stopAfter = (from: number, started: boolean, lefts: number): number => { + const p = properties[line.paragraph] ?? UNSET; + const after = from + STOP_SLACK * height; + let stop: number | undefined; + if (p.left > after + lefts) stop = p.left; + else if (given > 0) { + // The first stop past the point, by halves: a value may give many. + const { tabs } = p; + let low = 0; + let high = tabs.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (tabs[middle]! > after + lefts) high = middle; + else low = middle + 1; + } + stop = tabs[low]; + } else if (!started) return from; + const step = DEFAULT_TAB * height; + stop ??= (Math.floor(after / step) + 1) * step; + // A stop the line cannot reach takes the pen nowhere. + return stop < limit ? stop : from; + }; + /** * Places parts from where `pen` is, and moves `pen` on past them. With `into`, it adds them to - * that line. It gives how far the last of them reach for the break: the last characters' ink - * less the left of the first of them, or the last stack's ink; spaces have no part in it. + * that line. It gives how far the last of them reach, from the left of the box, for the break: + * from the line's first point, as the wrap measures it, the last characters' ink less the left + * of the first of them, or the last stack's ink; spaces have no part in it. */ const place = (parts: Parts, pen: Pen, into?: Line): number => { let { x, key, ink } = pen; let reach = x; let left: number | undefined; + /** Where the line's first point stands from the left of the box. */ + let at = line.at; + /** Takes the pending tab to its stop, for a next character whose ink starts `lefts` on. */ + const toStop = (lefts: number): void => { + const tab = pen.tab!; + const start = at!; + const stop = stopAfter(tab.from, tab.started, lefts); + const before = tab.from - start; + x = stop - start - lefts; + // The words after it are measured as a line that starts on the stop. + pen.gap = start + lefts - line.origin; + if (into) { + into.at ??= start; + into.items.push({ + kind: "tab", + from: before, + to: stop - start, + format: tab.format, + face: tab.face, + }); + } + ink = x; + pen.tab = undefined; + pen.tabbed = true; + }; for (let p = 0; p < parts.count; p++) { const part = parts.items[p]!; if (part.kind === "stack") { + if (at === undefined) at = line.origin; + if (pen.tab) toStop(0); if (into) { + into.at ??= at; into.items.push({ kind: "stack", x, @@ -605,52 +886,78 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { value: part.value, }); } - reach = x + part.shape.ink; + reach = x + part.shape.ink + pen.gap; + ink = x + part.shape.ink; + pen.started = true; x += part.shape.advance; - ink = reach; key = undefined; left = undefined; continue; } const { face } = part; + const { source: value, to } = part; let run: Built | undefined; - if (key !== part.key) { - // A new run starts where the last one's advances end, or its ink where that is further. - if (key !== undefined && ink > x) x = ink; - key = part.key; - if (into) { - run = { - kind: "run", - head: undefined, - source: part.source, - from: part.from, - to: part.from, - x, - face, - format: part.format, - advance: 0, - last: x, - lastIndex: 0, - top: 0, - bottom: 0, - }; - into.items.push(run); - } - } else if (into) { + if (into && key === part.key) { const last = into.items[into.items.length - 1]; run = last?.kind === "run" ? last : undefined; } - const { source: value, to } = part; for (let k = part.from; k < to; k++) { const code = value.charCodeAt(k); + if (code === TAB) { + // The pen goes to a stop once the next character is known. + if (at === undefined) at = line.origin; + if (pen.tab) toStop(0); + pen.tab = { from: at + x, started: pen.started, format: part.format, face }; + key = undefined; + run = undefined; + left = undefined; + continue; + } let index = tableIndex(value.codePointAt(k)!); if (index < 0) index = UNKNOWN; + const lefts = code === 32 ? 0 : face.lefts[index]! * along; + if (at === undefined) { + // The first character of a line: its ink, or a space's first point, starts the line. + at = line.origin - (code === 32 ? 0 : lefts + lean * face.bottoms[index]! * height); + } + // The first character after a tab: its ink starts at the stop. + if (pen.tab) toStop(lefts); + pen.started = true; + if (key !== part.key) { + // A new run starts where the last one's advances end, or its ink where that is further. + if (key !== undefined && ink > x) x = ink; + key = part.key; + if (into) { + into.at ??= at; + run = { + kind: "run", + head: undefined, + source: value, + from: k, + to: k, + x, + face, + format: part.format, + advance: 0, + last: x, + lastIndex: 0, + top: 0, + bottom: 0, + }; + into.items.push(run); + } + } ink = x + face.rights[index]! * along; if (code !== 32) { - left ??= face.lefts[index]! * along; - reach = ink - left; + left ??= lefts; + reach = ink - left + pen.gap; } if (run) { + if (run.source !== value || run.to !== k) { + if (run.to > run.from) (run.head ??= []).push(run.source.slice(run.from, run.to)); + run.source = value; + run.from = k; + } run.last = x; run.lastIndex = index; if (face.tops[index]! > run.top) run.top = face.tops[index]!; @@ -658,24 +965,19 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { } x += face.advances[index]! * along; // A pair of surrogates is one character. - if (code >= 0xd800 && code <= 0xdbff && k + 1 < to && value.charCodeAt(k + 1) >= 0xdc00) - k++; - } - if (run) { - // The run holds the part's characters, as one stretch where they follow on. - if (run.source !== value || run.to !== part.from) { - if (run.to > run.from) (run.head ??= []).push(run.source.slice(run.from, run.to)); - run.source = value; - run.from = part.from; + const pair = + code >= 0xd800 && code <= 0xdbff && k + 1 < to && value.charCodeAt(k + 1) >= 0xdc00; + if (pair) k++; + if (run) { + run.to = k + 1; + run.advance = x - run.x; } - run.to = to; - run.advance = x - run.x; } } pen.x = x; pen.key = key; pen.ink = ink; - return reach; + return reach + line.origin; }; /** Drops the spaces a line ends with. */ @@ -683,20 +985,44 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { if (spaces.count > 0 && line.items[line.items.length - 1]?.kind === "stack") line.spaced = true; spaces.count = 0; }; - const trial: Pen = { x: 0, key: undefined, ink: 0 }; + const restart = (first: boolean): void => { + line = newLine(first); + pen.x = 0; + pen.key = undefined; + pen.ink = 0; + pen.tab = undefined; + pen.gap = 0; + pen.started = false; + pen.tabbed = false; + }; + /** + * True when a word reaching `reach` leaves the line: past the width by more than the tables' + * rounding, or on a line that starts at an indent or holds a tab, at the width itself. + */ + const overflows = (reach: number, pen: Pen): boolean => + reach > limit + (line.origin > 0 || pen.tabbed ? -SLACK : SLACK) * height; + const trial: Pen = { + x: 0, + key: undefined, + ink: 0, + tab: undefined, + gap: 0, + started: false, + tabbed: false, + }; const endWord = (): void => { if (word.count === 0) return; trial.x = pen.x; trial.key = pen.key; trial.ink = pen.ink; + trial.tab = pen.tab; + trial.gap = pen.gap; + trial.started = pen.started; + trial.tabbed = pen.tabbed; place(spaces, trial); - if (words > 0 && place(word, trial) > wrapAt) { + if (words > 0 && overflows(place(word, trial), trial)) { endLine(); - line = { items: [], spaced: false }; - lines.push(line); - pen.x = 0; - pen.key = undefined; - pen.ink = 0; + restart(false); } else place(spaces, pen, line); place(word, pen, line); words++; @@ -738,18 +1064,37 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { into.count++; }; - for (const piece of parsed.pieces) { + /** Breaks the value into lines. */ + const build = (): void => { + lines = []; + paragraph = 0; + line = newLine(true); + limit = limitOf(properties[0] ?? UNSET); + pen.x = 0; + pen.key = undefined; + pen.ink = 0; + pen.tab = undefined; + pen.gap = 0; + pen.started = false; + pen.tabbed = false; + word.count = 0; + spaces.count = 0; + words = 0; + for (const piece of parsed.pieces) breakPiece(piece); + endWord(); + endLine(); + }; + const breakPiece = (piece: ParagraphPiece): void => { if (piece.kind === "break") { endWord(); endLine(); - line = { items: [], spaced: false }; - lines.push(line); - pen.x = 0; - pen.key = undefined; - pen.ink = 0; + paragraph++; + limit = limitOf(properties[paragraph] ?? UNSET); + restart(true); words = 0; - continue; + return; } + if (piece.kind === "properties") return; const face = faceFor(piece.format); if (piece.kind === "stack") { const top = partOf(piece.top, face); @@ -779,7 +1124,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { } const value = `${piece.top}${piece.separator}${piece.bottom}`; word.items[word.count++] = { kind: "stack", shape, face, value }; - continue; + return; } if (face.shx && piece.diameter) approximate = true; // Characters at a size of their own are not laid out yet. @@ -791,19 +1136,24 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const value = nonBreaking(piece.value); const breaking = piece.value; for (let k = 0; k < value.length; k++) { - if (breaking.charCodeAt(k) === 32) { + const code = breaking.charCodeAt(k); + if (code === 32) { if (k > from) append(word, value, from, k, format, face, key); endWord(); append(spaces, value, k, k + 1, format, face, key); from = k + 1; + } else if (code === TAB) { + // A tab starts a word, which takes it along where the line wraps. + if (k > from) append(word, value, from, k, format, face, key); + endWord(); + from = k; } else if (tableIndex(value.codePointAt(k)!) < 0) { approximate = true; } } if (value.length > from) append(word, value, from, value.length, format, face, key); - } - endWord(); - endLine(); + }; + build(); if (lean !== 0 && [...faces.values()].some((face) => face.shx)) approximate = true; @@ -816,17 +1166,23 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { /** How far the lean moves where the line starts: by its first character's bottom. */ let startLean = 0; let end = 0; + let drawn = false; // What the box of a dimension's text takes below the baseline: how far its characters reach, // and how far below the line a stack sets its lowest part's baseline. let runDown = 0; let drop = 0; for (const item of built.items) { + if (item.kind === "tab") { + start ??= 0; + continue; + } if (item.kind === "stack") { stackUp = Math.max(stackUp, item.shape.top); down = Math.min(down, item.shape.bottom); for (const part of item.shape.parts) drop = Math.max(drop, -part.up); start ??= item.x; end = item.x + item.shape.ink; + drawn = true; continue; } const run = item; @@ -848,8 +1204,9 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { startLean = lean * run.face.bottoms[index]! * height; } end = run.last + run.face.rights[run.lastIndex]! * along; + drawn = true; } - const empty = start === undefined; + const empty = !drawn; // A line's A is at least a capital's height, and D a third of it unless a stack reaches highest. const top = empty ? height : Math.max(up, stackUp); // A line that ends in a stack and dropped spaces after it is placed by its first point and @@ -864,28 +1221,60 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { down: settings.dimension ? runDown - (stackUp > up ? drop : 0) : down, start: start ?? 0, end, + shift, leanedStart: (start ?? 0) + startLean - shift, leanedEnd: empty ? 0 : end + lean * top - shift, + empty, }; }); - // Down the box: each line's baseline from its top. + // Down the box: each line's baseline from its top, by its paragraph's spacing, with the room + // its paragraph leaves before it and the last one after it. const baselines: number[] = []; let boxHeight: number; - if (exactly) { - measured.forEach((_, k) => baselines.push(-height - k * EXACT_PITCH * factor * height)); - boxHeight = -baselines[baselines.length - 1]! + EXACT_BELOW * height; - } else { + { let top = 0; - for (const m of measured) { - baselines.push(top - m.top); - top -= factor * (m.top + m.below + AT_LEAST_BELOW * height); - } - const last = measured[measured.length - 1]!; - boxHeight = -(baselines[baselines.length - 1]! + last.down); + let bottom = 0; + measured.forEach((m, k) => { + const p = properties[m.built.paragraph] ?? UNSET; + if (m.built.first) { + const before = k > 0 ? (properties[m.built.paragraph - 1] ?? UNSET).after : 0; + top -= (p.before > 0 ? Math.max(p.before, BEFORE_LEAST * height) : p.before) + before; + } + const spacing = p.spacing; + let baseline: number; + let slot: number; + if (spacing?.style === "e") { + baseline = top - spacing.value; + slot = EXACT_PITCH * spacing.value; + // The box ends two thirds of the spacing below the last baseline, less four thirds of + // what the spacing passes the height by. + const past = Math.max(0, spacing.value - height); + bottom = baseline - (2 * spacing.value - 4 * past) / 3; + } else if (spacing?.style === "m") { + const natural = m.top + m.below; + baseline = top - m.top; + slot = spacing.value * MULTIPLE * natural; + bottom = top - Math.min(slot, natural); + } else if (exactly) { + baseline = top - height; + slot = EXACT_PITCH * factor * height; + bottom = baseline - EXACT_BELOW * height; + } else { + baseline = top - m.top; + slot = factor * (m.top + m.below + AT_LEAST_BELOW * height); + bottom = baseline + m.down; + } + baselines.push(baseline); + top -= slot; + }); + boxHeight = -bottom; } const { align, valign } = settings; const boxTop = valign === "middle" ? boxHeight / 2 : valign === "bottom" ? boxHeight : 0; + /** Where the left of the box stands from the point, and where its lines may reach. */ + const boxLeft = + given > 0 ? (align === "center" ? -given / 2 : align === "right" ? -given : 0) : 0; const ink: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]; const include = (x: number, y: number): void => { @@ -901,94 +1290,193 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { include(...to); }; let widest = 0; - const laid = measured.map((m, k): ParagraphLine => { - const baseline = boxTop + baselines[k]!; - const offset = - align === "center" - ? -(m.leanedStart + m.leanedEnd) / 2 - : align === "right" - ? -m.leanedEnd - : -m.leanedStart; - const runs: ParagraphRun[] = []; - /** The value of the line's one run or stack, and those of all once it has more, joined flat. */ - let value = ""; - let values: string[] | undefined; - const add = (part: string): void => { - if (values) values.push(part); - else if (value === "") value = part; - else values = [value, part]; + // What the line being placed holds and how it is stretched, kept across lines so that placing + // one makes no closures of its own. + let runs: ParagraphRun[] = []; + let value = ""; + let values: string[] | undefined; + let baseline = 0; + let gaps: readonly number[] = NO_GAPS; + let stretch = 0; + let gap = 0; + let grown = 0; + /** Adds a part to the line's value: the one run or stack, and all once it has more, joined flat. */ + const add = (part: string): void => { + if (values) values.push(part); + else if (value === "") value = part; + else values = [value, part]; + }; + /** Adds a run of `value` in `face` at its first point `x`, of `size`, with its baseline at `base`. */ + const run = (value: string, x: number, base: number, size: number, face: Face, top: number) => { + if (value === "") return undefined; + let advance = 0; + let head: number | undefined; + let tail = 0; + for (const character of value) { + let index = indexOf(character); + if (index < 0) index = UNKNOWN; + head ??= face.heads?.[index] ?? 0; + advance += face.advances[index]!; + tail = face.tails?.[index] ?? 0; + } + const scale = size * widthFactor; + const drawn: ParagraphRun = { + value, + x, + baseline: base, + height: size, + font: face.font, + bold: face.bold, + advance: advance * scale, + start: x + (head ?? 0) * scale, + end: x + (advance + tail) * scale, }; - /** Adds a run of `value` in `face` at its first point `x`, of `size`, with its baseline at `base`. */ - const run = (value: string, x: number, base: number, size: number, face: Face, top: number) => { - if (value === "") return; - let advance = 0; - let head: number | undefined; - let tail = 0; - for (const character of value) { - let index = indexOf(character); - if (index < 0) index = UNKNOWN; - head ??= face.heads?.[index] ?? 0; - advance += face.advances[index]!; - tail = face.tails?.[index] ?? 0; + runs.push(drawn); + const below = face.below * size; + const reach = Math.max(top, 1) * size; + const from = Math.min(drawn.start, x); + const to = Math.max(drawn.end, x + drawn.advance); + include(from - lean * below, base - below); + include(to + lean * reach, base + reach); + include(from + lean * reach, base + reach); + include(to - lean * below, base - below); + return drawn; + }; + /** The underline, overline and strike-through of `format` from `x0` to `x1` on the line. */ + const lined = (format: RunFormat, face: Face, x0: number, x1: number): void => { + if (format.underline) { + const up = baseline - face.underline * height; + stroke("underline", [x0, up], [x1, up]); + } + if (format.overline) + stroke("overline", [x0, baseline + OVERLINE * height], [x1, baseline + OVERLINE * height]); + if (format.strikeThrough) { + const up = baseline + STRIKE_THROUGH * height; + stroke("strike-through", [x0, up], [x1, up]); + } + }; + /** How far the gaps before a place of the line have grown it. */ + const grow = (x: number): number => { + while (gap < gaps.length && gaps[gap]! <= x) { + grown += stretch; + gap++; + } + return grown; + }; + const laid: ParagraphLine[] = []; + for (let k = 0; k < measured.length; k++) { + const m = measured[k]!; + const built = m.built; + const p = properties[built.paragraph] ?? UNSET; + baseline = boxTop + baselines[k]!; + const lastOfParagraph = lines[k + 1]?.paragraph !== built.paragraph; + const justification = + p.justification === "justified" && lastOfParagraph ? undefined : p.justification; + const style = justification ?? align ?? "left"; + // The line is laid out from the left of the box, then moved across to its place: its ink + // from `origin` to the right indent, or about the point without a width. + const at = (built.at ?? built.origin) + m.shift; + const from = given > 0 ? built.origin : 0; + const to = given > 0 ? Math.max(built.origin, given - p.right) : 0; + const inkFrom = at + m.leanedStart; + const inkTo = at + m.leanedEnd; + // How far each of the gaps a justified or distributed line stretches grows, and after which. + stretch = 0; + gap = 0; + grown = 0; + gaps = NO_GAPS; + let after = -1; + let across = 0; + if (!m.empty && given > 0 && (style === "justified" || style === "distributed")) { + gaps = gapsOf(built, style === "distributed", along); + after = lastTabOf(built); + if (gaps.length > 0) stretch = (to - inkTo) / gaps.length; + } + if (style === "center" || (style === "distributed" && gaps.length === 0)) { + across = (from + to) / 2 - (inkFrom + inkTo) / 2; + } else if (style === "right") across = to - inkTo; + const offset = boxLeft + at + across; + runs = []; + value = ""; + values = undefined; + // Where each word of a stretched line in an SHX font stands is not measured. + if (gaps.length > 0 && built.items.some((item) => item.kind !== "tab" && item.face.shx)) { + approximate = true; + } + const items = built.items; + for (let i = 0; i < items.length; i++) { + const item = items[i]!; + if (item.kind === "tab") { + add("\t"); + lined(item.format, item.face, offset + item.from, offset + item.to); + continue; } - const scale = size * widthFactor; - const drawn: ParagraphRun = { - value, - x, - baseline: base, - height: size, - font: face.font, - bold: face.bold, - advance: advance * scale, - start: x + (head ?? 0) * scale, - end: x + (advance + tail) * scale, - }; - runs.push(drawn); - const below = face.below * size; - const reach = Math.max(top, 1) * size; - const from = Math.min(drawn.start, x); - const to = Math.max(drawn.end, x + drawn.advance); - include(from - lean * below, base - below); - include(to + lean * reach, base + reach); - include(from + lean * reach, base + reach); - include(to - lean * below, base - below); - }; - for (const item of m.built.items) { if (item.kind === "stack") { add(item.value); - const at = item.x + offset; + const x = item.x + offset + (i > after ? grow(item.x) : 0); for (const part of item.shape.parts) { - run(part.value, at + part.x, baseline + part.up, item.shape.size, item.face, part.top); + run(part.value, x + part.x, baseline + part.up, item.shape.size, item.face, part.top); } const drawnStroke = item.shape.stroke; if (drawnStroke) { const [[x0, y0], [x1, y1]] = drawnStroke; - stroke("bar", [at + x0, baseline + y0], [at + x1, baseline + y1]); + stroke("bar", [x + x0, baseline + y0], [x + x1, baseline + y1]); } continue; } - const built = item; - const x = built.x + offset; - const drawn = valueOf(built); + const drawn = valueOf(item); add(drawn); - run(drawn, x, baseline, height, built.face, built.top); - const { underline, overline, strikeThrough } = built.format; - const across = (kind: ParagraphStroke["kind"], up: number): void => - stroke(kind, [x, baseline + up], [x + built.advance, baseline + up]); - if (underline) across("underline", -built.face.underline * height); - if (overline) across("overline", OVERLINE * height); - if (strikeThrough) across("strike-through", STRIKE_THROUGH * height); + if (i <= after || gaps.length === 0) { + const x = item.x + offset; + run(drawn, x, baseline, height, item.face, item.top); + lined(item.format, item.face, x, x + item.advance); + continue; + } + // A stretched line draws each word and each space, or each character, on its own: the + // stretch of the run's value from `start`, which starts at `pieceX`. + let x = item.x; + let start = 0; + let pieceX = x; + let afterSpace = false; + const flush = (end: number): void => { + if (end === start) return; + const placed = run( + drawn.slice(start, end), + pieceX + offset + grow(pieceX), + baseline, + height, + item.face, + item.top, + ); + if (placed) lined(item.format, item.face, placed.x, placed.x + placed.advance); + start = end; + pieceX = x; + }; + for (let c = 0; c < drawn.length; c++) { + const code = drawn.charCodeAt(c); + const space = code === 32; + if (style === "distributed" || space || afterSpace) flush(c); + afterSpace = space; + let index = tableIndex(drawn.codePointAt(c)!); + if (index < 0) index = UNKNOWN; + x += item.face.advances[index]! * along; + // A pair of surrogates is one character. + if (code >= 0xd800 && code <= 0xdbff && drawn.charCodeAt(c + 1) >= 0xdc00) c++; + } + flush(drawn.length); } widest = Math.max(widest, m.end - m.start); - return { - value: values ? values.join("") : value, + // `add` sets the two, which the compiler does not follow. + const parts = values as string[] | undefined; + laid.push({ + value: parts ? parts.join("") : value, runs, baseline, - start: m.built.items.length === 0 ? 0 : m.start + offset, - end: m.built.items.length === 0 ? 0 : m.end + offset, + start: m.empty ? 0 : m.start + offset, + end: m.empty ? 0 : m.end + offset + grown, top: m.top, - }; - }); + }); + } const frameWidth = given > 0 ? given : widest; const left = align === "center" ? -frameWidth / 2 : align === "right" ? -frameWidth : 0; @@ -1005,6 +1493,43 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { }; } +/** The index of a line's last tab among its items, or -1. */ +function lastTabOf(line: Line): number { + for (let i = line.items.length - 1; i >= 0; i--) if (line.items[i]!.kind === "tab") return i; + return -1; +} + +/** + * The places along a line, from its first point, past which a justified line grows by a share of + * what it lacks: after each space that follows a character since its last tab. A distributed line + * grows before each character and stack since its last tab but the first. + */ +function gapsOf(line: Line, distributed: boolean, along: number): number[] { + const out: number[] = []; + let seen = false; + const items = line.items; + for (let i = lastTabOf(line) + 1; i < items.length; i++) { + const item = items[i]!; + if (item.kind === "tab") continue; + if (item.kind === "stack") { + if (distributed && seen) out.push(item.x); + seen = true; + continue; + } + let x = item.x; + for (const character of valueOf(item)) { + let index = indexOf(character); + if (index < 0) index = UNKNOWN; + const advance = item.face.advances[index]! * along; + const space = character === " "; + if (distributed ? seen : space && seen) out.push(distributed ? x : x + advance); + if (distributed || !space) seen = true; + x += advance; + } + } + return out; +} + /** The corners of a box of a layout where `place` puts them: lower left, lower right, upper right, upper left. */ function corners( place: (along: number, up: number) => Point, diff --git a/src/pdf.ts b/src/pdf.ts index 4732096..bbd2133 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -275,16 +275,16 @@ const ATTRIBUTES = new Set([ ]); /** - * Text with the four entities `toSVG` escapes with, and the line feed it writes as ` `, in - * their place. Any other `&` is refused. + * Text with the four entities `toSVG` escapes with, and the line feed and the tab it writes as + * ` ` and ` `, in their place. Any other `&` is refused. */ function unescape(text: string, where: string): string { if (!text.includes("&")) return text; - return text.replace(/&(amp;|lt;|gt;|quot;|#10;)?/g, (_, name: string | undefined) => { + return text.replace(/&(amp;|lt;|gt;|quot;|#10;|#9;)?/g, (_, name: string | undefined) => { if (name === undefined) throw refuse("an & that is not one toSVG writes", where); - return ({ "amp;": "&", "lt;": "<", "gt;": ">", "quot;": '"', "#10;": "\n" } as const)[ - name as "amp;" - ]; + return ( + { "amp;": "&", "lt;": "<", "gt;": ">", "quot;": '"', "#10;": "\n", "#9;": "\t" } as const + )[name as "amp;"]; }); } diff --git a/src/rules.ts b/src/rules.ts index fd75318..05c14da 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -39,6 +39,8 @@ import { PARAGRAPH_STACK_LINED, PARAGRAPH_STACK_PART, PARAGRAPH_STACK_SEPARATOR, + PARAGRAPH_SPACING_AT_LEAST, + PARAGRAPH_TAB_KIND, PARAGRAPH_TOO_DEEP, PARAGRAPH_TRAILING, type BoldFont, @@ -48,6 +50,7 @@ import { type paragraphItalic, type paragraphNoSemicolon, type paragraphNotLaidOut, + type paragraphPropertyUnknown, type paragraphShxBold, type paragraphUnknownCode, type paragraphUnknownFont, @@ -969,7 +972,7 @@ type ParagraphPercent = S extends `${string}%${infer R}` ? ["% type ParagraphPlainCode = "P" | "~" | "\\" | "{" | "}" | "o"; /** The codes tsdraft does not lay out that end with a `;`. */ -type ParagraphEndedCode = "p" | "H" | "W" | "Q" | "T" | "A" | "C" | "c"; +type ParagraphEndedCode = "H" | "W" | "Q" | "T" | "A" | "C" | "c"; /** * Whether the characters are underlined, `L`, struck through, `K`, both or neither, as the codes @@ -1020,7 +1023,7 @@ type Relined = C extends "L" */ export type ParagraphValue = string extends T ? T - : T extends `${string}${Exclude}${string}` + : T extends `${string}${Exclude}${string}` ? typeof PARAGRAPH_CONTROL : T extends `${string}${Chars}${string}` ? typeof PARAGRAPH_PRIVATE_USE @@ -1084,27 +1087,126 @@ type ParagraphCode< : ReturnType> : C extends "S" ? ParagraphStack - : C extends ParagraphEndedCode - ? After extends `${string};${string}` - ? ReturnType> + : C extends "p" + ? After extends `${infer Body};${infer Next}` + ? ParagraphProperties< + Body extends `x${infer Rest}` ? Rest : Body, + "option", + [...N, 0] + > extends true + ? ParagraphCodes + : ParagraphProperties< + Body extends `x${infer Rest}` ? Rest : Body, + "option", + [...N, 0] + > : ReturnType> - : C extends "N" | "X" | "O" - ? ReturnType> - : C extends "U" | "u" - ? After extends `+${infer H1}${infer H2}${infer H3}${infer H4}${infer Next}` - ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] - ? ParagraphUnicode, Next, D, N, F> - : ReturnType> - : ReturnType> - : C extends "M" | "m" - ? After extends `+${"1" | "2" | "3" | "4" | "5"}${infer H1}${infer H2}${infer H3}${infer H4}${string}` + : C extends ParagraphEndedCode + ? After extends `${string};${string}` + ? ReturnType> + : ReturnType> + : C extends "N" | "X" | "O" + ? ReturnType> + : C extends "U" | "u" + ? After extends `+${infer H1}${infer H2}${infer H3}${infer H4}${infer Next}` ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] - ? ReturnType> + ? ParagraphUnicode, Next, D, N, F> + : ReturnType> + : ReturnType> + : C extends "M" | "m" + ? After extends `+${"1" | "2" | "3" | "4" | "5"}${infer H1}${infer H2}${infer H3}${infer H4}${string}` + ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] + ? ReturnType> + : ReturnType> : ReturnType> : ReturnType> - : ReturnType> : typeof PARAGRAPH_TRAILING; +/** + * Where the walk of a `\p` code's options stands: before an option, where a number starts, after + * its sign, after its point with no digit yet, among its digits, or among a tab stop's, where a + * comma may start another stop. + */ +type PropertyState = "option" | "number" | "signed" | "point" | "digits" | "decimals"; + +/** + * True for the options of a `\p` code after its `x`, as `readProperties` in + * `src/paragraph-codes.ts` reads them, and the message otherwise, which quotes an option by its + * letter and the character after it, `O`. `Stops` is true inside a list of tab stops. Past the + * walk's steps it gives up and leaves the rest to the runtime check. + */ +type ParagraphProperties< + S extends string, + State extends PropertyState, + N extends 0[], + O extends string = "", + Stops extends boolean = false, +> = N["length"] extends ParagraphTypeSteps + ? true + : State extends "option" + ? S extends `${infer C}${infer R}` + ? C extends "," + ? ParagraphProperties + : C extends "i" | "l" | "r" | "b" | "a" + ? ParagraphProperties> + : C extends "q" + ? R extends `${"l" | "c" | "r" | "j" | "d"}${infer After}` + ? ParagraphProperties + : ReturnType>> + : C extends "s" + ? R extends `${"m" | "e"}${infer After}` + ? ParagraphProperties> + : R extends `a${string}` + ? typeof PARAGRAPH_SPACING_AT_LEAST + : ReturnType>> + : C extends "t" + ? R extends `z${infer After}` + ? ParagraphProperties + : R extends `${"r" | "c" | "d"}${string}` + ? typeof PARAGRAPH_TAB_KIND + : ParagraphProperties, true> + : ReturnType>> + : true + : State extends "number" | "signed" | "point" + ? S extends `${infer C}${infer R}` + ? C extends Digit + ? ParagraphProperties< + R, + State extends "point" ? "decimals" : "digits", + [...N, 0], + O, + Stops + > + : [State, C] extends ["number", "-"] + ? ParagraphProperties + : [State, C] extends ["number" | "signed", "."] + ? ParagraphProperties + : ReturnType> + : ReturnType> + : S extends `${Digit}${infer R}` + ? ParagraphProperties + : [State, S] extends ["digits", `.${infer R}`] + ? ParagraphProperties + : Stops extends true + ? S extends `,${infer R}` + ? R extends `${"r" | "c" | "d"}${string}` + ? typeof PARAGRAPH_TAB_KIND + : R extends `${Digit | "." | "-"}${string}` + ? ParagraphProperties + : ParagraphProperties + : ParagraphProperties + : ParagraphProperties; + +/** + * The option a message quotes: its letter and the character after it, as the builder holds them, a + * line feed as the `\P` it becomes. + */ +type PropertyOption = S extends `\n${string}` + ? "\\P" + : S extends `${infer A}${infer B}${string}` + ? `${A}${B extends "\n" ? "\\" : B}` + : S; + /** A `\U+XXXX` code, with its four digits in lower case. */ type ParagraphUnicode< T extends string, diff --git a/src/svg.ts b/src/svg.ts index 1f4e68e..61785be 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -1233,7 +1233,8 @@ function paragraphToSvg( ``, ); } - const open = ``; return `${open}>\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } diff --git a/test/bounded.test.ts b/test/bounded.test.ts index dca3e0a..8f2f39b 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2339,6 +2339,16 @@ test("a paragraph of many lines, runs or braces, a long word and numbers past dr paragraph({ value: `\\S${"1".repeat(200_000)}/${"2".repeat(200_000)};`, width: 1 }), paragraph({ value: "%".repeat(500_000), lineSpacingStyle: "exactly" }), paragraph({ value: `\\fArial${"|b0".repeat(200_000)};X` }), + // Tabs to stops of their own and by default, indents, stretched lines and a right indent, + // which lays the lines out twice. + paragraph({ value: "H\t".repeat(200_000), width: 3 }), + paragraph({ value: `\\pxt${"1,".repeat(100_000)}2;${"H\t".repeat(100_000)}`, width: 1e6 }), + paragraph({ value: "\\pxi-3,l3,t3;1.\tA B\\P".repeat(40_000), width: 4 }), + paragraph({ value: "\\pxqd;AB CD ".repeat(50_000), width: 1e-6 }), + paragraph({ value: "\\pxqj;AB CD ".repeat(50_000), width: 20 }), + paragraph({ value: `\\pxi1,l2,r3;${"W ".repeat(200_000)}`, width: 6 }), + paragraph({ value: "\\pl99999999999999999999,r-1e9;A".repeat(1_000), width: 1 }), + paragraph({ value: "\\pxsm4,se0.0001,b1000,a-1000;A\\P".repeat(50_000), width: 1 }), ]; for (const [i, leaf] of hostile.entries()) { const d: Drawing = { diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index b417412..d031e7a 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -8,8 +8,10 @@ import { layoutMtext, layoutParagraph, lint, + list, measureMtext, measureParagraph, + paragraphFormat, paragraphInStyle, parseParagraph, plain, @@ -96,7 +98,9 @@ test("what tsdraft does not lay out is refused, and named", () => { ["\\A1;A", /code \\A/], ["\\C1;A", /code \\C, which sets the color/], ["\\c255;A", /code \\c, which sets the true color/], - ["\\pi-1,l1;A", /code \\p/], + ["\\ptr3;A", /aligns text by its right/], + ["\\psa1.2;A", /at least a size apart/], + ["\\pi-;A", /option "i-"/], ["A\\NB", /code \\N, which starts a new column/], ["A\\XB", /code \\X/], ["\\OA", /code \\O, which draws a line over/], @@ -265,6 +269,97 @@ test("a paragraph is laid out where the leading CAD app sets its lines and runs" } }); +test("a list hangs its items under their marks, and its tabs and indents fall where the leading CAD app puts them", () => { + const arial = { font: "Arial" } as const; + const lines = (value: string, width: number) => + layoutParagraph({ value, height: 1, width, ...arial }).lines.map((line) => line.value); + assert.equal( + list(["ONE", { text: "TWO", items: ["UNDER"] }]), + "\\pxi-3,l3,t3;1.\tONE\\P\\pxi-3,l3,t3;2.\tTWO\\P\\pxi-3,l6,t6;A.\tUNDER", + ); + assert.equal( + paragraphFormat({ + indent: 0, + left: 0, + tabs: [], + justification: "justified", + spacing: { style: "m", value: 1.15 }, + }), + "\\pxi0,l0,tz,qj,sm1.15;", + ); + // The text after the tab starts its ink on the stop, the left indent, as do the lines it wraps to. + assert.ok( + near(runs({ value: list(["HHHH HHHH HHHH"]), width: 11.35, ...arial }), [ + ["1.", -0.15211, -1.00409], + ["HHHH HHHH", 2.88813, -1.00409], + ["HHHH", 2.88813, -2.67076], + ]), + ); + // The words after the tab are measured as a line that starts on the stop, as the plot wraps them. + assert.deepEqual(lines(list(["HHHH HHHH HHHH"]), 11.2348), ["1.\tHHHH HHHH", "HHHH"]); + assert.deepEqual(lines(list(["HHHH HHHH HHHH"]), 11.2346), ["1.\tHHHH", "HHHH", "HHHH"]); + // Stops given, then every four heights; a stop that would put the next letter behind the pen is + // passed, and a centered line is laid out from the box and then moved. + assert.ok( + near(runs({ value: "\\pxt2.5,4;H\tH\tH\tH", width: 20, ...arial }), [ + ["H", -0.11187, -1], + ["H", 2.38813, -1], + ["H", 3.88813, -1], + ["H", 7.88813, -1], + ]), + ); + assert.deepEqual(lines("\\pxt3;HHH\tHHH HHH HHH", 6), ["HHH", "\tHHH", "HHH", "HHH"]); + assert.ok( + near(runs({ value: "\\pxqc;H\tH", width: 10, ...arial }), [ + ["H", 2.49591, -1], + ["H", 6.49591, -1], + ]), + ); + // A right indent holds every line short of it, and the lines after the first start at the left + // indent. + const starts = layoutParagraph({ + value: `\\pxi1,l2,r1;${"HHHH ".repeat(8)}`, + height: 1, + width: 32, + ...arial, + }).lines.map((line) => [line.value.split(" ").length, Math.round(line.start)]); + assert.deepEqual(starts, [ + [6, 3], + [2, 2], + ]); + // A justified line grows its spaces to end at the width, each space a run of its own; its + // paragraph's last line stands by the attachment. + assert.ok( + near( + runs({ value: "\\pqj;HHHH HH HHHH H HHHH HHHH HHH", width: 12, ...arial }).slice(0, 5), + [ + ["HHHH", -0.11187, -1], + [" ", 3.92361, -1], + ["HH", 4.99, -1], + [" ", 7.0067, -1], + ["HHHH", 8.0771, -1], + ], + 0.003, + ), + ); + // The paragraph's own spacing, by a factor and exactly, and room before and after it. + const baselines = (value: string, height = 1) => + layoutParagraph({ value, height, ...arial }).lines.map((line) => +line.baseline.toFixed(4)); + assert.deepEqual(baselines("\\psm1.5;HHH\\P1\\S1/2;\\PHHH"), [-1, -4.8415, -7.8903]); + assert.deepEqual(baselines("\\pse0.6;HHH\\PHHH"), [-0.6, -1.6]); + assert.deepEqual(baselines("\\pb1;HHH\\P\\pa2;HHH\\PHHH"), [-2, -4.6667, -9.3333]); + // Room before a paragraph is a quarter of a height at least, and `x` holds for the codes after. + assert.deepEqual(baselines("\\pxa0.5;HHH\\P\\pb0.1;HHH"), [-1, -3.4167]); + assert.deepEqual(baselines("\\pxa0.5;HHH\\P\\pb0.5;HHH", 2), [-2, -7.3333]); + assert.deepEqual(baselines("\\pa1;HHH\\P\\pb0.5;HHH", 2), [-2, -6.8333]); + // The picture holds the tab as an entity, which an XML reader keeps, and the plot reads it. + const d = createDrawing({ units: "in" }); + d.layout("SHEET", { paper: "ARCH D" }, () => d.paragraph(list(["ONE"]), { at: [1, 20] })); + const picture = toSVG(d.build(), { layout: "SHEET" }); + assert.ok(picture.includes('data-paragraph="\\pxi-3,l3,t3;1. ONE"')); + assert.ok(svgToPDF([picture]).length > 0); +}); + test("what the tables cannot lay out exactly is approximate, or refused", () => { const approximate = (value: string, font: string, obliqueAngle = 0) => layoutParagraph({ value, height: 1, font, obliqueAngle }).approximate; @@ -365,11 +460,14 @@ test("readDXF gives back each paragraph as toDXF wrote it, in model space, a blo d.layout("SHEET", { paper: "ARCH D" }, () => d.paragraph(long, { at: [1, 20], width: 6, height: 0.125 }), ); + d.paragraph(list(["ONE\tTWO", "THREE"]), { at: [0, -6], width: 4 }); const drawing = d.build(); - const read = await readDXF(toDXF(drawing), { geometry: true }); + const dxf = toDXF(drawing); + assert.ok(dxf.includes("1.^IONE^ITWO"), "a tab is written as ^I"); + const read = await readDXF(dxf, { geometry: true }); assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); const mtexts = read.model.entities!.filter((e) => e.kind === "mtext"); - assert.equal(mtexts.length, 2); + assert.equal(mtexts.length, 3); assert.equal(mtexts[1]!.kind === "mtext" && mtexts[1]!.value, long); }); diff --git a/test/rules.test.ts b/test/rules.test.ts index 4c9f601..bb33c40 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -1280,10 +1280,13 @@ test("a paragraph's height, width, line spacing and codes are checked twice", () assert.throws(() => d.paragraph("NOTE}", { at }), /closes no \{/); // @ts-expect-error: a height inside the value is not laid out yet. assert.throws(() => d.paragraph("\\H2x;NOTE", { at }), /code \\H, which sets the height/); - // @ts-expect-error: nor are a paragraph's indents and tab stops. - assert.throws(() => d.paragraph("\\pxi-3,l3;NOTE", { at }), /code \\p, which sets the indents/); - // @ts-expect-error: nor is a tab. - assert.throws(() => d.paragraph("1.\tNOTE", { at }), /control characters/); + d.paragraph("\\pxi-3,l3,t3;1.\tNOTE", { at }); + // @ts-expect-error: a tab stop that aligns by its right is not laid out yet. + assert.throws(() => d.paragraph("\\pxtr3;1.\tNOTE", { at }), /aligns text by its right/); + // @ts-expect-error: nor is spacing at least a size. + assert.throws(() => d.paragraph("\\psa1;NOTE", { at }), /at least a size apart/); + // @ts-expect-error: an option \p does not know. + assert.throws(() => d.paragraph("\\pz3;NOTE", { at }), /option "z3"/); // @ts-expect-error: nor are columns. assert.throws(() => d.paragraph("ONE\\NTWO", { at }), /code \\N, which starts a new column/); // @ts-expect-error: a code tsdraft does not know. From 0c2dac9754ec3650444f8ffc2938bf3b86385565 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 19 Nov 2026 20:59:38 -0500 Subject: [PATCH 07/35] Raster images: write, read, lint and plot them, clip and frame included Raster images, in R2018 drawings. `d.image(path, at, { pixels, width })` draws a PNG or a JPEG with its lower-left corner at `at`, `width` drawing units wide, and takes `height`, `rotation`, `clip`, `invertClip` and `transparent`. Its path starts from the drawing file's folder, and its `pixels` are the file's, which the new `rasterSize` reads. A clip is two corners of a rectangle along the image's sides, or a polygon, in the drawing's coordinates. `imageFrame: false` on a drawing hides every image's frame. The DXF writer writes each file once as an image definition, with everything CAD programs need to load and draw it. `lint` and the builder refuse an absolute path, pixels that are not two whole numbers above 0, a clip of no size, `invertClip` without a clip and an image in an R12 drawing. `toSVG` and `toPDF` take the files' bytes as `images` and draw each image as CAD programs plot it, clip and frame included, and the PDF embeds each file once. An xref's images take their files from `{ drawing, images }` among `xrefs`. `tsdraft render` and `tsdraft dev` read each image's file from the folder of the drawing file it is in. `readDXF` reads images and lists the file's image definitions. The example sheet has a vicinity map. [docs/images.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/images.md) has the rest. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 10 + CHANGELOG.md | 29 + GUIDE.md | 4 + README.md | 23 + cli/src/worker.ts | 164 +++++- cli/test/fixtures/read/reader-a/read.js | 1 + cli/test/render.test.ts | 76 +++ docs/assets/site-plan-dark.svg | 7 + docs/assets/site-plan-light.svg | 7 + docs/command.md | 11 + docs/format.md | 8 + docs/images.md | 132 +++++ docs/plotting.md | 2 + docs/reading.md | 12 + docs/rules.md | 7 + examples/site-plan.ts | 39 +- examples/vicinity-map.png | Bin 0 -> 1070 bytes scripts/readme-drawing.ts | 5 +- src/blocks.ts | 23 +- src/drawing.ts | 162 +++++- src/dxf-r2018.ts | 188 +++++- src/extents.ts | 19 + src/images.ts | 318 +++++++++++ src/index.ts | 27 + src/lint.ts | 105 +++- src/pdf.ts | 218 ++++++- src/raster.ts | 697 +++++++++++++++++++++++ src/read/check.ts | 30 + src/read/dxf.ts | 71 ++- src/read/entities.ts | 84 +++ src/read/model.ts | 65 ++- src/rules.ts | 138 +++++ src/shape.ts | 22 + src/svg.ts | 211 ++++++- test/format.test.ts | 2 +- test/images.test.ts | 726 ++++++++++++++++++++++++ test/read-agreement.ts | 38 ++ test/read-fuzz.ts | 33 +- test/shape.test.ts | 22 +- 39 files changed, 3690 insertions(+), 46 deletions(-) create mode 100644 docs/images.md create mode 100644 examples/vicinity-map.png create mode 100644 src/images.ts create mode 100644 src/raster.ts create mode 100644 test/images.test.ts diff --git a/AGENTS.md b/AGENTS.md index cfdc0d0..ed206e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -356,6 +356,16 @@ internal. `checkDrawingRead` holds a reader's answer to the model's fields: change both together, and the reading page, `docs/reading.md`. `test/read-fuzz.ts` fuzzes the reader from a seed, and `test/read-agreement.ts` holds a read with geometry to the `Drawing` it came from. +- `src/images.ts` is the one place of where an image's pixels go, its clip as the file holds it + and its frame: the writers, the plots, the extents and the readers all take an image from it. + A file is keyed by its path with `exactKey`, never `Strings`, since a lost key writes a file + twice. A file's bytes are untrusted input: `src/raster.ts` reads them as `src/truetype.ts` reads + a font, and decodes a PNG only up to `RASTER_PIXELS`. A browser drops the colors of a pixel of + no alpha, which the leading CAD app plots for an image not marked transparent, so `toSVG` holds + such a PNG again without its transparency, up to `OPAQUE_PIXELS`; past them it holds the file + as it is and marks the `` `data-opaque`, which `toPDF` reads. That is the one place the + preview and the plot part. A PNG the plot must decode and cannot is drawn by neither, as a file + not given. - `src/pdf.ts` plots layouts to PDF from the pictures `toSVG` draws of them, and decides nothing about a drawing: every rule of what a sheet plots stays in `toSVG`, so the preview and the plot cannot part. It reads the closed set of elements and attributes `toSVG` writes diff --git a/CHANGELOG.md b/CHANGELOG.md index ad62c7f..b4774d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,35 @@ ## Unreleased +- Raster images, in R2018 drawings: `d.image(path, at, { pixels, width })` draws a PNG or a JPEG + with its lower-left corner at `at`, `width` drawing units wide, and `height`, `rotation`, + `clip`, `invertClip` and `transparent` where given; its height defaults to the file's + proportions. `path` starts from the drawing file's folder and the writers write it with `\`. + `pixels` are the file's, which the new `rasterSize` reads from a PNG's or a JPEG's header, and + two images of one file must give it the same. `clip` is two corners of a rectangle along the + image's sides, or a polygon of three points or more, in the drawing's coordinates, and may reach + past the image. Both writers write each file once as an image definition, with its reactor, the + dictionary of images and the drawing's image variables, and the four classes counted, without + which CAD programs draw nothing of an image. `imageFrame: false` on a drawing hides every + image's frame. `lint` and the builder refuse an image in an R12 drawing, an empty or absolute + path or one with `* ? < > | : "`, pixels that are not two whole numbers from 1 to 2^31-1, a + width or height not greater than 0, a clip of fewer than 2 points or more than 10,000, a + rectangle of no size along the image's sides, a polygon of fewer than 3 points that differ, + and `invertClip` with no clip; a literal path is a compile error. `toSVG` and `toPDF` take the + files' bytes as `images`, by the image's path as the drawing gives it, and draw each image as + CAD programs plot it: the file's pixels mapped onto its corners, cut to its clip, opaque unless + it is `transparent`, then its frame, its outline or its clip's, in its pen. The picture holds + each file once, a JPEG without its EXIF and a PNG that plots opaque without its transparency + up to 4,194,304 pixels, and the PDF holds a JPEG and a PNG of no transparency + to show as their own data and decodes any other PNG. An image whose file is not given is its + frame with its path inside it, and one whose file has other pixels is refused with a + `RangeError`. An xref's images take their files from `{ drawing, images }` among `xrefs`, + never from the sheet's. `tsdraft render` and `tsdraft dev` read each image's file from the drawing file's + folder, warn of one missing, and report an error for one of other pixels. `readDXF` reads each + image, with `u` and `v`, the vectors of one of its pixels, and its clip in the world's + coordinates, and lists the file's image definitions in `images`, with how many images name each, + one that none names among them. The example sheet has a vicinity map above its key plan. + [docs/images.md](docs/images.md) describes them. - What a dimension style sets of how its dimensions look. In architectural units, `fraction` stacks the fraction of an inch over a bar, `"stacked"`, or beside a slash, `"diagonal"`, at `fractionScale` of the text's height, as `4'-1` and a stacked `7/16`. `textPlacement: diff --git a/GUIDE.md b/GUIDE.md index 26a396c..54b265d 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -63,6 +63,10 @@ builder draws `line`, `polyline`, `rect`, `circle`, `arc`, `text` and dimensions takes `bulges` to make a side an arc, `width` or `widths` to draw its sides wide, and `radius` to round its corners; `cloud` draws a revision cloud around an outline, which crosses nothing inside it, and `donut` a filled ring or dot. [docs/polylines.md](docs/polylines.md) has them. +`image` draws a PNG or a JPEG at a width in drawing units, with the file's `pixels`, which +`rasterSize` reads, and an optional `clip`; the command reads the file from the drawing file's +folder for the pictures, and warns of one that is missing. +[docs/images.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/images.md) has them. Give an entity an `id` when you will want to find it again: 1 to 64 letters, digits, `.`, `-` and `_`, each used once in a drawing. A diagnostic about the entity carries the id. diff --git a/README.md b/README.md index 69b64aa..14e63ed 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,27 @@ d.paragraph( `measureParagraph` gives its lines and its box. [Paragraphs](docs/paragraphs.md) has the codes it takes and what it refuses. +An image is a PNG or a JPEG drawn at a size in drawing units, such as an aerial under a plan or +a vicinity map on a sheet. The drawing holds the file's path and its pixels, which `rasterSize` +reads, and the plot draws the file from the bytes it is given: + +```ts +import { rasterSize } from "tsdraft"; + +const pixels = rasterSize(readFileSync("aerial.png"))!; +d.image("aerial.png", [0, 0], { + pixels, + width: 400, + clip: [ + [20, 20], + [380, 260], + ], +}); +toPDF(drawing, { images: { "aerial.png": readFileSync("aerial.png") } }); +``` + +[Images](docs/images.md) has clips, frames and transparency, and what `lint` refuses. + A dimension measures between two points and writes what it measures. In the file it is a dimension, which a CAD program measures again when its points move, and a dimension style says how it is drawn: @@ -357,6 +378,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version widths and donuts, how a wide polyline plots, and what `lint` refuses of them. - [Paragraphs](docs/paragraphs.md) covers paragraph text: its width and box, the codes its value takes, the helpers that write them, how it is laid out, and what `lint` refuses. +- [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, + transparency, how the plot draws one, and what `lint` refuses. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. - [Xrefs](docs/xrefs.md) covers references to DWG files: the path, units, a diff --git a/cli/src/worker.ts b/cli/src/worker.ts index cc56583..c8d86d7 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -161,8 +161,11 @@ interface Library { xrefs?: GivenXrefs; layout?: string; view?: readonly [number, number, number, number]; + images?: Readonly>; }, ) => string; + /** A raster file's pixels. A copy of tsdraft from before images has none. */ + readonly rasterSize?: (bytes: Uint8Array) => [number, number] | undefined; /** What is wrong with the text as it plots. A copy of tsdraft from before it has none. */ readonly inspectText?: ( drawing: Drawing, @@ -608,9 +611,28 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { + const read = rasterFiles(library, referenced, at, budget, xref); + diagnostics.push(...read.diagnostics); + return read.images; + }); const fontsOf = fontsIn(library, [shown, ...drawingsOf(given)]); const { svg, min, max } = framed( - library.toSVG(shown, { margin: 0, drawNoPlot: drawNoPlot === true, xrefs: drawn }), + library.toSVG(shown, { + margin: 0, + drawNoPlot: drawNoPlot === true, + xrefs: pictured, + ...images, + }), ); // Each layout's sheet. A copy of tsdraft from before layouts would draw model space for // each, so it draws none. Two layouts of one name are one picture, the first's. @@ -624,7 +646,8 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise): Record { +/** The most bytes the files of a drawing's images are read to, all told. */ +const RASTER_BYTES = 1 << 30; + +/** + * The files of a drawing's images, by each image's path as the drawing gives it, read from the + * folder of the drawing's file, with what is wrong with each: one that is not there, is not a PNG + * or a JPEG, or has other pixels than its image gives it, which the picture then draws as its + * frame and its path, as the leading CAD app draws an image whose file it cannot find. Each is + * tracked, so `tsdraft dev` builds again when one changes. `budget` counts the bytes read for + * every drawing of the build, and once it is spent nothing more is read. `xref` names the xref + * the drawing stands for. Undefined for a copy of tsdraft from before images. + */ +function rasterFiles( + library: Library, + drawing: Drawing, + file: string, + budget: { total: number }, + xref?: string, +): { images: Record | undefined; diagnostics: BuildDiagnostic[] } { + if (typeof library.rasterSize !== "function") return { images: undefined, diagnostics: [] }; + if (budget.total > RASTER_BYTES) return { images: {}, diagnostics: [] }; + const of = xref === undefined ? "" : ` of the xref ${JSON.stringify(xref)}`; + const images: Record = {}; + const diagnostics: BuildDiagnostic[] = []; + const seen = new Set(); + const lists: unknown[] = [ + drawing.entities, + ...(Array.isArray(drawing.layouts) ? drawing.layouts.map((l) => l?.entities) : []), + ...(Array.isArray(drawing.blocks) ? drawing.blocks.map((b) => b?.entities) : []), + ]; + for (const list of lists) { + if (!Array.isArray(list)) continue; + for (const e of list) { + if (typeof e !== "object" || e === null || e.kind !== "image") continue; + const { path, pixels } = e as { path?: unknown; pixels?: unknown }; + if ( + typeof path !== "string" || + seen.has(path) || + isAbsolute(path) || + /^[A-Za-z]:/.test(path) + ) { + continue; + } + seen.add(path); + const at = join(dirname(file), path.replaceAll("\\", "/")); + // A link is watched beside the file it leads to, whose change it does not see. + track(at, fileVersion(at)); + try { + const real = realpathSync(at); + if (real !== at) track(real, fileVersion(real)); + } catch { + // A missing file has no file behind it. + } + let bytes: Uint8Array; + try { + bytes = new Uint8Array(readFileSync(at)); + } catch { + diagnostics.push({ + rule: "image", + severity: "warning", + message: `The file of the image ${JSON.stringify(path)}${of} is not at ${at}, so the pictures draw its frame and its path, as the leading CAD app draws an image whose file it cannot find`, + }); + continue; + } + budget.total += bytes.length; + if (budget.total > RASTER_BYTES) { + diagnostics.push({ + rule: "image", + severity: "warning", + message: `The files of the drawing's images come to more than ${RASTER_BYTES} bytes, so the pictures draw the image ${JSON.stringify(path)}${of} and those after it as frames`, + }); + return { images, diagnostics }; + } + const size = library.rasterSize(bytes); + if (size === undefined) { + diagnostics.push({ + rule: "image", + severity: "warning", + message: `The file of the image ${JSON.stringify(path)}${of} is not a PNG or a JPEG the pictures can draw, so they draw its frame and its path`, + }); + continue; + } + if (!Array.isArray(pixels) || pixels[0] !== size[0] || pixels[1] !== size[1]) { + diagnostics.push({ + rule: "image", + severity: "error", + message: `The file of the image ${JSON.stringify(path)}${of} is ${size[0]} by ${size[1]} pixels, and the drawing gives it ${JSON.stringify(pixels)}: the leading CAD app would plot it at the wrong size. Give it the file's pixels, which rasterSize reads`, + }); + continue; + } + images[path] = bytes; + } + } + return { images, diagnostics }; +} + +/** + * What the pictures are given for the xrefs: each drawing given with no lint error, and with + * `files`, the files of its images, read from the folder of the xref's file, which `folder`, the + * folder of the drawing that references it, starts its path from. + */ +function drawnOf( + given: ReadonlyMap, + folder = "", + files?: (drawing: Drawing, file: string, xref: string) => Record | undefined, +): Record { return Object.fromEntries( - [...given.values()] - .filter((g) => g.errors.length === 0) - .map((g) => [ - g.name, - g.nested.size > 0 ? { drawing: g.drawing, xrefs: drawnOf(g.nested) } : g.drawing, - ]), + [...given] + .filter(([, g]) => g.errors.length === 0) + .map(([xref, g]) => { + const path = typeof xref.path === "string" ? xref.path.replaceAll("\\", "/") : ""; + const at = isAbsolute(path) ? path : join(folder, path); + // A path with a drive, which lint refuses, names no folder here. + const found = path !== "" && !/^[A-Za-z]:/.test(path); + const images = files && !g.preview && found ? files(g.drawing, at, g.name) : undefined; + const nested = g.nested.size > 0 ? drawnOf(g.nested, dirname(at), files) : undefined; + return [ + g.name, + nested === undefined && images === undefined + ? g.drawing + : { + drawing: g.drawing, + ...(nested === undefined ? {} : { xrefs: nested }), + ...(images === undefined ? {} : { images }), + }, + ]; + }), ); } diff --git a/cli/test/fixtures/read/reader-a/read.js b/cli/test/fixtures/read/reader-a/read.js index 1aeb005..aa692bc 100644 --- a/cli/test/fixtures/read/reader-a/read.js +++ b/cli/test/fixtures/read/reader-a/read.js @@ -47,6 +47,7 @@ export async function readDrawingFile(chunks, name) { dimensionStyles: [], blocks: [], xrefs: [], + images: [], model: { census: { layers: {}, diff --git a/cli/test/render.test.ts b/cli/test/render.test.ts index ed14f1d..6cf38fd 100644 --- a/cli/test/render.test.ts +++ b/cli/test/render.test.ts @@ -15,6 +15,7 @@ import { import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { deflateSync } from "node:zlib"; import { after, test } from "node:test"; import { BUILT_IN_STANDARD, pdfFace } from "tsdraft"; import { faces } from "../src/fonts.ts"; @@ -1603,3 +1604,78 @@ test("dev plots the set and a sheet on request, and no picture that draws what d ["--draw-no-plot"], ); }); + +/** A PNG of one gray, `width` by `height`. */ +function grayPng(width: number, height: number): Uint8Array { + const crc = (bytes: Uint8Array): number => { + let c = 0xffffffff; + for (const b of bytes) { + c ^= b; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + return (c ^ 0xffffffff) >>> 0; + }; + const chunk = (type: string, data: Uint8Array): Buffer => { + const body = Buffer.concat([Buffer.from(type, "latin1"), data]); + const out = Buffer.alloc(body.length + 8); + out.writeUInt32BE(data.length, 0); + body.copy(out, 4); + out.writeUInt32BE(crc(body), body.length + 4); + return out; + }; + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header.set([8, 0, 0, 0, 0], 8); + const rows = Buffer.alloc((width + 1) * height, 128); + for (let y = 0; y < height; y++) rows[y * (width + 1)] = 0; + return Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + chunk("IHDR", header), + chunk("IDAT", deflateSync(rows)), + chunk("IEND", new Uint8Array()), + ]); +} + +test("render reads each image's file beside its drawing, an xref's beside the xref's file", () => { + const dir = realpathSync(tempDir()); + mkdirSync(join(dir, "sheets")); + mkdirSync(join(dir, "civil")); + // One name in both folders, of other sizes: each drawing draws its own. + writeFileSync(join(dir, "sheets", "aerial.png"), grayPng(2, 2)); + writeFileSync(join(dir, "civil", "aerial.png"), grayPng(3, 3)); + const image = { + kind: "image", + layer: "0", + path: "aerial.png", + at: [0, 0], + width: 10, + height: 10, + }; + const drawing = (pixels: number, more: object = {}) => ({ + format: 0, + units: "ft", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [{ ...image, pixels: [pixels, pixels] }], + ...more, + }); + const base = drawing(3); + const sheet = drawing(2, { + xrefs: [{ name: "BASE", path: "../civil/base.dwg" }], + entities: [ + { ...image, pixels: [2, 2] }, + { kind: "insert", layer: "0", block: "BASE", at: [20, 0] }, + ], + }); + const plan = join(dir, "sheets", "plan.ts"); + writeFileSync( + plan, + `export const xrefs = { BASE: ${JSON.stringify(base)} };\nexport default ${JSON.stringify(sheet)};\n`, + ); + const { state } = render(plan); + assert.deepEqual(state.diagnostics, []); + const svg = readFileSync(state.outputs.svg!, "utf8"); + assert.match(svg, /data-pixels="2 2"/); + assert.match(svg, /data-pixels="3 3"/); +}); diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index c992dc0..fdc77ad 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -1,4 +1,5 @@ + @@ -249,6 +250,12 @@ KEY PLAN SCALE: 1" = 40' + + + + VICINITY MAP + NOT TO SCALE + N diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index 2097b78..c568fce 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -1,4 +1,5 @@ + @@ -249,6 +250,12 @@ KEY PLAN SCALE: 1" = 40' + + + + VICINITY MAP + NOT TO SCALE + N diff --git a/docs/command.md b/docs/command.md index ccc5c85..57a9060 100644 --- a/docs/command.md +++ b/docs/command.md @@ -125,6 +125,17 @@ Give `--view` the `bounds` of a diagnostic, a little larger, to see what the dia about, and read a sheet's title block and notes with it. `tsdraft dev` has no such flag: its page pans and zooms. +## Images + +The pictures and the PDF draw each image from its file, which the command reads from the folder +of the drawing file by the image's path, `\` and `/` alike, once a build, up to 1 GB in all. A +file that is missing, or is not a PNG or a JPEG, gives an `image` warning, and the pictures draw +the image's frame with its path inside it, as a CAD program draws an image whose file it cannot +find. A file whose pixels are not the ones the image gives it is an `image` error, and its frame is +drawn the same way. An xref's images are read from the folder of its file, which its path starts +from the drawing file's. `tsdraft dev` builds again when an image's file changes. +[Images](images.md#plotting) has what a picture holds of one. + ## The JSON `BuildState` in [`cli/src/state.ts`](../cli/src/state.ts) documents each field, and `schema`, diff --git a/docs/format.md b/docs/format.md index 0a31ccb..1ce28b7 100644 --- a/docs/format.md +++ b/docs/format.md @@ -85,6 +85,14 @@ the `linetype` and `lineweight` of every entity. Its value holds `\P` for each p A drawing with no paragraph has the JSON it had before paragraphs existed. [Paragraphs](paragraphs.md) describes them. +An image is an entity of kind `"image"`, in `drawing.entities`, a block's `entities` or a layout's +`entities`, with its `layer`, its file's `path` and `pixels`, its lower-left corner `at`, its +`width` and `height` in drawing units, and where they are set a `rotation`, a `clip`, a list of +points, `invertClip` and `transparent`, each `true`, and the `linetype` and `lineweight` of every +entity, which its frame is drawn in. `imageFrame: false` on the drawing hides every image's frame. +A drawing with no image has the JSON it had before images existed. [Images](images.md) describes +them. + A drawing written by hand needs `format: 0` too. `lint` reports a drawing without it, or with another version, under the rule `format`, and `toDXF` refuses to write it. `lint` takes any plain data and never throws: a list that is not an array, an entity of an unknown `kind`, a diff --git a/docs/images.md b/docs/images.md new file mode 100644 index 0000000..febe563 --- /dev/null +++ b/docs/images.md @@ -0,0 +1,132 @@ +# Images + +An image is a raster file, a PNG or a JPEG, drawn at a size in drawing units: an aerial under a +site plan, a vicinity map, a logo in a title block, a standard detail kept as a picture. The +drawing holds the file's path and its size in pixels, and nothing of what it shows. CAD programs +load the file each time they open the drawing. In the file it is an `IMAGE`, with the file's +definition, an `IMAGEDEF`, which every image of that file shares. + +Images are R2018 only. The builder and `lint` refuse one in an R12 drawing. + +## Drawing one + +`d.image(path, at, options)` places the file at `path` with its lower-left corner at `at`, `width` +drawing units wide. `pixels` are the file's own width and height in pixels, which `rasterSize` +reads from its bytes. Its height defaults to the width times the file's height over its width, +so its pixels are square: + +```ts +import { readFileSync } from "node:fs"; +import { createDrawing, rasterSize } from "tsdraft"; + +const pixels = rasterSize(readFileSync("aerial.png"))!; +const d = createDrawing({ units: "ft" }); +d.layer("C-IMAG", { color: 8 }, () => { + d.image("aerial.png", [-50, -40], { pixels, width: 400 }); +}); +``` + +`path` starts from the folder of the drawing's file, with `\` or `/` between folders, such as +`"aerial.png"` or `"../survey/aerial.png"`. The writers write it with `\`, as CAD programs save +one. An absolute path is refused: a CAD program looks for its file there and nowhere else, so on +another machine it finds none. + +`pixels` must be the file's. A CAD program draws the file's own pixels at the size each pixel has +in the drawing, so an image whose file has other pixels plots at the wrong size, and cut. +`toSVG`, `toPDF` and `tsdraft render` refuse such a file. + +`height` stretches the image, and `rotation` turns it about its lower-left corner, in degrees +counterclockwise. In a block, an insert's scale and rotation place it as they place the rest of +the block, and a negative scale mirrors it. + +Each file is written once, as one definition that every image of it names, with `\` and `/` taken +as one. Two images of one file must give it the same `pixels`. The definition is named by the +file's name without its extension, with a number after it where another file took the name +first. A drawing cannot hold a definition no image uses: [reading](reading.md) has the ones a +file holds. + +## Clipping + +`clip` hides what lies outside an outline, in the drawing's coordinates. Two points are opposite +corners of a rectangle along the image's sides; three or more are a polygon, which the writers +close. Points outside the image are kept: the image shows inside both its outline and the clip. + +```ts +// The part of the aerial around the lot. +d.image("aerial.png", [-50, -40], { + pixels, + width: 400, + clip: [ + [-20, -20], + [180, 160], + ], +}); +``` + +On a turned image the two corners are taken along its sides, so they name a rectangle turned with +it. `invertClip: true` shows the image outside the clip and hides what the clip holds. + +A CAD program paints the part of a clip that reaches past its image white, which hides what is +drawn before the image there. `toSVG` and `toPDF` leave that part unpainted. + +## Frames, transparency and order + +Each image has a frame: its outline, or its clip's, past the image too, or the hole alone for an +inverted clip, drawn in the image's layer, color and lineweight after the image. `imageFrame: +false` on the drawing hides every frame, in the plot too, as a sheet with a logo or an aerial +wants. + +A PNG's transparent pixels show what is behind them only with `transparent: true`. Without it the +image is opaque, and a transparent pixel plots in the color the file gives it. A JPEG has no +transparency. + +An image hides what is drawn before it and is hidden by what is drawn after it, in the order of +the drawing. Draw an aerial first, and the linework over it. + +## Plotting + +`toSVG` and `toPDF` draw an image from its file's bytes, given as `images`, by the image's path +exactly as the drawing gives it: + +```ts +const images = { "aerial.png": new Uint8Array(readFileSync("aerial.png")) }; +toSVG(drawing, { layout: "C-101", images }); +toPDF(drawing, { images, deflate: zlib.deflateSync }); +``` + +The picture holds each file once, as a data URL, and the PDF holds it once as it is: a JPEG, and a +PNG with no transparency to show, as their own data, and any other PNG decoded, with its +transparency as a soft mask. A browser drops the colors of a pixel with no alpha, which CAD +programs plot for an image not marked `transparent`, so the picture holds a PNG with transparency +again without it for such an image: the file without its `tRNS` chunk, or for an alpha channel +its colors decoded and stored uncompressed. A PNG with an alpha channel of more than 4,194,304 +pixels is held as it is instead, its pixels with no alpha see-through in the picture, and the PDF +plots it opaque. A JPEG is drawn as its pixels are stored, whatever its EXIF says, as +CAD programs plot it. An image whose file is not given, or is neither a PNG nor a JPEG, is drawn +as a CAD program draws one whose file it cannot find: its frame, with its path written inside it. + +An xref's images take their files from the xref's own, whose paths start from its drawing's +folder, never from the sheet's: give them with the drawing, as `{ drawing, images }` among +`xrefs`. Without them, an xref's images are drawn as images whose files are missing. + +```ts +toSVG(sheet, { images, xrefs: { BASE: { drawing: base, images: baseImages } } }); +``` + +`tsdraft render` and `tsdraft dev` read each image's file from the drawing file's folder, and warn +of one that is missing. Its pixels must be the file's, or the build reports an error and draws +the frame. + +## What lint refuses + +- A path that is empty, absolute, longer than 32,000 characters, or that holds `* ? < > | : "`, a + multibyte escape or a character a text cannot hold. +- `pixels` that are not two whole numbers from 1 to 2,147,483,647, and two images of one file with + other pixels. +- A width or a height that is not greater than 0 as written. +- A clip of fewer than 2 points or more than 10,000, a rectangle of no width or no height in the + image's axes, a polygon of fewer than 3 points that differ, and `invertClip` with no clip. +- An image in an R12 drawing. + +Brightness, contrast and fade are always written as CAD programs set them for a new image: 50, 50 +and 0. A file that sets other values reads them, and its plot draws the image without them. diff --git a/docs/plotting.md b/docs/plotting.md index 080d8be..5705a23 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -63,6 +63,8 @@ preview shows it: does. - A wide side of a polyline is filled, at its width whatever its pen, with its joins and its dashes as [How it plots](polylines.md#how-it-plots) says. +- An image is drawn from its file's bytes, given as `images`, clipped to its clip, with its frame + in its pen, and the PDF holds each file once, as [Plotting](images.md#plotting) says. - Each layer is a layer of the PDF too, by the name the picture gives it, `XREF|LAYER` for a layer of an xref, so a PDF viewer lists the layers and can hide one. - Each page has a bookmark and a page label with its layout's name. diff --git a/docs/reading.md b/docs/reading.md index e521777..725c835 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -67,6 +67,9 @@ states and keeps each object's handle, and it keeps going past what it does not The pictures the leading CAD app makes for dimensions, the blocks named `*D` and a number, are kept by a read with `geometry` alone. - `xrefs`: each with its name, its path as the file holds it, and whether it is an overlay. +- `images`: each image definition of the file's dictionary of them, with its name, its path as + the file holds it, the pixels it states, whether it is loaded, and how many images name it. One + no image uses is kept, as CAD programs keep it through a save and a purge. - `layouts`: each with its paper, its plotter, its plot style table, its plot's rotation, its viewports and its inserts. A viewport has its rectangle on the paper, the center and height of the model space it shows, `ratio`, which is paper units per model unit, its twist, and @@ -120,6 +123,15 @@ A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers its tip, the point where the shafts meet, the landing's direction and length, its note, where the note is held, and the note's height and style. Any other is counted under `other`. - `solid`: three or four corners, filled, as a dimension draws an arrowhead. +- `image`: a raster image, with its definition's `path` and the handle of the `definition`, the + `pixels` it states, its lower-left corner `at`, and `u` and `v`, the vectors of one of its pixels + along its bottom and up its side, which a mirrored or slanted image has too. `clip` is its clip + boundary, unless the file holds the whole image's with its clip off and not inverted, in the + world's coordinates: two opposite corners of a rectangle along its sides, as the file holds them, + or a polygon without its first point again. `invertClip`, `transparent`, `hidden` for one the + file says not to show and `unclipped` for one it says not to clip say so, and `brightness`, + `contrast` and `fade` are left out at 50, 50 and 0. An image out of the plane is counted under + `other`. Each keeps the pen it sets for itself, each part left out when it is ByLayer: `color`, an index with 0 for ByBlock, `trueColor` as `0xRRGGBB`, `linetype`, `lineweight` in hundredths of a diff --git a/docs/rules.md b/docs/rules.md index 071c6a1..6f17e71 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -46,6 +46,13 @@ it would take `1e+100` for `1e+10` and report nothing. it. So are a stacked part of other characters than digits and capitals with `.`, `,`, `+` or `-`, or spaces, and a stack in underlined or struck-through characters. [Paragraphs](paragraphs.md#what-lint-refuses) has the rest. +- An image is R2018 only. Its path is not empty, starts from the folder of the drawing's file and + holds no `* ? < > | : "`, since the leading CAD app finds the file of an absolute path only + there, its `pixels` are the file's, two whole numbers from 1 to 2,147,483,647, and two images of + one file give it the same pixels. Its width and height are greater than 0 as written. A clip is + two corners of a rectangle of some width and height along the image's sides, or a polygon of 3 + points that differ, at most 10,000 in all, and `invertClip` needs a clip. + [Images](images.md#what-lint-refuses) has the rest. - Arc angles are stored from 0 up to 360, so -90 becomes 270. An arc cannot come within 0.000001 degrees of a full turn, because its two angles would be written the same and the leading CAD app holds such an arc as having no length. Draw a diff --git a/examples/site-plan.ts b/examples/site-plan.ts index 1172d3b..197150f 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -77,7 +77,7 @@ // call, the project, the date and who drew and checked it from `createDrawing`'s `fields`, the // number from the layout's name and the scale from the viewport. In CAD each field stays an // attribute. -import { mkdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { BUILT_IN_STANDARD, checkIntent, @@ -87,6 +87,7 @@ import { list, measureText, paragraphFormat, + rasterSize, toDXF, toSVG, type Drawing, @@ -107,11 +108,21 @@ export const standard = defineStandard({ layers: { "V-TREE": { color: 3, pen: "fine", discipline: "V" }, "C-ANNO-REVS": { color: 1, pen: "medium", discipline: "C" }, + "C-ANNO-IMAG": { color: 8, pen: "fine", discipline: "C" }, }, leaderStyles: { notes: { role: "note", arrowSize: 1 / 8, landing: 1 / 8, gap: 1 / 16 } }, defaultLeaderStyle: "notes", }); +/** + * The raster files the sheet's images show, by the path each image gives, from this file's + * folder: the vicinity map, a PNG. `rasterSize` reads its pixels, which the image must state. + */ +export const images = { + "vicinity-map.png": new Uint8Array(readFileSync(new URL("./vicinity-map.png", import.meta.url))), +}; +const vicinityPixels = rasterSize(images["vicinity-map.png"])!; + /** A text role of the standard, which gives a text its text style and the height it plots at. */ type Role = keyof typeof standard.textRoles; const roles = standard.textRoles; @@ -626,6 +637,25 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee attributes: { VIEW_TITLE: "KEY PLAN", VIEW_SCALE: `SCALE: ${keyView.label}` }, }); }); + + // The vicinity map, a raster image above the key plan, as wide as it and at the image's own + // proportions, with its title under it. CAD programs load the file each time they open the + // drawing, by its path from the drawing's folder. + const mapWidth = keySide; + const mapHeight = (mapWidth * vicinityPixels[1]) / vicinityPixels[0]; + const mapTitle = keyPlan.top + 1; + d.layer("C-ANNO-IMAG", () => + d.image("vicinity-map.png", [keyPlan.left, mapTitle + 3 / 4], { + pixels: vicinityPixels, + width: mapWidth, + height: mapHeight, + }), + ); + d.layer("C-ANNO-TITL", () => + d.insert("VIEW TITLE", [keyTitleX, mapTitle], { + attributes: { VIEW_TITLE: "VICINITY MAP", VIEW_SCALE: "NOT TO SCALE" }, + }), + ); d.layer("C-ANNO-SYMB", () => { // The plan's viewport is not turned, so its north is up the sheet. The key plan's north // arrow is turned as far as its view. @@ -827,8 +857,11 @@ if (import.meta.main) { const outDir = new URL("./out/", import.meta.url); mkdirSync(outDir, { recursive: true }); writeFileSync(new URL("site-plan.dxf", outDir), toDXF(drawing)); - writeFileSync(new URL("site-plan.svg", outDir), toSVG(drawing)); - writeFileSync(new URL("site-plan-sheet.svg", outDir), toSVG(drawing, { layout: example.layout })); + writeFileSync(new URL("site-plan.svg", outDir), toSVG(drawing, { images })); + writeFileSync( + new URL("site-plan-sheet.svg", outDir), + toSVG(drawing, { layout: example.layout, images }), + ); const onSheet = drawing.layouts?.[0]?.entities.length ?? 0; console.log( `Wrote ${drawing.entities.length} entities in model space and ${onSheet} on the sheet, ` + diff --git a/examples/vicinity-map.png b/examples/vicinity-map.png new file mode 100644 index 0000000000000000000000000000000000000000..d8008ee9e6ea709d89ff976f4a1a65ce0dba9c90 GIT binary patch literal 1070 zcmeAS@N?(olHy`uVBq!ia0y~yU~~YoKX5PuNw?3wkw8i)z$e7@|Ns9L6%}V69)9uc z;Ry|mY5VSIvmbcCz`%Un)5S5QV$R#y4})$S2(T?&d++~L>)=~L8+7OI4g1nqUa$Y@ zF5hH}wmo|~fZ)X1%Day1-|yY?@5Sf)zi&QYH;-{)y2A@efhx8ZYB4)O_V{}Kmvh@C zUcY?)yQBOwP%!VV59>vb=_MWTUiZ7^e8UA}g)clDw#-gMG9R(~e8+}efZ)lpCH4Hu zcf0pr_D59{zvQy5AOuWIUSj{&R}2errFY`q}B?%bsmbb9iLREVSN~nd!Y@{A|1X#rk)q$=Kw7yu6)r z$E9_*3*YY9D!@;HSZ#FPfvEj2xtFu)Je$40AmhOIx|iJPY&Gx2_ZOrb z_+ImqTb-@ujrjf#PZ=%cf1M1R^;h6q@{ImO`?kLl-<*GZ`*`f;dtaNHU$Vb!drIEF znfvq6LvEY?YWrV3yWX8-p3c9Xr{c+hsqOV_YvgzQ`f#P;DRcO5$qh9Rs_dD?`0t!Z zKk%q=_FtX|tAgG08M)cF`PnnSlfUsc{ebPp`R5y~lWxCGKQQmcx8ITl(QBR-QEm`)=>n^h__1=<(|3^}HZtgzwNsWC^-o!{q z?l{Y(0Za!<-&OurOT3Kxr{1&bxw|EGvkx#Y`t$veo{-GuIWe@z9#{Y{c)I$ztaD0e F0sy{+3`PI| literal 0 HcmV?d00001 diff --git a/scripts/readme-drawing.ts b/scripts/readme-drawing.ts index ea23790..c6196d5 100644 --- a/scripts/readme-drawing.ts +++ b/scripts/readme-drawing.ts @@ -6,7 +6,7 @@ import { execFileSync } from "node:child_process"; import { readFileSync, writeFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import planSet, { xrefs as planSetXrefs } from "../examples/plan-set/set.ts"; -import { sitePlan } from "../examples/site-plan.ts"; +import { images, sitePlan } from "../examples/site-plan.ts"; import { toSVG } from "../src/index.ts"; const root = fileURLToPath(new URL("..", import.meta.url)); @@ -39,7 +39,7 @@ interface Picture { // The site plan's picture is its layout, as toSVG draws the sheet: paper units, each line as // wide as its lineweight, and dashes as long as they plot. const site = sitePlan(); -const sitePicture = toSVG(site.drawing, { layout: site.drawing.layouts![0]!.name }); +const sitePicture = toSVG(site.drawing, { layout: site.drawing.layouts![0]!.name, images }); // The permit set's pictures are two of its sheets, each with the border its xref draws. const planSetSheet = (layout: string) => toSVG(planSet, { layout, xrefs: planSetXrefs }); @@ -90,6 +90,7 @@ const pictures: Picture[] = [ "C-ANNO-TEXT": "line", "C-ANNO-SYMB": "line", "C-ANNO-TITL": "line", + "C-ANNO-IMAG": "muted", "G-ANNO-TTLB": "line", }, }, diff --git a/src/blocks.ts b/src/blocks.ts index 7d7c1bf..a31e1a2 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -332,6 +332,12 @@ export function attributeText(insert: Insert, definition: AttributeDefinition): export interface XrefDrawing { readonly drawing: Drawing; readonly xrefs?: XrefDrawings; + /** + * The bytes of each raster file the drawing's images show, by the image's path as the drawing + * gives it, which starts from the drawing's own folder. Without it, its images are drawn as + * images whose files are missing. + */ + readonly images?: Readonly>; } /** @@ -351,6 +357,8 @@ export interface Referenced { readonly blocks: ReadonlyMap; /** The drawings its attachments stand for, by `layerKey` of each xref's name. */ readonly xrefs: ReadonlyMap; + /** The files of its images, as its `XrefDrawing` gives them. */ + readonly images?: unknown; } /** A layer by its name: one of the drawing's own, or one of a drawing it references. */ @@ -400,7 +408,15 @@ export function drawnXrefs(drawing: Drawing, xrefs: XrefDrawings | undefined): X Object.fromEntries( [...tree.values()].map((r) => [ r.name, - r.xrefs.size > 0 ? { drawing: r.drawing, xrefs: out(r.xrefs) } : r.drawing, + r.xrefs.size > 0 || r.images !== undefined + ? { + drawing: r.drawing, + ...(r.xrefs.size > 0 ? { xrefs: out(r.xrefs) } : {}), + ...(r.images === undefined + ? {} + : { images: r.images as Readonly> }), + } + : r.drawing, ]), ); return out(referencedTree(drawing, xrefs, () => NO_BLOCKS).xrefs); @@ -539,9 +555,11 @@ export function referencedTree( const nested = typeof value === "object" && value !== null && "drawing" in value; const found: unknown = nested ? (value as XrefDrawing).drawing : value; const inner: unknown = nested ? (value as XrefDrawing).xrefs : undefined; + const files: unknown = nested ? (value as XrefDrawing).images : undefined; if ( !drawingLike(found) || - (inner !== undefined && (typeof inner !== "object" || inner === null)) + (inner !== undefined && (typeof inner !== "object" || inner === null)) || + (files !== undefined && (typeof files !== "object" || files === null)) ) { note("shape", chain); continue; @@ -563,6 +581,7 @@ export function referencedTree( drawing: referenced, blocks: held, xrefs: into ?? NO_XREFS, + ...(files === undefined ? {} : { images: files }), }); if (into) { queue.push({ diff --git a/src/drawing.ts b/src/drawing.ts index 5288293..3e252a7 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -52,6 +52,7 @@ import { } from "./papers.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; import { arcsAlong, cloud, donut, MAX_CLOUD_ARCS, rounded } from "./polylines.ts"; +import { imageVectors } from "./images.ts"; import { canonical } from "./json.ts"; import { DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; import { @@ -152,6 +153,12 @@ import { type PolylineWidth, type R12Leaders, type R12Polylines, + type R12Images, + type ImagePath, + imageClipProblem, + imagePathProblem, + imagePixelsProblem, + IMAGE_INVERT_WITHOUT_CLIP, type R12Paragraphs, type LineSpacing, type ParagraphValue, @@ -595,6 +602,45 @@ export interface Leader extends Placed { readonly gap?: number; } +/** + * A raster image: a PNG or a JPEG file, which the leading CAD app loads each time it opens the + * drawing and draws at its size in drawing units. The drawing holds the file's path and its size + * in pixels, and nothing of what it shows. Each file the drawing's images name is written as one + * definition of it. R2018 only. + */ +export interface Image extends EntityBase { + readonly kind: "image"; + /** + * The file's path from the folder of this drawing's file, with `\` or `/` between folders, such + * as `"aerial.png"` or `"..\\images\\aerial.png"`. + */ + readonly path: string; + /** + * The file's width and height in pixels, as the file holds them, which `rasterSize` reads. The + * leading CAD app draws the file's own pixels at the size each pixel has here, so an image of a + * file with other pixels plots at the wrong size. + */ + readonly pixels: readonly [width: number, height: number]; + /** Where its lower-left corner goes. */ + readonly at: Point; + /** How wide it is along its bottom edge, in drawing units. */ + readonly width: number; + /** How high it is up its side, in drawing units. */ + readonly height: number; + /** Degrees counterclockwise. Defaults to 0. */ + readonly rotation?: number; + /** + * The outline that clips it, in the drawing's coordinates: two opposite corners of a rectangle + * along its sides, or the points of a polygon, three or more. What lies outside the clip or + * outside the image is not shown. + */ + readonly clip?: readonly Point[]; + /** True to show the image outside its clip and hide what the clip holds. */ + readonly invertClip?: boolean; + /** True to show what is behind the transparent pixels of a PNG. Otherwise it is opaque. */ + readonly transparent?: boolean; +} + export type Entity = | Line | Polyline @@ -605,7 +651,8 @@ export type Entity = | Insert | LinearDimension | AlignedDimension - | Leader; + | Leader + | Image; /** * A leader style: how the leaders that name it are drawn. Its sizes are the sizes its leaders @@ -869,6 +916,11 @@ export interface Drawing { readonly dimensionStyles?: readonly DimensionStyle[]; /** The leader styles that leaders name. */ readonly leaderStyles?: readonly LeaderStyle[]; + /** + * Whether each image's frame shows and plots: its outline, or its clip's, in its pen. Defaults + * to true, as the leading CAD app has it. A sheet with a logo or an aerial wants false. + */ + readonly imageFrame?: boolean; } /** @@ -1180,6 +1232,42 @@ export interface DonutOptions< readonly inside?: DonutHole; } +/** + * The options of `image()`: the file's pixels, the image's size and turn, its clip, and the + * options of every entity. + * + * @typeParam IW - The width as written. + * @typeParam IH - The height as written. + */ +export interface ImageOptions< + IW extends number = number, + IH extends number = number, + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, +> extends EntityOptions<"R2018", T, W, L, I, Z, P> { + /** The file's width and height in pixels, which `rasterSize` reads from its bytes. */ + readonly pixels: readonly [width: number, height: number]; + /** How wide the image is along its bottom edge, in drawing units. */ + readonly width: Positive; + /** How high it is. Defaults to the width times the file's height over its width. */ + readonly height?: Positive; + /** Degrees counterclockwise. Defaults to 0. */ + readonly rotation?: number; + /** + * The outline that clips it, in the drawing's coordinates: two opposite corners of a rectangle + * along its sides, or the points of a polygon, three or more. + */ + readonly clip?: readonly Point[]; + /** True to show the image outside its clip and hide what the clip holds. */ + readonly invertClip?: boolean; + /** True to show what is behind the transparent pixels of a PNG. */ + readonly transparent?: boolean; +} + /** A text style to define: a `TextStyle`, checked. */ export interface TextStyleDefinition< N extends string = string, @@ -2517,6 +2605,78 @@ export class DrawingBuilder< }); } + /** + * A raster image: the PNG or JPEG file at `path`, from the folder of this drawing's file, with + * its lower-left corner at `at`, `width` drawing units wide. `pixels` are the file's own, which + * `rasterSize` reads, and its height defaults to the width times the file's height over its + * width. `clip` hides what lies outside two corners of a rectangle along its sides or a + * polygon, in the drawing's coordinates. R2018 only. + * + * ```ts + * d.image("aerial.png", [0, 0], { pixels: [4000, 3000], width: 400 }); + * ``` + */ + image< + const F extends string, + IW extends number, + IH extends number = number, + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + >( + path: V extends "R12" ? R12Images : ImagePath, + at: Point, + options: V extends "R12" ? R12Images : ImageOptions, + ): this { + const o = options as unknown as ImageOptions; + return this.#add(DrawingBuilder.prototype.image, o, () => { + if (this.dxf === "R12") refuse("image", R12_ONLY.images); + const pathProblem = imagePathProblem(path); + if (pathProblem) refuse("image", pathProblem); + const pixelsProblem = imagePixelsProblem(o.pixels); + if (pixelsProblem) refuse("image", `pixels: ${pixelsProblem}`); + const [w, h] = o.pixels; + const width = positive(o.width, "width"); + const height = o.height === undefined ? width * (h / w) : positive(o.height, "height"); + if (o.height === undefined && sizeProblem(height)) { + refuse("geometry", `height: ${sizeProblem(height)}`); + } + const rotation = + o.rotation === undefined ? undefined : kept(num(o.rotation, "rotation"), "rotation"); + const image: Image = { + kind: "image", + layer: this.#current, + path: path as string, + pixels: [w, h], + at: pt(at), + width, + height, + ...(rotation === undefined ? {} : { rotation }), + }; + if (o.clip !== undefined) { + const [u, v] = imageVectors(image); + const clipProblem = imageClipProblem(o.clip, image.at, u, v); + if (clipProblem) refuse("image", `clip: ${clipProblem}`); + } else if (o.invertClip === true) refuse("image", IMAGE_INVERT_WITHOUT_CLIP); + for (const [field, value] of [ + ["invertClip", o.invertClip], + ["transparent", o.transparent], + ] as const) { + if (value !== undefined && typeof value !== "boolean") { + refuse("image", `${field} must be true or false`); + } + } + return { + ...image, + ...(o.clip === undefined ? {} : { clip: o.clip.map(pt) }), + ...(o.invertClip === true ? { invertClip: true } : {}), + ...(o.transparent === true ? { transparent: true } : {}), + }; + }); + } + /** * A polyline of the current layer through `points`, with what `given` says of its sides, once * the sides are checked. A radius rounds the corners first. diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 5550f78..3311a0b 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -35,6 +35,7 @@ import type { DimensionStyle, Drawing, Entity, + Image, Insert, Layout, Leader, @@ -47,6 +48,23 @@ import type { Viewport, } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; +import { + drawingImages, + IMAGE_DICTIONARY, + IMAGE_VARIABLES, + exactKey, + imageClip, + imageDefinitions, + imageDictionaryHandle, + imagePathKey, + imageReactorHandle, + imageVectors, + RASTER_UNITS, + rasterVariablesHandle, + writtenImagePath, + type ImageDefinition, +} from "./images.ts"; +import { isUnits } from "./units.ts"; import { checksLimit, DrawingError } from "./lint.ts"; import { layoutBlockName, @@ -83,7 +101,7 @@ import { validLeaderStyleHandle, } from "./leaders.ts"; import { entityLinetype, layerLinetype, lineweightCode, patternLength } from "./linetypes.ts"; -import { shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; +import { idKey, shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; /** `$INSUNITS` codes from the DXF Reference. */ const INSUNITS: Record = { in: 1, ft: 2, mm: 4, cm: 5, m: 6 }; @@ -162,6 +180,14 @@ export function toDXFR2018( // Keyed as style names are compared, so a leader that names `notes` takes the style `NOTES`. const leaderStylesByKey = new Map(leaderStyles.map((style) => [layerKey(style.name), style])); const leaderArrowheads = leaderArrowheadsWithBlocks(leaderStyles); + // Each file the images show is one definition, and each image has a reactor of its own. + const images = [...drawingImages(drawing)]; + const definitions = imageDefinitions(images); + // Keyed exactly, since a path may be long. + const definitionOf = new Map(); + for (const definition of definitions) + definitionOf.set(exactKey(imagePathKey(definition.path)), definition); + const reactors: { readonly image: string; readonly reactor: string; readonly of: string }[] = []; g(0, "SECTION"); g(2, "CLASSES"); @@ -176,6 +202,14 @@ export function toDXFR2018( entity: true, }); } + // The leading CAD app draws nothing of an image whose class it holds no count of. + if (images.length > 0) { + const count = (n: number, entity = false) => ({ count: n, entity }); + writeClass(g, "IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, count(definitions.length)); + writeClass(g, "RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, count(1)); + writeClass(g, "IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, count(images.length)); + writeClass(g, "IMAGE", "AcDbRasterImage", "ISM", 2175, count(images.length, true)); + } g(0, "ENDSEC"); g(0, "SECTION"); @@ -436,6 +470,19 @@ export function toDXFR2018( ): void => { entities.forEach((entity, index) => { const own = entity.id === undefined ? handle() : handleOf(entity.id); + if (entity.kind === "image") { + const definition = definitionOf.get(exactKey(imagePathKey(entity.path)))!; + const reactor = entity.id === undefined ? handle() : imageReactorHandle(idKey(entity.id)); + reactors.push({ image: own, reactor, of: definition.handle }); + writeImage(g, entity, { + handle: own, + owner, + paper, + definition: definition.handle, + reactor, + }); + return; + } if (entity.kind === "leader") { const style = leaderStylesByKey.get(layerKey(entity.style)); if (style === undefined) return; @@ -623,6 +670,12 @@ export function toDXFR2018( g(281, 1); // duplicate records: keep existing g(3, "ACAD_GROUP"); g(350, groupDictionary); + if (images.length > 0) { + g(3, IMAGE_DICTIONARY); + g(350, imageDictionaryHandle()); + g(3, IMAGE_VARIABLES); + g(350, rasterVariablesHandle()); + } if (sheets.length > 0) { g(3, "ACAD_LAYOUT"); g(350, layoutDictionary); @@ -670,6 +723,9 @@ export function toDXFR2018( writeLeaderStyle(g, style, leaderDictionary, textStyle, linetypeByBlock); } } + if (images.length > 0) { + writeImageObjects(g, definitions, reactors, rootDictionary, drawing); + } if (sheets.length > 0) { g(0, "DICTIONARY"); ownedBy(g, layoutDictionary, rootDictionary); @@ -744,6 +800,7 @@ export function toDXFR2018( sheets.length > 0 || dimensionStyles.length > 0 || leaderStyles.length > 0 || + images.length > 0 || drawing.entities.some((entity) => entity.id !== undefined); h(5, named ? ID_HANDLE_SEED : handle()); h(0, "ENDSEC"); @@ -1661,6 +1718,135 @@ function writeClass( g(281, of.entity ? 1 : 0); } +/** Where an image's IMAGE goes, and what it points to. */ +interface ImagePlace { + readonly handle: string; + readonly owner: string; + readonly paper: boolean; + readonly definition: string; + readonly reactor: string; +} + +/** + * An IMAGE: its corner, the vectors of one pixel and its pixels, its definition, shown and + * clipped, transparent when asked, brightness 50, contrast 50 and fade 0, and its clip in pixels. + * The vectors and the clip are written with 15 digits, which a pixel of a large file needs. + */ +function writeImage(g: Group, e: Image, place: ImagePlace): void { + g(0, "IMAGE"); + g(5, place.handle); + g(330, place.owner); + g(100, "AcDbEntity"); + if (place.paper) g(67, 1); + g(8, e.layer); + const linetype = entityLinetype(e); + if (linetype !== undefined) g(6, linetype); + if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { + g(370, lineweightCode(e.lineweight)); + } + g(100, "AcDbRasterImage"); + g(90, 0); // the class's version + point(g, 10, ...e.at); + const [u, v] = imageVectors(e); + for (const [code, [x, y]] of [ + [11, u], + [12, v], + ] as const) { + g(code, fifteenDigits(x)); + g(code + 10, fifteenDigits(y)); + g(code + 20, 0); + } + g(13, e.pixels[0]); + g(23, e.pixels[1]); + g(340, place.definition); + // Shown, shown when not square to the screen, clipped by its boundary, and transparent. + g(70, 7 | (e.transparent ? 8 : 0)); + g(280, e.clip === undefined ? 0 : 1); + g(281, 50); + g(282, 50); + g(283, 0); + g(290, e.invertClip ? 1 : 0); + g(360, place.reactor); + const clip = imageClip(e); + g(71, clip.type); + g(91, clip.points.length); + for (const [x, y] of clip.points) { + g(14, fifteenDigits(x)); + g(24, fifteenDigits(y)); + } +} + +/** + * The objects of a drawing's images: the dictionary of their definitions, each definition with + * the reactors of the images of it, each reactor, and RASTERVARIABLES, which says whether a frame + * shows. + */ +function writeImageObjects( + g: Group, + definitions: readonly ImageDefinition[], + reactors: readonly { readonly image: string; readonly reactor: string; readonly of: string }[], + root: string, + drawing: Drawing, +): void { + const dictionary = imageDictionaryHandle(); + g(0, "DICTIONARY"); + ownedBy(g, dictionary, root); + g(100, "AcDbDictionary"); + g(281, 1); + // In the order the leading CAD app saves them: by the name folded to lower case as it folds + // names, a character's code at a time. + const sorted = definitions + .map((definition) => ({ definition, key: layerKey(definition.name) })) + .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)) + .map(({ definition }) => definition); + // Each definition's reactors, by its handle, which is short. + const reactorsOf = new Map(); + for (const { reactor, of } of reactors) { + const list = reactorsOf.get(of); + if (list) list.push(reactor); + else reactorsOf.set(of, [reactor]); + } + for (const definition of sorted) { + g(3, dxfOnce(definition.name)); + g(350, definition.handle); + } + for (const definition of definitions) { + g(0, "IMAGEDEF"); + g(5, definition.handle); + g(102, "{ACAD_REACTORS"); + g(330, dictionary); + for (const reactor of reactorsOf.get(definition.handle) ?? []) g(330, reactor); + g(102, "}"); + g(330, dictionary); + g(100, "AcDbRasterImageDef"); + g(90, 0); + g(1, dxfOnce(writtenImagePath(definition.path))); + g(10, definition.pixels[0]); + g(20, definition.pixels[1]); + // The size of one pixel, as the leading CAD app gives a file of no resolution: a whole image + // one unit wide. + g(11, fifteenDigits(1 / definition.pixels[0])); + g(21, fifteenDigits(1 / definition.pixels[0])); + g(280, 1); // loaded + g(281, 0); // no unit of resolution + } + for (const { image, reactor } of reactors) { + g(0, "IMAGEDEF_REACTOR"); + g(5, reactor); + g(330, image); + g(100, "AcDbRasterImageDefReactor"); + g(90, 2); + g(330, image); + } + g(0, "RASTERVARIABLES"); + ownedBy(g, rasterVariablesHandle(), root); + g(100, "AcDbRasterVariables"); + g(90, 0); + g(70, drawing.imageFrame === false ? 0 : 1); + g(71, 1); // high quality + g(72, isUnits(drawing.units) ? RASTER_UNITS[drawing.units] : RASTER_UNITS.in); +} + /** A color the leading CAD app holds as ByLayer and as ByBlock, as a multileader and its style write one. */ const COLOR_BY_LAYER = -1073741824; const COLOR_BY_BLOCK = -1056964608; diff --git a/src/extents.ts b/src/extents.ts index 79e59c6..c47b693 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -9,6 +9,7 @@ import { type Matrix, type Referenced, } from "./blocks.ts"; +import { imageCorners, imageDrawable, imageFrame } from "./images.ts"; import { dimensionPicture, pictureTexts, type Dimension } from "./dimensions.ts"; import type { AttributeDefinition, @@ -316,10 +317,28 @@ export function boxer( add(box[2], box[3]); break; } + case "image": { + // The image, and the frame of a clip that reaches past it: a rectangle's four corners + // along the image's sides, or a polygon's points. One the plots cannot draw has none. + if (!imageDrawable(e, clipsChecked)) break; + for (const [x, y] of imageCorners(e)) add(x, y); + if (e.clip === undefined) break; + if (e.clip.length === 2) { + for (const [x, y] of imageFrame(e)) add(x, y); + break; + } + const box = pointsBox(e.clip); + if (box[0] === Infinity) break; + add(box[0], box[1]); + add(box[2], box[3]); + break; + } } }; /** The box of a list of points, worked out once for a long list however many hold it. */ const pointBoxes = new WeakMap(); + /** Whether each clip an image gives can be drawn, read once however many images share it. */ + const clipsChecked = new WeakMap(); const pointsBox = (points: readonly Point[]): Bounds => { const long = Array.isArray(points) && points.length >= SHARED; const known = long ? pointBoxes.get(points) : undefined; diff --git a/src/images.ts b/src/images.ts new file mode 100644 index 0000000..a0d7358 --- /dev/null +++ b/src/images.ts @@ -0,0 +1,318 @@ +// Images: where an image's pixels go, its clip as the file holds it, the outline its frame +// draws, and the definition each file is written as. The writers, the plot, the extents and the +// readers all take an image from here, from the numbers as they are written. +import type { Drawing, Entity, Image, Point } from "./drawing.ts"; +import { written } from "./format.ts"; +import { keyHandle } from "./handles.ts"; +import { layerKey } from "./layers.ts"; +import { imagePixelsProblem } from "./rules.ts"; +import { sha256Text } from "./sha256.ts"; +import { filled, KEYED } from "./shape.ts"; + +/** + * A key of a `Map` for a string of any length, which no other string has: the string itself, or + * for one longer than V8 hashes by its characters, its SHA-256. + */ +export function exactKey(text: string): string { + return text.length <= KEYED ? `=${text}` : `#${sha256Text(text)}`; +} + +/** A plain array of `count` finite numbers or more, read without running a getter. */ +function finiteNumbers(value: unknown, count: number): boolean { + if ( + !Array.isArray(value) || + value.length !== count || + Reflect.ownKeys(value).length !== count + 1 + ) + return false; + for (let i = 0; i < count; i++) { + const item = Object.getOwnPropertyDescriptor(value, i); + if (!item || !("value" in item) || typeof item.value !== "number") return false; + if (!Number.isFinite(item.value)) return false; + } + return true; +} + +/** + * Whether an image's fields can be drawn: a path, its pixels, a point and finite sizes not 0, and + * a clip of two points or more, each a point, plain arrays all. The plots and the extents leave + * out one that cannot, which `lint` refuses. + */ +export function imageDrawable(image: Image, checked?: WeakMap): boolean { + const { path, pixels, at, width, height, rotation, clip } = image as Partial< + Record + >; + const size = (n: unknown) => typeof n === "number" && Number.isFinite(n) && n !== 0; + if (typeof path !== "string" || imagePixelsProblem(pixels) !== undefined) return false; + if (!finiteNumbers(at, 2) || !size(width) || !size(height)) return false; + if (rotation !== undefined && !(typeof rotation === "number" && Number.isFinite(rotation))) + return false; + if (clip === undefined) return true; + if (!Array.isArray(clip) || clip.length < 2) return false; + // A list many images share is read once a call that keeps what it found in `checked`. + const known = checked?.get(clip); + if (known !== undefined) return known; + let sound = Reflect.ownKeys(clip).length === clip.length + 1; + for (let i = 0; sound && i < clip.length; i++) { + const item = Object.getOwnPropertyDescriptor(clip, i); + sound = item !== undefined && "value" in item && finiteNumbers(item.value, 2); + } + checked?.set(clip, sound); + return sound; +} + +/** The vectors of one pixel of an image: along its bottom edge, and up its side. */ +export function imageVectors(image: Image): [u: Point, v: Point] { + const turn = ((image.rotation ?? 0) * Math.PI) / 180; + // A turn by a whole quarter is exact, as the leading CAD app saves one. + const quarter = Number.isInteger((image.rotation ?? 0) / 90); + const cos = quarter ? Math.round(Math.cos(turn)) : Math.cos(turn); + const sin = quarter ? Math.round(Math.sin(turn)) : Math.sin(turn); + const [du, dv] = [image.width / image.pixels[0], image.height / image.pixels[1]]; + return [ + [du * cos + 0, du * sin + 0], + [-dv * sin + 0, dv * cos + 0], + ]; +} + +/** The lower-left corner as written, and the vectors of one pixel. */ +function placed(image: Image): { at: Point; u: Point; v: Point } { + const [u, v] = imageVectors(image); + return { at: [written(image.at[0]), written(image.at[1])], u, v }; +} + +/** + * A point of the drawing in an image's pixels, as its clip holds them: across from the centers of + * its left column, and down from the centers of its top row, so the image spans -0.5 to its width + * less 0.5 one way and -0.5 to its height less 0.5 the other. + */ +export function toImagePixels( + at: Point, + u: Point, + v: Point, + pixels: readonly [number, number], + [x, y]: Point, +): Point { + const det = u[0] * v[1] - u[1] * v[0]; + const [dx, dy] = [x - at[0], y - at[1]]; + const s = (dx * v[1] - dy * v[0]) / det; + const t = (u[0] * dy - u[1] * dx) / det; + return [s - 0.5, pixels[1] - t - 0.5]; +} + +/** A point of an image's pixels, as its clip holds them, in the drawing. */ +export function fromImagePixels( + at: Point, + u: Point, + v: Point, + pixels: readonly [number, number], + [x, y]: Point, +): Point { + const [s, t] = [x + 0.5, pixels[1] - y - 0.5]; + return [at[0] + s * u[0] + t * v[0], at[1] + s * u[1] + t * v[1]]; +} + +/** A clip as the file holds it: 1 for a rectangle by two corners, 2 for a polygon, in pixels. */ +export interface ImageClip { + readonly type: 1 | 2; + readonly points: readonly Point[]; +} + +/** + * An image's clip as the file holds it. With none, the whole image: its two corners. A rectangle's + * corners are its lower and upper, as the leading CAD app's own `IMAGECLIP` writes them, and a + * polygon ends at its first point again, without which that app discards the drawing. + */ +export function imageClip(image: Image): ImageClip { + const [w, h] = image.pixels; + if (image.clip === undefined) { + return { + type: 1, + points: [ + [-0.5, -0.5], + [w - 0.5, h - 0.5], + ], + }; + } + const { at, u, v } = placed(image); + const points = image.clip.map(([x, y]) => + toImagePixels(at, u, v, image.pixels, [written(x), written(y)]), + ); + if (points.length === 2) { + const [[x0, y0], [x1, y1]] = points as [Point, Point]; + return { + type: 1, + points: [ + [Math.min(x0, x1), Math.min(y0, y1)], + [Math.max(x0, x1), Math.max(y0, y1)], + ], + }; + } + const [first] = points; + const last = points.at(-1)!; + const closed = first![0] === last[0] && first![1] === last[1]; + return { type: 2, points: closed ? points : [...points, first!] }; +} + +/** + * Whether a clip as a file holds it, in pixels, is the whole image's rectangle, which the leading + * CAD app saves for an image it does not clip: to a billionth of the image, since a DXF of the + * same save may hold 99.50000000000001 where the DWG holds 99.5. + */ +export function wholeImageClip( + type: number, + points: readonly Point[], + [w, h]: readonly [number, number], +): boolean { + if (type !== 1 || points.length !== 2) return false; + const [[x0, y0], [x1, y1]] = points as [Point, Point]; + const near = (value: number, edge: number, side: number) => + Math.abs(value - edge) <= 1e-9 * Math.max(1, side); + return ( + near(Math.min(x0, x1), -0.5, w) && + near(Math.min(y0, y1), -0.5, h) && + near(Math.max(x0, x1), w - 0.5, w) && + near(Math.max(y0, y1), h - 0.5, h) + ); +} + +/** The corners of an image in the drawing, from its lower-left corner round counterclockwise. */ +export function imageCorners(image: Image): [Point, Point, Point, Point] { + const { at, u, v } = placed(image); + const [w, h] = image.pixels; + const along: Point = [u[0] * w, u[1] * w]; + const up: Point = [v[0] * h, v[1] * h]; + return [ + at, + [at[0] + along[0], at[1] + along[1]], + [at[0] + along[0] + up[0], at[1] + along[1] + up[1]], + [at[0] + up[0], at[1] + up[1]], + ]; +} + +/** + * The outline an image's frame draws, in the drawing, as a closed ring: its clip's outline, past + * the image too, the hole's alone for an inverted clip, or the image's outline when it is not + * clipped. A rectangle of a clip is the one along the image's sides through its corners. + */ +export function imageFrame(image: Image): Point[] { + if (image.clip === undefined) return imageCorners(image); + const clip = imageClip(image); + const { at, u, v } = placed(image); + const back = (p: Point) => fromImagePixels(at, u, v, image.pixels, p); + if (clip.type === 1) { + const [[x0, y0], [x1, y1]] = clip.points as [Point, Point]; + return [back([x0, y1]), back([x1, y1]), back([x1, y0]), back([x0, y0])]; + } + return clip.points.slice(0, -1).map(back); +} + +/** One file the images of a drawing show, as one definition of it. */ +export interface ImageDefinition { + /** Its name in the dictionary of images: the file's name without its extension, made unique. */ + readonly name: string; + /** The path as the first image of it gives it. */ + readonly path: string; + readonly pixels: readonly [number, number]; + readonly handle: string; +} + +/** A path as the writers write it, with `\` between folders, as the leading CAD app saves one. */ +export function writtenImagePath(path: string): string { + return path.replaceAll("/", "\\"); +} + +/** The key two paths of one file share: `\` and `/` are one. */ +export function imagePathKey(path: string): string { + return path.replaceAll("\\", "/"); +} + +/** + * The handle of the definition of the file at `path`, from its path with `\` and `/` taken as + * one, so it keeps it when the drawing around it changes. Never change the key. + */ +export function imageDefinitionHandle(path: string): string { + return keyHandle(`image-definition:${imagePathKey(path)}`); +} + +/** The handle of the dictionary of images, `ACAD_IMAGE_DICT`. */ +export function imageDictionaryHandle(): string { + return keyHandle("dictionary:acad_image_dict"); +} + +/** The handle of RASTERVARIABLES, which holds whether images' frames show. */ +export function rasterVariablesHandle(): string { + return keyHandle("raster-variables:"); +} + +/** The handle of the reactor of an image with an id, from the id with A to Z in lower case. */ +export function imageReactorHandle(idKey: string): string { + return keyHandle(`image-reactor:${idKey}`); +} + +/** The name of the dictionary of images, as the leading CAD app names it. */ +export const IMAGE_DICTIONARY = "ACAD_IMAGE_DICT"; + +/** The name under which the root dictionary holds RASTERVARIABLES. */ +export const IMAGE_VARIABLES = "ACAD_IMAGE_VARS"; + +/** + * The definitions of the files a drawing's images show, in the order each file is first met: + * one for each path, with `\` and `/` taken as one. Each is named by its file's name without its + * extension, as the leading CAD app's `-IMAGE` names one, with a number after it for a name another + * file took first, compared as that app compares names. + */ +export function imageDefinitions(images: Iterable): ImageDefinition[] { + // Keyed exactly, since a path may be long and a lost key would write a file twice. + const byPath = new Map(); + const taken = new Set(); + // The next number to try after each name taken, so that many files of one name are named in + // time in proportion to their count. + const next = new Map(); + const found: ImageDefinition[] = []; + for (const image of images) { + const path = imagePathKey(image.path); + const key = exactKey(path); + if (byPath.has(key)) continue; + const file = path.slice(path.lastIndexOf("/") + 1); + const dot = file.lastIndexOf("."); + const base = (dot > 0 ? file.slice(0, dot) : file) || "image"; + const baseKey = exactKey(layerKey(base)); + let name = base; + if (taken.has(baseKey)) { + // Every number below the one kept was taken, and stays taken. + let n = next.get(baseKey) ?? 2; + while (taken.has(exactKey(layerKey(`${base}${n}`)))) n++; + name = `${base}${n}`; + next.set(baseKey, n + 1); + } + taken.add(exactKey(layerKey(name))); + const definition: ImageDefinition = { + name, + path: image.path, + pixels: [image.pixels[0], image.pixels[1]], + handle: imageDefinitionHandle(image.path), + }; + byPath.set(key, definition); + found.push(definition); + } + return found; +} + +/** + * Every image of a drawing, in the order the writers name their files by: model space, each + * layout, then each block, each list read up to its first empty slot. + */ +export function* drawingImages(drawing: Drawing): Generator { + const lists: (readonly Entity[] | undefined)[] = [ + drawing.entities, + ...filled(drawing.layouts ?? []).map((layout) => layout.entities), + ...filled(drawing.blocks ?? []).map((block) => block.entities), + ]; + for (const list of lists) { + for (const e of filled(list ?? [])) if (e.kind === "image") yield e; + } +} + +/** RASTERVARIABLES' units of a drawing's units, as the leading CAD app saves them. */ +export const RASTER_UNITS = { in: 5, ft: 6, mm: 1, cm: 2, m: 3 } as const; diff --git a/src/index.ts b/src/index.ts index 176c23b..fe5d059 100644 --- a/src/index.ts +++ b/src/index.ts @@ -66,6 +66,8 @@ export { type DxfVersion, type Entity, type EntityOptions, + type Image, + type ImageOptions, type Insert, type InsertOptions, type Layer, @@ -116,6 +118,29 @@ export { type Zone, } from "./drawing.ts"; export { toDXF, type DxfOptions } from "./dxf.ts"; +export { rasterSize } from "./raster.ts"; +export { + drawingImages, + fromImagePixels, + IMAGE_DICTIONARY, + IMAGE_VARIABLES, + imageClip, + imageCorners, + imageDefinitionHandle, + imageDefinitions, + imageDictionaryHandle, + imageFrame, + imagePathKey, + imageReactorHandle, + imageVectors, + RASTER_UNITS, + rasterVariablesHandle, + toImagePixels, + wholeImageClip, + writtenImagePath, + type ImageClip, + type ImageDefinition, +} from "./images.ts"; export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; export { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; export { capHeightOf, FONTS, type Font, type FontInfo } from "./fonts.ts"; @@ -305,6 +330,8 @@ export { type ReadEntityBase, type ReadField, type ReadHeader, + type ReadImage, + type ReadImageDefinition, type ReadInsert, type ReadLayer, type ReadLayerCensus, diff --git a/src/lint.ts b/src/lint.ts index 489ae6f..f3c4461 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -34,6 +34,7 @@ import type { Drawing, DxfVersion, Entity, + Image, Layout, Viewport, Insert, @@ -47,6 +48,7 @@ import type { Xref, } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; +import { exactKey, imagePathKey, imageReactorHandle, imageVectors } from "./images.ts"; import { written } from "./format.ts"; import { validIdHandle } from "./handles.ts"; import { validLayoutHandles, validViewportView, viewReaches } from "./layouts.ts"; @@ -79,6 +81,13 @@ import { STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { parseParagraph, type ParsedParagraph } from "./paragraph-codes.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; import { + IMAGE_CLIP_MOST, + IMAGE_CLIP_MOST_PROBLEM, + IMAGE_INVERT_WITHOUT_CLIP, + IMAGE_PIXELS_SAME, + imageClipProblem, + imagePathProblem, + imagePixelsProblem, arcIsWrittenAsPoint, arcProblem, ATTRIBUTES_SHAPE, @@ -202,6 +211,7 @@ export type LintRule = | "undefined-leader-style" | "leader" | "paragraph" + | "image" | "zero-length" | "standard" | "layer-outside-standard" @@ -501,6 +511,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) case "leader": cost += long1(e.style) + long1(e.textStyle); break; + case "image": + cost += long1(e.path); + break; } return cost; }; @@ -686,6 +699,16 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) }); } + const frame: unknown = drawing.imageFrame; + if (frame !== undefined && typeof frame !== "boolean") { + out.push({ + rule: "image", + severity: "error", + message: "imageFrame must be true or false", + item: "imageFrame", + }); + } + // The leading CAD app compares linetype names as it compares layer names, and AUDIT reports a // twin of a built-in linetype as it reports any other. const linetypes = new Set(); @@ -1398,6 +1421,69 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) }; type Add = (rule: LintRule, severity: Diagnostic["severity"], problem: string) => void; + /** The pixels the first image of each file gives it, by its path with \ and / as one. */ + // Keyed exactly, since a path may be long. + const imagePixels = new Map(); + /** + * Checks what an image holds beyond the fields every entity has: its path, its pixels, its clip + * and its flags, and that each file has one size, and takes its reactor's handle from its id. + */ + const lintImage = ( + image: Image, + add: Add, + sound: boolean, + named: boolean, + here: () => string, + ): void => { + const pathProblem = imagePathProblem(image.path); + if (pathProblem) add("image", "error", pathProblem); + const pixelsProblem = imagePixelsProblem(image.pixels); + if (pixelsProblem) add("image", "error", `pixels: ${pixelsProblem}`); + for (const [field, value] of [ + ["invertClip", image.invertClip], + ["transparent", image.transparent], + ] as const) { + if (value !== undefined && typeof value !== "boolean") { + add("image", "error", `${field} must be true or false`); + } + } + if (image.clip === undefined && image.invertClip === true) { + add("image", "error", IMAGE_INVERT_WITHOUT_CLIP); + } + if (pathProblem === undefined && pixelsProblem === undefined) { + const key = exactKey(imagePathKey(image.path)); + const first = imagePixels.get(key); + // A long path many images share is read again for each, which `repeatedIn` paid for. + if (first === undefined) imagePixels.set(key, [image.pixels[0], image.pixels[1]]); + else if (first[0] !== image.pixels[0] || first[1] !== image.pixels[1]) { + add("image", "error", IMAGE_PIXELS_SAME); + } + } + if (sound && pixelsProblem === undefined && image.clip !== undefined) { + const list: unknown = image.clip; + if (Array.isArray(list) && list.length > IMAGE_CLIP_MOST) { + add("image", "error", `clip: ${IMAGE_CLIP_MOST_PROBLEM}`); + } else if ( + Array.isArray(list) && + list.length > 64 && + !spend(Math.floor(list.length / 8), here) + ) { + return; + } else { + const [u, v] = imageVectors(image); + const at: Point = [written(image.at[0]), written(image.at[1])]; + const problem = imageClipProblem(image.clip, at, u, v); + if (problem) add("image", "error", `clip: ${problem}`); + } + } + if (named) { + const clash = claim( + imageReactorHandle(idKey(image.id as string)), + `the reactor of the image ${shown(image.id)}`, + ); + if (clash) add("id-handle", "error", clash); + } + }; /** Checks the id of an entity or a viewport and takes its handle. True for an id that is new. */ const lintId = (id: unknown, add: Add): boolean => { if (id === undefined) return false; @@ -1448,9 +1534,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const here = () => `${entity.kind} #${index} of ${space}`; // A long list of points, bulges or widths that many polylines share is read again for // each, and paid for. - if (isObject(entity) && entity.kind === "polyline") { + if (isObject(entity) && (entity.kind === "polyline" || entity.kind === "image")) { let cost = 0; - for (const list of [entity.points, entity.bulges, entity.widths]) { + const lists = + entity.kind === "image" ? [entity.clip] : [entity.points, entity.bulges, entity.widths]; + for (const list of lists) { if (Array.isArray(list) && list.length >= FREE && again(list)) cost += Math.floor(list.length / 8); } @@ -1602,6 +1690,13 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (problems.length === 0) lintLeader(entity, add, block !== undefined); return; } + if (entity.kind === "image") { + if (r12) { + add("image", "error", R12_ONLY.images); + return; + } + lintImage(entity, add, problems.length === 0, named, here); + } if (entity.kind === "linear-dimension" || entity.kind === "aligned-dimension") { lintDimension(entity, add, problems.length === 0, block !== undefined, here); // The block of its picture takes handles from its id, or else from its place. @@ -2205,6 +2300,11 @@ function geometryProblems(e: Entity): string[] { case "leader": finite("its point", ...e.at); break; + case "image": + finite("its position and rotation", ...e.at, e.rotation ?? 0); + size("width", e.width); + size("height", e.height); + break; } return out; } @@ -2235,6 +2335,7 @@ function zeroLength(e: Entity): string | undefined { case "linear-dimension": case "aligned-dimension": case "leader": + case "image": return undefined; } } diff --git a/src/pdf.ts b/src/pdf.ts index bbd2133..332085c 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -9,6 +9,7 @@ import { paperInfo } from "./papers.ts"; import { Sha256 } from "./sha256.ts"; import { filled } from "./shape.ts"; import { SHEET_PICTURE, toSVG } from "./svg.ts"; +import { fromBase64, plotDecodes, pngPixels, rasterInfo, uncompressed } from "./raster.ts"; import { readTrueType, type TrueType } from "./truetype.ts"; export interface PdfOptions { @@ -43,6 +44,12 @@ export interface PdfOptions { readonly missing?: (layout: string, characters: string, page: number) => void; /** The document's title, which a viewer shows in place of the file's name. */ readonly title?: string; + /** + * The bytes of each raster file the drawing's images show, by the image's path exactly as the + * drawing gives it, as `toSVG` takes them. The PDF holds each PNG and JPEG once, as it is: a + * JPEG and a PNG of no transparency as the file holds them, and any other PNG decoded. + */ + readonly images?: Readonly>; } /** One sheet of a set whose sheets are drawings of their own. */ @@ -52,6 +59,8 @@ export interface PdfSheet { readonly layout: string; /** The drawing each xref of `drawing` stands for, by name, as `toSVG` takes them. */ readonly xrefs?: XrefDrawings; + /** The raster files of its images, as `toPDF` takes them, in place of those of the options. */ + readonly images?: Readonly>; } /** @@ -90,6 +99,7 @@ export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions layout: layout!, ...(options.xrefs ? { xrefs: options.xrefs } : {}), })); + const images = options.images; if (sheets.length === 0) throw new RangeError("There is no layout to plot"); sheets.forEach((sheet, i) => { if ( @@ -103,8 +113,12 @@ export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions } }); const pdf = new PdfWriter(options); - for (const { drawing, layout, xrefs } of sheets) { - pdf.page(toSVG(drawing, xrefs ? { layout, xrefs } : { layout })); + for (const sheet of sheets) { + const { drawing, layout, xrefs } = sheet; + const own = sheet.images ?? images; + pdf.page( + toSVG(drawing, { layout, ...(xrefs ? { xrefs } : {}), ...(own ? { images: own } : {}) }), + ); } return pdf.finish(); } @@ -236,6 +250,9 @@ const ELEMENTS = new Set([ "ellipse", "path", "text", + "defs", + "image", + "use", ]); /** The attributes it writes on them, apart from `data-` ones, which say what an element is. */ @@ -272,6 +289,9 @@ const ATTRIBUTES = new Set([ "lengthAdjust", "xml:space", "font-weight", + "href", + "preserveAspectRatio", + "clip-rule", ]); /** @@ -1012,6 +1032,100 @@ class PdfWriter { return widths; } + /** Each image the PDF holds, by its name, and the name of each file. */ + private readonly images = new Map(); + private readonly imageNames = new Map(); + /** The hash of each picture's copy of a file, worked out once however many times it is used. */ + private readonly digests = new WeakMap(); + + /** + * The name of the image XObject of a raster file, written the first time the PDF meets it, or + * undefined for one it cannot read. A picture holds a file to plot opaque without its + * transparency, or marks the image `data-opaque`, which `opaque` is. + */ + private imageObject(bytes: Uint8Array, opaque: boolean): string | undefined { + let digest = this.digests.get(bytes); + if (digest === undefined) + this.digests.set(bytes, (digest = new Sha256().update(bytes).digest())); + const key = `${digest}${opaque ? "/opaque" : ""}`; + const known = this.imageNames.get(key); + if (known !== undefined) return known ?? undefined; + const written = this.writeImage(bytes, opaque); + const name = written === undefined ? null : `Im${this.images.size}`; + if (name !== null) this.images.set(name, { object: written! }); + this.imageNames.set(key, name); + return name ?? undefined; + } + + /** + * Writes a raster file as an image XObject, and its soft mask, and gives its object, which is + * reserved only once the file reads. + */ + private writeImage(bytes: Uint8Array, opaque: boolean): number | undefined { + const info = rasterInfo(bytes); + if (info === undefined) return undefined; + const size = `/Type /XObject /Subtype /Image /Width ${info.width} /Height ${info.height}`; + if (info.kind === "jpeg") { + const space = ["", "/DeviceGray", "", "/DeviceRGB", "/DeviceCMYK"][info.components]!; + // An Adobe CMYK JPEG holds each part inverted. + const decode = info.components === 4 && info.inverted ? " /Decode [1 0 1 0 1 0 1 0]" : ""; + const object = this.reserve(); + this.object( + object, + `<< ${size} /ColorSpace ${space} /BitsPerComponent 8${decode} /Filter /DCTDecode /Length ${bytes.length} >>`, + bytes, + ); + return object; + } + const palette = + info.palette === undefined + ? undefined + : `[/Indexed /DeviceRGB ${info.palette.length / 3 - 1} <${[...info.palette].map((b) => b.toString(16).padStart(2, "0")).join("")}>]`; + // A PNG of no transparency is its own data, which a PDF undoes the filters of as a PNG's. + // One stored without compression, as a picture holds a file to plot opaque, is decoded and + // compressed, and kept as it is when it does not decode. + const own = !plotDecodes(info); + const pixels = own && !uncompressed(info) ? undefined : pngPixels(info); + if (own && pixels === undefined) { + const colors = info.color === 2 ? 3 : 1; + const space = palette ?? (colors === 3 ? "/DeviceRGB" : "/DeviceGray"); + const object = this.reserve(); + this.object( + object, + `<< ${size} /ColorSpace ${space} /BitsPerComponent ${info.depth} /Filter /FlateDecode /DecodeParms << /Predictor 15 /Colors ${colors} /BitsPerComponent ${info.depth} /Columns ${info.width} >> /Length ${info.data.length} >>`, + info.data, + ); + return object; + } + if (pixels === undefined) return undefined; + const { width, height, channels, samples } = pixels; + const colors = channels >= 3 ? 3 : 1; + const alpha = channels === 2 || channels === 4; + const color = new Uint8Array(width * height * colors); + const mask = alpha && !opaque ? new Uint8Array(width * height) : undefined; + for (let i = 0; i < width * height; i++) { + for (let k = 0; k < colors; k++) color[i * colors + k] = samples[i * channels + k]!; + if (mask) mask[i] = samples[i * channels + channels - 1]!; + } + const object = this.reserve(); + let soft = ""; + if (mask) { + const maskObject = this.reserve(); + this.stream( + maskObject, + mask, + ` /Type /XObject /Subtype /Image /Width ${width} /Height ${height} /ColorSpace /DeviceGray /BitsPerComponent 8`, + ); + soft = ` /SMask ${maskObject} 0 R`; + } + this.stream( + object, + color, + ` ${size} /ColorSpace ${colors === 3 ? "/DeviceRGB" : "/DeviceGray"} /BitsPerComponent 8${soft}`, + ); + return object; + } + private layerObject(name: string): number { let number = this.layers.get(name); if (number === undefined) this.layers.set(name, (number = this.reserve())); @@ -1024,6 +1138,8 @@ class PdfWriter { const fonts = new Map(); const missing = new Set(); const marks = new Map(); + /** The images the page paints, by their names in its resources. */ + const images = new Set(); const page = this.pages.length + 1; const where = (tag: string) => `the element <${tag}> of picture ${page}`; let paper: @@ -1031,9 +1147,15 @@ class PdfWriter { | undefined; const stack: Inherited[] = []; /** The tag of each group open, the root's first, and whether the root has closed. */ - const names: ("svg" | "g")[] = []; + const names: ("svg" | "g" | "defs")[] = []; let ended = false; - const clips = new Map(); + const clips = new Map< + string, + | { x: number; y: number; width: number; height: number } + | { pieces: readonly Piece[]; evenOdd: boolean } + >(); + /** Each raster file the picture holds, by its id. */ + const rasters = new Map(); /** The clip path being read, whose rectangles are kept and not drawn. */ let inClip: string | undefined; /** The layer of the marked content open, and the pen last set at this depth of `q`. */ @@ -1116,6 +1238,8 @@ class PdfWriter { (tag === "clipPath" ? inClip !== undefined : inClip === undefined && names.at(-1) === tag); + // What the picture holds in its definitions is kept there, and drawn where a use names it. + const inDefs = names.includes("defs"); if ( ended || (closing && (!ends || attributeText!.trim() !== "")) || @@ -1143,6 +1267,7 @@ class PdfWriter { } text = undefined; } else if (tag === "clipPath") inClip = undefined; + else if (tag === "defs") names.pop(); else if (tag === "g" || tag === "svg") { names.pop(); ended = names.length === 0; @@ -1220,7 +1345,43 @@ class PdfWriter { } const parent = stack.at(-1); if (!parent) throw refuse(`<${tag}> outside the picture`, `picture ${page}`); + if (tag === "defs") { + if (inDefs || inClip !== undefined || Object.keys(element).length > 0) { + throw refuse(" where it is", where(tag)); + } + if (!selfClosing) names.push("defs"); + continue; + } + if (inDefs) { + if (tag !== "image" || !selfClosing || element.id === undefined) { + throw refuse(`<${tag}> in the definitions`, where(tag)); + } + const data = /^data:image\/(?:png|jpeg);base64,(.*)$/s.exec(element.href ?? "")?.[1]; + const bytes = data === undefined ? undefined : fromBase64(data); + if ( + bytes === undefined || + element.width !== "1" || + element.height !== "1" || + element.preserveAspectRatio !== "none" + ) { + throw refuse("an image that is not a PNG or a JPEG of the unit square", where(tag)); + } + rasters.set(element.id, bytes); + continue; + } if (inClip !== undefined) { + if (tag === "path") { + const extra = Object.keys(element).find((name) => name !== "d" && name !== "clip-rule"); + if (extra !== undefined) throw refuse(`the attribute ${extra} of a clip`, where(tag)); + const rule = element["clip-rule"]; + if (rule !== undefined && rule !== "evenodd") + throw refuse(`the clip-rule ${rule}`, where(tag)); + clips.set(inClip, { + pieces: pathPieces(element.d ?? "", where(tag), 1), + evenOdd: rule === "evenodd", + }); + continue; + } if (tag !== "rect") throw refuse(`<${tag}> in a clip path`, where(tag)); // A clip is a rectangle of the group's space, and nothing turns or moves it. const extra = Object.keys(element).find( @@ -1268,15 +1429,30 @@ class PdfWriter { close(); pens.push(pen); pen = { ...pen }; - const corners = [ - [rect.x, rect.y], - [rect.x + rect.width, rect.y], - [rect.x + rect.width, rect.y + rect.height], - [rect.x, rect.y + rect.height], - ].map(([cx, cy]) => apply(matrix, cx!, cy!).map(num).join(" ")); - content.add( - `q\n${corners[0]} m\n${corners[1]} l\n${corners[2]} l\n${corners[3]} l\nh W n`, - ); + if ("pieces" in rect) { + // An image's clip: its outline, or the image's with the hole inside it. + content.add("q"); + const p = (point: readonly [number, number]) => + apply(matrix, point[0], point[1]).map(num).join(" "); + for (const piece of rect.pieces) { + if (piece.kind === "move") content.add(`${p(piece.to)} m`); + else if (piece.kind === "line") content.add(`${p(piece.to)} l`); + else if (piece.kind === "curve") + content.add(`${p(piece.c1)} ${p(piece.c2)} ${p(piece.to)} c`); + else content.add("h"); + } + content.add(rect.evenOdd ? "W* n" : "W n"); + } else { + const corners = [ + [rect.x, rect.y], + [rect.x + rect.width, rect.y], + [rect.x + rect.width, rect.y + rect.height], + [rect.x, rect.y + rect.height], + ].map(([cx, cy]) => apply(matrix, cx!, cy!).map(num).join(" ")); + content.add( + `q\n${corners[0]} m\n${corners[1]} l\n${corners[2]} l\n${corners[3]} l\nh W n`, + ); + } saved = true; } stack.push({ ...inherited, saved }); @@ -1289,6 +1465,20 @@ class PdfWriter { continue; } if (!selfClosing) throw refuse(`<${tag}> with something inside it`, where(tag)); + if (tag === "use") { + const id = /^#(.+)$/.exec(element.href ?? "")?.[1]; + const bytes = id === undefined ? undefined : rasters.get(id); + if (bytes === undefined) + throw refuse(`the use of ${JSON.stringify(element.href)}`, where(tag)); + const key = this.imageObject(bytes, element["data-opaque"] !== undefined); + if (key === undefined) continue; + mark(inherited.layer); + images.add(key); + // The picture's image holds its top row at y 0, and a PDF's at y 1. + const m = compose(matrix, [1, 0, 0, -1, 0, 1]).map(num).join(" "); + content.add(`q\n${m} cm\n/${key} Do\nQ`); + continue; + } // The hidden rectangle of a view, and the white of the paper, put no ink on the page. if (element.visibility === "hidden" || element["data-paper-sheet"] !== undefined) continue; const stroke = colorOf(inherited.stroke, where(tag)); @@ -1374,9 +1564,11 @@ class PdfWriter { ([face, key]) => `/${key} ${"codes" in face ? face.object : this.faceObject(face)} 0 R`, ); const layerList = [...marks].map(([layer, key]) => `/${key} ${this.layers.get(layer)} 0 R`); + const imageList = [...images].map((key) => `/${key} ${this.images.get(key)!.object} 0 R`); const resources = [ fontList.length > 0 ? `/Font << ${fontList.join(" ")} >>` : "", layerList.length > 0 ? `/Properties << ${layerList.join(" ")} >>` : "", + imageList.length > 0 ? `/XObject << ${imageList.join(" ")} >>` : "", ] .filter(Boolean) .join(" "); diff --git a/src/raster.ts b/src/raster.ts new file mode 100644 index 0000000..82aa92e --- /dev/null +++ b/src/raster.ts @@ -0,0 +1,697 @@ +// Raster files, for an image's plot: what a PNG or a JPEG holds, read from its bytes. A raster +// file is untrusted input: every length and count is held to the bytes before it is read, a +// decode is held to the samples the header gives, and a file that is not read is answered with +// undefined, never a throw. + +/** What a raster file is, from its header. */ +export type RasterInfo = PngInfo | JpegInfo; + +export interface PngInfo { + readonly kind: "png"; + readonly width: number; + readonly height: number; + /** 1, 2, 4, 8 or 16. */ + readonly depth: number; + /** 0 gray, 2 RGB, 3 a palette, 4 gray and alpha, 6 RGB and alpha. */ + readonly color: number; + readonly interlaced: boolean; + /** RGB of each palette entry, for a palette. */ + readonly palette: Uint8Array | undefined; + /** The tRNS chunk's bytes, when the file has one. */ + readonly transparency: Uint8Array | undefined; + /** The IDAT chunks' bytes, one zlib stream. */ + readonly data: Uint8Array; +} + +export interface JpegInfo { + readonly kind: "jpeg"; + readonly width: number; + readonly height: number; + /** 1 gray, 3 YCbCr or RGB, 4 CMYK. */ + readonly components: number; + /** True when an Adobe marker says the file's CMYK is stored inverted, as Adobe's are. */ + readonly inverted: boolean; +} + +/** The most pixels an image's plot decodes, so a hostile header cannot ask for more memory. */ +export const RASTER_PIXELS = 100_000_000; + +const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]; +const SAMPLES: Readonly> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }; +const DEPTHS: Readonly> = { + 0: [1, 2, 4, 8, 16], + 2: [8, 16], + 3: [1, 2, 4, 8], + 4: [8, 16], + 6: [8, 16], +}; + +const u32 = (b: Uint8Array, at: number): number => + ((b[at]! << 24) | (b[at + 1]! << 16) | (b[at + 2]! << 8) | b[at + 3]!) >>> 0; +const u16 = (b: Uint8Array, at: number): number => (b[at]! << 8) | b[at + 1]!; + +/** What a PNG or a JPEG file holds, or undefined for any other bytes and for a broken file. */ +export function rasterInfo(bytes: Uint8Array): RasterInfo | undefined { + if (bytes.length >= 8 && PNG_SIGNATURE.every((b, i) => bytes[i] === b)) return pngInfo(bytes); + if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) return jpegInfo(bytes); + return undefined; +} + +/** + * A raster file's size in pixels, across and down, from its header: what an image's `pixels` + * is. Undefined for a file that is not a PNG or a JPEG, or is broken. + */ +export function rasterSize(bytes: Uint8Array): [width: number, height: number] | undefined { + const info = rasterInfo(bytes); + return info === undefined ? undefined : [info.width, info.height]; +} + +function pngInfo(bytes: Uint8Array): PngInfo | undefined { + let at = 8; + let header: Uint8Array | undefined; + let palette: Uint8Array | undefined; + let transparency: Uint8Array | undefined; + const data: Uint8Array[] = []; + let length = 0; + while (at + 8 <= bytes.length) { + const size = u32(bytes, at); + const type = String.fromCharCode( + bytes[at + 4]!, + bytes[at + 5]!, + bytes[at + 6]!, + bytes[at + 7]!, + ); + const from = at + 8; + if (size > bytes.length - from - 4) return undefined; + const body = bytes.subarray(from, from + size); + if (type === "IHDR") header = body; + else if (type === "PLTE") palette = body; + else if (type === "tRNS") transparency = body; + else if (type === "IDAT") { + data.push(body); + length += size; + } else if (type === "IEND") break; + at = from + size + 4; + } + if (header === undefined || header.length < 13 || data.length === 0) return undefined; + const [width, height] = [u32(header, 0), u32(header, 4)]; + const [depth, color, compression, filter, interlace] = [ + header[8]!, + header[9]!, + header[10]!, + header[11]!, + header[12]!, + ]; + if (width === 0 || height === 0 || width > 0x7fffffff || height > 0x7fffffff) return undefined; + if (!DEPTHS[color]?.includes(depth) || compression !== 0 || filter !== 0 || interlace > 1) { + return undefined; + } + if (color === 3 && (palette === undefined || palette.length % 3 !== 0 || palette.length === 0)) { + return undefined; + } + const joined = new Uint8Array(length); + let to = 0; + for (const part of data) { + joined.set(part, to); + to += part.length; + } + return { + kind: "png", + width, + height, + depth, + color, + interlaced: interlace === 1, + palette: color === 3 ? palette : undefined, + transparency, + data: joined, + }; +} + +function jpegInfo(bytes: Uint8Array): JpegInfo | undefined { + let at = 2; + let inverted = false; + while (at + 4 <= bytes.length) { + if (bytes[at] !== 0xff) return undefined; + const marker = bytes[at + 1]!; + if (marker === 0xff) { + at++; + continue; + } + if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7) || marker === 0x01) { + at += 2; + continue; + } + const size = u16(bytes, at + 2); + if (size < 2 || at + 2 + size > bytes.length) return undefined; + // APP14, Adobe's, says whether its CMYK is stored inverted. + if ( + marker === 0xee && + size >= 7 && + String.fromCharCode(...bytes.subarray(at + 4, at + 9)) === "Adobe" + ) { + inverted = true; + } + // A start of frame of any kind but the three that are not frames. + if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) { + if (size < 8) return undefined; + const [height, width, components] = [u16(bytes, at + 5), u16(bytes, at + 7), bytes[at + 9]!]; + if (width === 0 || height === 0 || ![1, 3, 4].includes(components)) return undefined; + return { kind: "jpeg", width, height, components, inverted }; + } + if (marker === 0xda || marker === 0xd9) return undefined; + at += 2 + size; + } + return undefined; +} + +// Inflate, RFC 1950 and 1951: the zlib stream of a PNG's data. + +const LENGTH_BASE = [ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, + 163, 195, 227, 258, +]; +const LENGTH_EXTRA = [ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, +]; +const DISTANCE_BASE = [ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, + 3073, 4097, 6145, 8193, 12289, 16385, 24577, +]; +const DISTANCE_EXTRA = [ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, +]; +const CODE_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + +/** A canonical Huffman code: the count of codes of each length, and the symbols in order. */ +interface Huffman { + readonly counts: Uint16Array; + readonly symbols: Uint16Array; +} + +function huffman(lengths: ArrayLike, n: number): Huffman | undefined { + const counts = new Uint16Array(16); + for (let i = 0; i < n; i++) counts[lengths[i]!]!++; + counts[0] = 0; + let left = 1; + for (let len = 1; len < 16; len++) { + left = left * 2 - counts[len]!; + if (left < 0) return undefined; + } + const offsets = new Uint16Array(16); + for (let len = 1; len < 15; len++) offsets[len + 1] = offsets[len]! + counts[len]!; + const symbols = new Uint16Array(n); + for (let i = 0; i < n; i++) if (lengths[i] !== 0) symbols[offsets[lengths[i]!]!++] = i; + return { counts, symbols }; +} + +class Inflater { + #at = 0; + #bit = 0; + #bits = 0; + #out: Uint8Array; + #length = 0; + failed = false; + readonly input: Uint8Array; + readonly limit: number; + constructor(input: Uint8Array, limit: number) { + this.input = input; + this.limit = limit; + this.#out = new Uint8Array(Math.min(limit, Math.max(1024, input.length * 4))); + } + + bits(n: number): number { + while (this.#bits < n) { + if (this.#at >= this.input.length) { + this.failed = true; + return 0; + } + this.#bit |= this.input[this.#at++]! << this.#bits; + this.#bits += 8; + } + const value = this.#bit & ((1 << n) - 1); + this.#bit >>>= n; + this.#bits -= n; + return value; + } + + decode(code: Huffman): number { + let value = 0; + let first = 0; + let index = 0; + for (let len = 1; len < 16; len++) { + value |= this.bits(1); + if (this.failed) return -1; + const count = code.counts[len]!; + if (value - count < first) return code.symbols[index + (value - first)]!; + index += count; + first = (first + count) << 1; + value <<= 1; + } + this.failed = true; + return -1; + } + + push(byte: number): boolean { + if (this.#length >= this.limit) { + this.failed = true; + return false; + } + if (this.#length === this.#out.length) { + const grown = new Uint8Array(Math.min(this.limit, this.#out.length * 2)); + grown.set(this.#out); + this.#out = grown; + } + this.#out[this.#length++] = byte; + return true; + } + + copy(distance: number, length: number): boolean { + if (distance > this.#length) { + this.failed = true; + return false; + } + for (let i = 0; i < length; i++) + if (!this.push(this.#out[this.#length - distance]!)) return false; + return true; + } + + stored(): boolean { + this.#bit = 0; + this.#bits = 0; + if (this.#at + 4 > this.input.length) return false; + const length = this.input[this.#at]! | (this.input[this.#at + 1]! << 8); + const check = this.input[this.#at + 2]! | (this.input[this.#at + 3]! << 8); + this.#at += 4; + if ((length ^ 0xffff) !== check || this.#at + length > this.input.length) return false; + for (let i = 0; i < length; i++) if (!this.push(this.input[this.#at++]!)) return false; + return true; + } + + block(lengths: Huffman, distances: Huffman): boolean { + for (;;) { + const symbol = this.decode(lengths); + if (symbol < 0) return false; + if (symbol < 256) { + if (!this.push(symbol)) return false; + } else if (symbol === 256) return true; + else { + const s = symbol - 257; + if (s >= 29) return false; + const length = LENGTH_BASE[s]! + this.bits(LENGTH_EXTRA[s]!); + const d = this.decode(distances); + if (d < 0 || d >= 30) return false; + const distance = DISTANCE_BASE[d]! + this.bits(DISTANCE_EXTRA[d]!); + if (this.failed || !this.copy(distance, length)) return false; + } + } + } + + dynamic(): boolean { + const [nlen, ndist, ncode] = [this.bits(5) + 257, this.bits(5) + 1, this.bits(4) + 4]; + if (this.failed || nlen > 286 || ndist > 30) return false; + const lengths = new Uint8Array(320); + for (let i = 0; i < ncode; i++) lengths[CODE_ORDER[i]!] = this.bits(3); + const code = huffman(lengths, 19); + if (code === undefined) return false; + lengths.fill(0); + let i = 0; + while (i < nlen + ndist) { + const symbol = this.decode(code); + if (symbol < 0) return false; + if (symbol < 16) lengths[i++] = symbol; + else { + let repeat = 0; + let value = 0; + if (symbol === 16) { + if (i === 0) return false; + value = lengths[i - 1]!; + repeat = 3 + this.bits(2); + } else if (symbol === 17) repeat = 3 + this.bits(3); + else repeat = 11 + this.bits(7); + if (this.failed || i + repeat > nlen + ndist) return false; + while (repeat-- > 0) lengths[i++] = value; + } + } + if (lengths[256] === 0) return false; + const literal = huffman(lengths, nlen); + const distance = huffman(lengths.subarray(nlen), ndist); + if (literal === undefined || distance === undefined) return false; + return this.block(literal, distance); + } + + run(): Uint8Array | undefined { + const [cmf, flg] = [this.input[0] ?? 0, this.input[1] ?? 0]; + if ((cmf & 15) !== 8 || ((cmf << 8) | flg) % 31 !== 0 || (flg & 32) !== 0) return undefined; + this.#at = 2; + const fixed = new Uint8Array(288); + fixed.fill(8, 0, 144); + fixed.fill(9, 144, 256); + fixed.fill(7, 256, 280); + fixed.fill(8, 280, 288); + const fixedLengths = huffman(fixed, 288)!; + const fixedDistances = huffman(new Uint8Array(30).fill(5), 30)!; + for (;;) { + const last = this.bits(1); + const type = this.bits(2); + if (this.failed) return undefined; + const ok = + type === 0 + ? this.stored() + : type === 1 + ? this.block(fixedLengths, fixedDistances) + : type === 2 + ? this.dynamic() + : false; + if (!ok || this.failed) return undefined; + if (last === 1) break; + } + return this.#out.subarray(0, this.#length); + } +} + +/** The bytes of a zlib stream, or undefined when it is broken or holds more than `limit`. */ +export function inflate(bytes: Uint8Array, limit: number): Uint8Array | undefined { + return new Inflater(bytes, limit).run(); +} + +/** A PNG's pixels at 8 bits a sample, rows from the top, in its own samples: gray, RGB and alpha. */ +export interface PngPixels { + readonly width: number; + readonly height: number; + /** 1 gray, 2 gray and alpha, 3 RGB, 4 RGB and alpha: a palette is given as RGB, or RGBA with tRNS. */ + readonly channels: number; + readonly samples: Uint8Array; +} + +const ADAM7 = [ + [0, 0, 8, 8], + [4, 0, 8, 8], + [0, 4, 4, 8], + [2, 0, 4, 4], + [0, 2, 2, 4], + [1, 0, 2, 2], + [0, 1, 1, 2], +] as const; + +/** + * A PNG's pixels, decoded: undone of its filters and its interlace, each sample at 8 bits, a + * palette looked up, and the alpha of tRNS added. Undefined for a file broken or larger than + * `RASTER_PIXELS`. + */ +export function pngPixels(info: PngInfo): PngPixels | undefined { + const { width, height, depth, color } = info; + if (width * height > RASTER_PIXELS) return undefined; + const samples = SAMPLES[color]!; + const bits = samples * depth; + const passes = info.interlaced + ? ADAM7.map(([x0, y0, dx, dy]) => ({ + x0, + y0, + dx, + dy, + w: Math.ceil((width - x0) / dx), + h: Math.ceil((height - y0) / dy), + })).filter((p) => p.w > 0 && p.h > 0) + : [{ x0: 0, y0: 0, dx: 1, dy: 1, w: width, h: height }]; + const total = passes.reduce((sum, p) => sum + p.h * (Math.ceil((p.w * bits) / 8) + 1), 0); + const raw = inflate(info.data, total); + if (raw === undefined || raw.length < total) return undefined; + const tRNS = info.transparency; + const alpha = color === 4 || color === 6 || tRNS !== undefined; + const channels = color === 0 ? (alpha ? 2 : 1) : color === 4 ? 2 : alpha ? 4 : 3; + const out = new Uint8Array(width * height * channels); + const bpp = Math.max(1, bits >> 3); + let at = 0; + for (const pass of passes) { + const stride = Math.ceil((pass.w * bits) / 8); + let previous = new Uint8Array(stride); + for (let y = 0; y < pass.h; y++) { + const type = raw[at]!; + const row = raw.slice(at + 1, at + 1 + stride); + at += stride + 1; + if (type > 4) return undefined; + for (let i = 0; i < stride; i++) { + const left = i >= bpp ? row[i - bpp]! : 0; + const up = previous[i]!; + const corner = i >= bpp ? previous[i - bpp]! : 0; + if (type === 1) row[i] = (row[i]! + left) & 255; + else if (type === 2) row[i] = (row[i]! + up) & 255; + else if (type === 3) row[i] = (row[i]! + ((left + up) >> 1)) & 255; + else if (type === 4) { + const p = left + up - corner; + const [pa, pb, pc] = [Math.abs(p - left), Math.abs(p - up), Math.abs(p - corner)]; + row[i] = (row[i]! + (pa <= pb && pa <= pc ? left : pb <= pc ? up : corner)) & 255; + } + } + previous = row; + for (let x = 0; x < pass.w; x++) { + // A sample as the file holds it, and at 8 bits. + const held = (k: number): number => { + if (depth === 8) return row[x * samples + k]!; + if (depth === 16) + return (row[(x * samples + k) * 2]! << 8) | row[(x * samples + k) * 2 + 1]!; + const index = (x * samples + k) * depth; + return (row[index >> 3]! >> (8 - depth - (index & 7))) & ((1 << depth) - 1); + }; + const sample = (k: number): number => { + if (depth === 8 || color === 3) return held(k); + if (depth === 16) return held(k) >> 8; + return Math.round((held(k) * 255) / ((1 << depth) - 1)); + }; + const to = ((pass.y0 + y * pass.dy) * width + pass.x0 + x * pass.dx) * channels; + if (color === 3) { + const index = sample(0); + const palette = info.palette!; + if (index * 3 + 2 >= palette.length) return undefined; + out[to] = palette[index * 3]!; + out[to + 1] = palette[index * 3 + 1]!; + out[to + 2] = palette[index * 3 + 2]!; + if (alpha) out[to + 3] = index < tRNS!.length ? tRNS![index]! : 255; + } else if (color === 0 || color === 4) { + out[to] = sample(0); + if (color === 4) out[to + 1] = sample(1); + else if (alpha) { + const key = tRNS!.length >= 2 ? u16(tRNS!, 0) : -1; + out[to + 1] = held(0) === key ? 0 : 255; + } + } else { + out[to] = sample(0); + out[to + 1] = sample(1); + out[to + 2] = sample(2); + if (color === 6) out[to + 3] = sample(3); + else if (alpha) { + const key = + tRNS!.length >= 6 ? [u16(tRNS!, 0), u16(tRNS!, 2), u16(tRNS!, 4)] : [-1, -1, -1]; + out[to + 3] = [held(0), held(1), held(2)].every((v, k) => v === key[k]) ? 0 : 255; + } + } + } + } + } + return { width, height, channels, samples: out }; +} + +const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +const BASE64_CODES = Uint8Array.from(BASE64, (c) => c.charCodeAt(0)); + +/** Bytes in base 64, as a data URL holds them. */ +export function base64(bytes: Uint8Array): string { + // Written as bytes and read as text once, so the text is one flat string: built from pieces, + // a long one takes many times its length in memory. + const out = new Uint8Array(base64Length(bytes.length)); + let to = 0; + for (let i = 0; i < bytes.length; i += 3) { + const [a, b, c] = [bytes[i]!, bytes[i + 1], bytes[i + 2]]; + const n = (a << 16) | ((b ?? 0) << 8) | (c ?? 0); + out[to++] = BASE64_CODES[(n >> 18) & 63]!; + out[to++] = BASE64_CODES[(n >> 12) & 63]!; + out[to++] = b === undefined ? 61 : BASE64_CODES[(n >> 6) & 63]!; + out[to++] = c === undefined ? 61 : BASE64_CODES[n & 63]!; + } + return new TextDecoder().decode(out); +} + +/** The characters `base64` writes for `bytes` bytes. */ +export function base64Length(bytes: number): number { + return 4 * Math.ceil(bytes / 3); +} + +/** + * Whether a plot must decode a PNG's pixels to draw it: one with transparency, or interlaced. A + * PDF holds any other as its own data. + */ +export function plotDecodes(info: PngInfo): boolean { + return info.interlaced || info.color === 4 || info.color === 6 || info.transparency !== undefined; +} + +/** The bytes of base 64, or undefined for text that is not. */ +export function fromBase64(text: string): Uint8Array | undefined { + if (text.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) return undefined; + const pad = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0; + const out = new Uint8Array((text.length / 4) * 3 - pad); + let at = 0; + for (let i = 0; i < text.length; i += 4) { + const n = + (BASE64.indexOf(text[i]!) << 18) | + (BASE64.indexOf(text[i + 1]!) << 12) | + ((text[i + 2] === "=" ? 0 : BASE64.indexOf(text[i + 2]!)) << 6) | + (text[i + 3] === "=" ? 0 : BASE64.indexOf(text[i + 3]!)); + for (const byte of [(n >> 16) & 255, (n >> 8) & 255, n & 255]) + if (at < out.length) out[at++] = byte; + } + return out; +} + +/** + * A JPEG without its EXIF segments. The leading CAD app plots a JPEG as its pixels are stored, + * whatever orientation its EXIF gives, and a browser turns one by it: without them the two agree. + */ +export function withoutExif(bytes: Uint8Array): Uint8Array { + const keep: Uint8Array[] = [bytes.subarray(0, 2)]; + let at = 2; + let dropped = false; + while (at + 4 <= bytes.length && bytes[at] === 0xff) { + const marker = bytes[at + 1]!; + // The image's data starts at the start of a scan, and nothing after it is a segment. + if (marker === 0xda || marker === 0xd9) break; + const size = u16(bytes, at + 2); + if (size < 2 || at + 2 + size > bytes.length) return bytes; + const exif = + marker === 0xe1 && + size >= 8 && + String.fromCharCode(...bytes.subarray(at + 4, at + 8)) === "Exif"; + if (exif) dropped = true; + else keep.push(bytes.subarray(at, at + 2 + size)); + at += 2 + size; + } + if (!dropped) return bytes; + keep.push(bytes.subarray(at)); + const out = new Uint8Array(keep.reduce((sum, part) => sum + part.length, 0)); + let to = 0; + for (const part of keep) { + out.set(part, to); + to += part.length; + } + return out; +} + +/** True when a PNG holds transparency: an alpha channel, or a tRNS chunk. */ +export function hasAlpha(info: RasterInfo): boolean { + return ( + info.kind === "png" && (info.color === 4 || info.color === 6 || info.transparency !== undefined) + ); +} + +/** The CRC of PNG's chunks, of each byte. */ +const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); + +/** True when a PNG's data is stored without compression, as `opaquePng` writes it. */ +export function uncompressed(info: PngInfo): boolean { + // The zlib header's two bytes, then the first block's type in bits 1 and 2: 0 is stored. + return info.data.length > 2 && (info.data[2]! & 6) === 0; +} + +/** + * A PNG's pixels with its transparency left out, as an image not marked transparent plots them: + * the file without its tRNS chunk, or one of an alpha channel decoded and written again, its + * colors at 8 bits, in deflate's stored blocks, which need no compressor. Undefined for a file + * that does not decode. + */ +export function opaquePng(info: PngInfo, bytes: Uint8Array): Uint8Array | undefined { + if (info.color !== 4 && info.color !== 6) { + if (info.transparency === undefined) return bytes; + // Every chunk but tRNS, as the file holds it; rasterInfo held each to the bytes. + const kept: Uint8Array[] = [bytes.subarray(0, 8)]; + for (let at = 8; at + 8 <= bytes.length;) { + const size = u32(bytes, at); + const end = Math.min(bytes.length, at + 12 + size); + const type = String.fromCharCode( + bytes[at + 4]!, + bytes[at + 5]!, + bytes[at + 6]!, + bytes[at + 7]!, + ); + if (type !== "tRNS") kept.push(bytes.subarray(at, end)); + if (type === "IEND") break; + at = end; + } + return concat(kept); + } + const pixels = pngPixels(info); + if (pixels === undefined) return undefined; + const { width, height, channels, samples } = pixels; + const colors = channels >= 3 ? 3 : 1; + const row = width * colors + 1; + const raw = new Uint8Array(row * height); + for (let y = 0; y < height; y++) { + // Filter 0 on every row: the samples as they are. + for (let x = 0; x < width; x++) { + for (let k = 0; k < colors; k++) { + raw[y * row + 1 + x * colors + k] = samples[(y * width + x) * channels + k]!; + } + } + } + const blocks = Math.max(1, Math.ceil(raw.length / 65_535)); + const zlib = new Uint8Array(2 + raw.length + 5 * blocks + 4); + zlib.set([0x78, 0x01]); + let to = 2; + for (let n = 0; n < blocks; n++) { + const part = raw.subarray(n * 65_535, (n + 1) * 65_535); + zlib.set([n === blocks - 1 ? 1 : 0, part.length & 255, part.length >> 8], to); + zlib.set([~part.length & 255, (~part.length >> 8) & 255], to + 3); + zlib.set(part, to + 5); + to += 5 + part.length; + } + // Adler-32 of the data, its two sums kept under 65,521 every 5,552 bytes. + let [a, b] = [1, 0]; + for (let i = 0; i < raw.length;) { + const end = Math.min(raw.length, i + 5552); + for (; i < end; i++) { + a += raw[i]!; + b += a; + } + a %= 65_521; + b %= 65_521; + } + zlib.set([b >> 8, b & 255, a >> 8, a & 255], to); + const header = new Uint8Array(13); + header.set([width >>> 24, (width >>> 16) & 255, (width >>> 8) & 255, width & 255]); + header.set([height >>> 24, (height >>> 16) & 255, (height >>> 8) & 255, height & 255], 4); + header.set([8, colors === 3 ? 2 : 0, 0, 0, 0], 8); + return concat([ + new Uint8Array(PNG_SIGNATURE), + chunk("IHDR", header), + chunk("IDAT", zlib), + chunk("IEND", new Uint8Array()), + ]); +} + +/** A PNG chunk: its length, its type, its data and the CRC of the type and the data. */ +function chunk(type: string, data: Uint8Array): Uint8Array { + const out = new Uint8Array(12 + data.length); + const length = data.length; + out.set([length >>> 24, (length >>> 16) & 255, (length >>> 8) & 255, length & 255]); + for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i); + out.set(data, 8); + let c = 0xffffffff; + for (let i = 4; i < 8 + length; i++) c = CRC_TABLE[(c ^ out[i]!) & 255]! ^ (c >>> 8); + c = (c ^ 0xffffffff) >>> 0; + out.set([c >>> 24, (c >>> 16) & 255, (c >>> 8) & 255, c & 255], 8 + length); + return out; +} + +/** The parts one after another. */ +function concat(parts: readonly Uint8Array[]): Uint8Array { + const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0)); + let to = 0; + for (const part of parts) { + out.set(part, to); + to += part.length; + } + return out; +} diff --git a/src/read/check.ts b/src/read/check.ts index b24bd37..afcdfc9 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -184,6 +184,24 @@ const ENTITY: Readonly> = { arrowSize: "number", }, solid: { ...BASE, kind: { oneOf: ["solid"] }, points: { list: "point" } }, + image: { + ...BASE, + kind: { oneOf: ["image"] }, + path: "string", + "definition?": "string", + pixels: "point", + at: "point", + u: "point", + v: "point", + "clip?": { list: "point" }, + "invertClip?": "boolean", + "transparent?": "boolean", + "hidden?": "boolean", + "unclipped?": "boolean", + "brightness?": "number", + "contrast?": "number", + "fade?": "number", + }, }; const SPACE: Fields = { @@ -309,6 +327,18 @@ const DRAWING_READ: Fields = { xrefs: { list: { fields: { "handle?": "string", name: "string", path: "string", overlay: "boolean" } }, }, + images: { + list: { + fields: { + "handle?": "string", + name: "string", + path: "string", + pixels: "point", + loaded: "boolean", + images: "count", + }, + }, + }, model: { fields: SPACE }, layouts: { list: { diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 14ebd71..a0593d9 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -13,6 +13,7 @@ import { brokenNumber, costOf, handleAt, + imageInWorld, nameCost, placementOf, readingOf, @@ -55,6 +56,8 @@ import { type ReadEntityBase, type ReadField, type ReadHeader, + type ReadImage, + type ReadImageDefinition, type ReadInsert, type ReadLayer, type ReadLayerCensus, @@ -184,6 +187,7 @@ const BLOCK_READS = new Set([ "ATTRIB", "CIRCLE", "DIMENSION", + "IMAGE", "INSERT", "LINE", "LWPOLYLINE", @@ -200,6 +204,7 @@ const BLOCK_READS = new Set([ const SPACE_READS = new Set([ "ATTRIB", "DIMENSION", + "IMAGE", "INSERT", "MTEXT", "POLYLINE", @@ -217,6 +222,7 @@ const HOUSEKEEPING = new Set([ "CELLSTYLEMAP", "DICTIONARYVAR", "FIELDLIST", + "IMAGEDEF_REACTOR", "MATERIAL", "MLEADERSTYLE", "MLINESTYLE", @@ -500,6 +506,19 @@ class DxfReader { starts: [], leaders: [], }; + /** The images kept, to finish once the definitions are read. */ + readonly #images: ReadImage[] = []; + /** How many images name each definition, by its handle. */ + readonly #imageUses = new Map(); + /** The handle of the dictionary of image definitions, from the root dictionary. */ + #imageDictionary: string | undefined; + /** The dictionary's entries, in its order: each definition's name and handle. */ + readonly #imageEntries: (readonly [name: string, handle: string])[] = []; + /** Each image definition, by its handle. */ + readonly #imageDefinitions = new Map< + string, + { readonly path: string; readonly pixels: readonly [number, number]; readonly loaded: boolean } + >(); readonly #later: Later = { start: (pending) => this.#staged.starts.push(pending), leader: (entity, style, textStyle) => @@ -581,7 +600,9 @@ class DxfReader { case "TABLES": return ALL; case "OBJECTS": - return type === "DICTIONARY" || type === "FIELD" || type === "LAYOUT" ? ALL : NOTHING; + return type === "DICTIONARY" || type === "FIELD" || type === "LAYOUT" || type === "IMAGEDEF" + ? ALL + : NOTHING; case "BLOCKS": if (type === "BLOCK" || type === "ENDBLK") return ALL; if (this.#inDimensionPicture) return NOTHING; @@ -974,10 +995,20 @@ class DxfReader { return; } } + // How many images name each definition, whatever the read keeps of them, for as many + // definitions as the census holds. + if (r.type === "IMAGE") { + const definition = handleAt(r, 340); + const uses = definition === undefined ? undefined : this.#imageUses.get(definition); + if (uses !== undefined) this.#imageUses.set(definition!, uses + 1); + else if (definition !== undefined && this.#imageUses.size < this.#limits.census) + this.#imageUses.set(definition, 1); + } if (!target) return; if (hidden(r)) return add(target.other, "invisible"); const reading = readingOf(r, baseOf(r, layer, handle), face, this.#later, this.#r12); const kept = reading !== undefined && "entity" in reading && this.#kept(target, reading.entity); + if (kept && reading.entity.kind === "image") this.#images.push(reading.entity); for (const pending of this.#settle(kept, target)) this.#starts.push(pending); if (reading === undefined) add(target.other, r.type); else if ("other" in reading) add(target.other, reading.other); @@ -1193,7 +1224,14 @@ class DxfReader { entries ??= {}; entries[key] = value; } else if (key === "ACAD_MLEADERSTYLE") this.#leaderStyleDictionary ??= value; - else if (styles && key.length <= LONGEST_NAME && !this.leaderStyles.has(value)) { + else if (key === "ACAD_IMAGE_DICT") this.#imageDictionary ??= value; + else if ( + handle === this.#imageDictionary && + key.length <= LONGEST_NAME && + this.#imageEntries.length < this.#limits.census + ) { + this.#imageEntries.push([unescaped(key), value]); + } else if (styles && key.length <= LONGEST_NAME && !this.leaderStyles.has(value)) { this.leaderStyles.set(value, unescaped(key)); } } @@ -1202,6 +1240,17 @@ class DxfReader { } return; } + case "IMAGEDEF": { + const handle = handleAt(r, 5); + if (handle === undefined || this.#imageDefinitions.size >= this.#limits.census) return; + const definition = inSubclass(r, "AcDbRasterImageDef"); + this.#imageDefinitions.set(handle, { + path: name(definition, 1) ?? "", + pixels: [num(definition, 10) ?? 0, num(definition, 20) ?? 0], + loaded: (num(definition, 280) ?? 1) !== 0, + }); + return; + } case "FIELD": { const handle = handleAt(r, 5); if (handle === undefined) return; @@ -1423,10 +1472,28 @@ class DxfReader { } if (this.#fieldsPast > 0) add(otherFields, "past the limit", this.#fieldsPast); + for (const image of this.#images) { + const definition = + image.definition === undefined ? undefined : this.#imageDefinitions.get(image.definition); + imageInWorld(image, definition?.path); + } + // The dictionary's definitions in its order, then any it does not list. + const listed = new Set(); + const images: ReadImageDefinition[] = []; + const listDefinition = (handle: string, name: string): void => { + const definition = this.#imageDefinitions.get(handle); + if (definition === undefined || listed.has(handle)) return; + listed.add(handle); + images.push({ handle, name, ...definition, images: this.#imageUses.get(handle) ?? 0 }); + }; + for (const [name, handle] of this.#imageEntries) listDefinition(handle, name); + for (const handle of this.#imageDefinitions.keys()) listDefinition(handle, ""); + return { format: READ_FORMAT, sha256, bytes, + images, ...(groups.version !== undefined && { version: groups.version }), ...(groups.codepage !== undefined && { codepage: groups.codepage }), encoding: groups.encoding, diff --git a/src/read/entities.ts b/src/read/entities.ts index 263950d..1a6db5d 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -2,11 +2,13 @@ // coordinates with the pen it sets for itself. import type { Point } from "../drawing.ts"; import { textOnce, textTwice } from "./groups.ts"; +import { wholeImageClip } from "../images.ts"; import type { ReadAttribute, ReadDimension, ReadEntity, ReadEntityBase, + ReadImage, ReadMtext, ReadMultileader, ReadPolyline, @@ -16,6 +18,7 @@ import { dimensionTextParts } from "./model.ts"; import { facing, first, + inSubclass, name, num, placed, @@ -209,6 +212,8 @@ export function readingOf( return dimension(r, base, face, r12); case "MULTILEADER": return multileader(r, base, later); + case "IMAGE": + return image(r, base); case "SOLID": { if (face === 0) return { other: "SOLID in 3D" }; const corner = (code: number): Point => @@ -220,6 +225,83 @@ export function readingOf( } } +/** + * An image as its file places it. Its clip is held in the image's pixels, as the file holds it, + * a polygon without its first point again at its end, and its path is the definition's, which + * the reader fills in once it has read the definitions: `imageInWorld` finishes it. + */ +function image(r: Rec, base: ReadEntityBase): Reading { + const s = inSubclass(r, "AcDbRasterImage"); + // An image whose vectors leave the plane is one the read model does not hold. + if ([31, 32, 30].some((code) => Math.abs(num(s, code) ?? 0) > 1e-9)) { + return { other: "IMAGE in 3D" }; + } + const flags = num(s, 70) ?? 0; + const points: Point[] = []; + for (let i = 0; i < s.codes.length; i++) { + if (s.codes[i] !== 14) continue; + const y = s.codes[i + 1] === 24 ? Number(s.values[i + 1]) : 0; + points.push([Number(s.values[i]), y]); + } + const [head] = points; + const tail = points.at(-1); + if ( + (num(s, 71) ?? 1) !== 1 && + points.length > 1 && + head![0] === tail![0] && + head![1] === tail![1] + ) { + points.pop(); + } + const definition = handleAt(s, 340); + const brightness = num(s, 281) ?? 50; + const contrast = num(s, 282) ?? 50; + const fade = num(s, 283) ?? 0; + return { + entity: { + ...base, + kind: "image", + path: "", + ...(definition !== undefined && { definition }), + pixels: [num(s, 13) ?? 0, num(s, 23) ?? 0], + at: point(s, 10), + u: point(s, 11), + v: point(s, 12), + // Flag 4 clips the image to its boundary whatever 280 says, as the leading CAD app draws + // it, and the whole image's boundary is no clip, unless it is inverted: a hole of it all. + ...(points.length > 0 && + ((num(s, 280) ?? 0) !== 0 || + (num(s, 290) ?? 0) !== 0 || + !wholeImageClip(num(s, 71) ?? 1, points, [num(s, 13) ?? 0, num(s, 23) ?? 0])) && { + clip: points, + }), + ...((num(s, 290) ?? 0) !== 0 && { invertClip: true }), + ...((flags & 8) !== 0 && { transparent: true }), + ...((flags & 1) === 0 && { hidden: true }), + ...((flags & 4) === 0 && { unclipped: true }), + ...(brightness !== 50 && { brightness }), + ...(contrast !== 50 && { contrast }), + ...(fade !== 0 && { fade }), + }, + }; +} + +/** + * Finishes an image the reader kept: its definition's path, and its clip from its pixels into + * the world's coordinates. + */ +export function imageInWorld(image: ReadImage, path: string | undefined): void { + const mutable = image as Mutable; + mutable.path = path ?? ""; + if (image.clip === undefined) return; + const { at, u, v } = image; + const height = image.pixels[1]; + mutable.clip = image.clip.map(([x, y]) => { + const [s, t] = [x + 0.5, height - y - 0.5]; + return [at[0] + s * u[0] + t * v[0], at[1] + s * u[1] + t * v[1]]; + }); +} + function lwpolyline(r: Rec, base: ReadEntityBase, face: Facing): Reading { if (face === 0) return { other: "LWPOLYLINE in 3D" }; const points: Point[] = []; @@ -492,5 +574,7 @@ export function costOf(e: ReadEntity): number { for (const a of e.attributes ?? []) more += attributeCost(a); return own + more; } + case "image": + return own + 4 + (e.clip?.length ?? 0) + chars(e.definition); } } diff --git a/src/read/model.ts b/src/read/model.ts index 8f101a3..260589e 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -41,6 +41,11 @@ export interface DrawingRead { */ readonly blocks: readonly ReadBlock[]; readonly xrefs: readonly ReadXref[]; + /** + * Each image definition of the file's dictionary of them, in the order of the dictionary, those + * no image uses among them: the leading CAD app keeps one through a save and a purge. + */ + readonly images: readonly ReadImageDefinition[]; /** Model space: its census, and with `geometry` what it draws. */ readonly model: ReadSpace; /** Each layout of paper space, in the order of its tab. */ @@ -425,6 +430,48 @@ export interface ReadSolid extends ReadEntityBase { readonly points: readonly Point[]; } +/** + * A raster image, as the file places it: its lower-left corner and the vectors of one of its + * pixels along its bottom and up its side, which a mirrored or slanted image has too. + */ +export interface ReadImage extends ReadEntityBase { + readonly kind: "image"; + /** The path of its definition as the file holds it, or `""` when it names none. */ + readonly path: string; + /** The handle of its definition, when it names one. */ + readonly definition?: string; + /** The pixels the image states, group 13. */ + readonly pixels: readonly [width: number, height: number]; + readonly at: Point; + /** The vector of one pixel along the image's bottom edge, and up its side. */ + readonly u: Point; + readonly v: Point; + /** + * The clip's boundary, in the world's coordinates: two opposite corners of a rectangle along the + * image's sides, or a polygon, without its first point again at its end. Left out when the file + * holds the whole image's boundary with the clip off and not inverted, as the leading CAD app + * saves an image it does not clip; `unclipped` says when the image is shown whole anyway. + */ + readonly clip?: readonly Point[]; + /** True when the image shows outside its clip, and the clip is a hole. */ + readonly invertClip?: boolean; + /** True when the transparent pixels of a PNG show what is behind. */ + readonly transparent?: boolean; + /** True when the file says not to show the image, which then shows its frame alone. */ + readonly hidden?: boolean; + /** + * True when the file says not to clip the image, so it all shows, whatever `clip` says. Its + * frame still follows `clip`. + */ + readonly unclipped?: boolean; + /** Group 281, from 0 to 100. Left out at 50. */ + readonly brightness?: number; + /** Group 282, from 0 to 100. Left out at 50. */ + readonly contrast?: number; + /** Group 283, from 0 to 100. Left out at 0. */ + readonly fade?: number; +} + /** What a space or a block draws, of the kinds the writers write. */ export type ReadEntity = | ReadLine @@ -436,7 +483,8 @@ export type ReadEntity = | ReadMtext | ReadDimension | ReadMultileader - | ReadSolid; + | ReadSolid + | ReadImage; export interface ReadBlock { /** The handle of the block's record, which an insert's block record points to. */ @@ -464,6 +512,21 @@ export interface ReadXref { readonly overlay: boolean; } +/** An image definition: the file an image shows. */ +export interface ReadImageDefinition { + readonly handle?: string | undefined; + /** Its name in the dictionary of image definitions. */ + readonly name: string; + /** The path as the file holds it, relative or absolute. */ + readonly path: string; + /** The pixels it states the file has. */ + readonly pixels: readonly [width: number, height: number]; + /** False when the file marks it not loaded, which the leading CAD app draws as a frame alone. */ + readonly loaded: boolean; + /** How many images of the file name it. */ + readonly images: number; +} + export interface ReadViewport { readonly handle?: string | undefined; readonly layer: string; diff --git a/src/rules.ts b/src/rules.ts index 05c14da..312643d 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -166,6 +166,28 @@ const R12_LEADERS = const R12_PARAGRAPHS = 'tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph'; const LINE_SPACING = "A paragraph's line spacing is a factor from 0.25 to 4"; +const R12_IMAGES = 'tsdraft writes no images to R12 drawings. Use DXF version "R2018" for an image'; +const IMAGE_PATH_EMPTY = "An image's path cannot be empty. The leading CAD app finds no file by it"; +const IMAGE_PATH_ABSOLUTE = + 'An image\'s path must start from the folder of the drawing\'s file, as "aerial.png" and "../images/aerial.png" do, and cannot start with /, \\ or a drive such as C:. The leading CAD app looks for the file of an absolute path in that folder alone, and on another machine finds none'; +const IMAGE_PATH_CHARS = + "An image's path cannot hold * ? < > | : or \". The leading CAD app finds no file whose name holds one of them"; +const IMAGE_PATH_LENGTH = + "An image's path cannot be longer than 32,000 characters. The leading CAD app finds no file by a path that comes to more than 32,767 characters with the folder of the drawing"; +const IMAGE_PATH_MULTIBYTE = + "An image's path cannot hold a backslash before M+, a digit from 1 to 5 and four hex digits, such as \\M+10041. The leading CAD app reads those as one character, and looks for another file. Write / there"; +const IMAGE_PIXELS = + "An image's pixels are its file's width and height in pixels, each a whole number from 1 to 2,147,483,647, which rasterSize reads from the file. The leading CAD app draws the file's own pixels at the size each has in the drawing, so pixels other than the file's plot it at the wrong size"; +const IMAGE_CLIP_POINTS = + "An image's clip is two opposite corners of a rectangle along its sides, or a polygon of at least 3 points"; +const IMAGE_CLIP_RECTANGLE = + "An image's clip of two corners must have its corners apart along the image's width and up its height, as written: it is a rectangle along the image's sides, and one of no width or height shows nothing"; +const IMAGE_CLIP_POLYGON = + "An image's clip of a polygon needs at least 3 points that differ, as written"; +const IMAGE_INVERT_CLIP = + "invertClip needs a clip: it shows the image outside the clip, and with no clip there is no outside"; +const IMAGE_PIXELS_DIFFER = + "Two images of one file must give it the same pixels: the file is written once, as one definition, with its pixels"; const R12_POLYLINES = 'tsdraft writes no arcs or widths of a polyline to R12 drawings. Use DXF version "R2018" for a polyline with bulges or a width'; const POLYLINE_WIDTH = @@ -685,6 +707,25 @@ export type XrefPath

= string extends P ? typeof XREF_PATH_MULTIBYTE : Description

; +/** + * Resolves to `P` when it is a path an image can have, and to the error message otherwise: a path + * is not empty, starts from the folder of the drawing's file, and holds no `* ? < > | : "`, no + * multibyte escape and no character a text cannot hold. Its length is checked when the code runs. + */ +export type ImagePath

= string extends P + ? P + : P extends "" + ? typeof IMAGE_PATH_EMPTY + : P extends `/${string}` | `\\${string}` + ? typeof IMAGE_PATH_ABSOLUTE + : Lowercase

extends `${LowerLetter}:${string}` + ? typeof IMAGE_PATH_ABSOLUTE + : P extends `${string}${Chars<'*?<>|:"'>}${string}` + ? typeof IMAGE_PATH_CHARS + : HasMultibyteEscape> extends true + ? typeof IMAGE_PATH_MULTIBYTE + : Description

; + /** * Resolves to `N` when it is a name a layout can have, and to the error message otherwise: a * name is not empty, is not `Model` in any case, holds none of `< > / \ " : ; ? * | , =` and @@ -916,6 +957,7 @@ export type R12Dimensions = typeof R12_DIMENSIONS; export type R12Leaders = typeof R12_LEADERS; export type R12Polylines = typeof R12_POLYLINES; export type R12Paragraphs = typeof R12_PARAGRAPHS; +export type R12Images = typeof R12_IMAGES; /** Resolves to `N` when it is a width a polyline can have, and to the error message otherwise. */ export type PolylineWidth = NotNegative; @@ -1535,6 +1577,7 @@ export const R12_ONLY = { leaders: R12_LEADERS, polylines: R12_POLYLINES, paragraphs: R12_PARAGRAPHS, + images: R12_IMAGES, } as const; /** What is wrong with a donut's hole, of `inside` across, or undefined. */ @@ -1981,6 +2024,101 @@ export function xrefPathProblem(path: unknown): string | undefined { return textProblem(path); } +/** Returns what is wrong with an image's path, or undefined when it is valid. */ +export function imagePathProblem(path: unknown): string | undefined { + if (typeof path !== "string") return "An image's path must be a string"; + if (path.length === 0) return IMAGE_PATH_EMPTY; + if (/^(?:[/\\]|[A-Za-z]:)/.test(path)) return IMAGE_PATH_ABSOLUTE; + if (/[*?<>|:"]/.test(path)) return IMAGE_PATH_CHARS; + if (path.length > 32000) return IMAGE_PATH_LENGTH; + if (/\\[Mm]\+[1-5][0-9A-Fa-f]{4}/.test(path)) return IMAGE_PATH_MULTIBYTE; + return textProblem(path); +} + +/** The most pixels an image's side may have: PNG's own most. */ +export const IMAGE_SIDE = 2_147_483_647; + +/** Returns what is wrong with an image's pixels, or undefined when they are valid. */ +export function imagePixelsProblem(pixels: unknown): string | undefined { + // A plain array of two, with no key but its indexes and its length. + if (!Array.isArray(pixels) || pixels.length !== 2 || Reflect.ownKeys(pixels).length !== 3) + return IMAGE_PIXELS; + // Each side read as a plain value, without a getter or the array's iterator. + const side = (i: number) => { + const item = Object.getOwnPropertyDescriptor(pixels, i); + const n: unknown = item && "value" in item ? item.value : undefined; + return Number.isInteger(n) && (n as number) >= 1 && (n as number) <= IMAGE_SIDE; + }; + return side(0) && side(1) ? undefined : IMAGE_PIXELS; +} + +/** + * Returns what is wrong with an image's clip, or undefined when it is valid. It is judged in the + * image's own axes, the vectors of one of its pixels `u` and `v`, from its corner `at`, with its + * points as written. + */ +export function imageClipProblem( + clip: unknown, + at: readonly [number, number], + u: readonly [number, number], + v: readonly [number, number], +): string | undefined { + if (!Array.isArray(clip) || clip.length < 2) return IMAGE_CLIP_POINTS; + if (Reflect.ownKeys(clip).length !== clip.length + 1) { + return "An image's clip must be a plain array of points, with no key but its indexes"; + } + const written2: (readonly [number, number])[] = []; + // Read by index as plain values, so an empty slot or a getter is a point that is missing. + const item = (list: unknown[], i: number): unknown => { + const found = Object.getOwnPropertyDescriptor(list, i); + return found && "value" in found ? found.value : undefined; + }; + for (let i = 0; i < clip.length; i++) { + const point = item(clip, i); + const [x, y]: unknown[] = + Array.isArray(point) && point.length === 2 && Reflect.ownKeys(point).length === 3 + ? [item(point, 0), item(point, 1)] + : []; + if ( + typeof x !== "number" || + typeof y !== "number" || + !Number.isFinite(x) || + !Number.isFinite(y) + ) { + return "Each point of an image's clip must be a point, [x, y], of finite numbers"; + } + const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (problem) return problem; + written2.push([written(x), written(y)]); + } + if (written2.length === 2) { + const det = u[0] * v[1] - u[1] * v[0]; + const along = ([x, y]: readonly [number, number]) => { + const [dx, dy] = [x - at[0], y - at[1]]; + return [(dx * v[1] - dy * v[0]) / det, (u[0] * dy - u[1] * dx) / det] as const; + }; + const [a, b] = [along(written2[0]!), along(written2[1]!)]; + // Apart by a millionth of a pixel at least, which the 15 digits a clip is written with keep. + const apart = (p: number, q: number) => + Math.abs(p - q) > 1e-6 * Math.max(1, Math.abs(p), Math.abs(q)); + return apart(a[0], b[0]) && apart(a[1], b[1]) ? undefined : IMAGE_CLIP_RECTANGLE; + } + const distinct = new Set(written2.map(([x, y]) => `${x},${y}`)); + return distinct.size >= 3 ? undefined : IMAGE_CLIP_POLYGON; +} + +/** The most points an image's clip may have. */ +export const IMAGE_CLIP_MOST = 10_000; + +/** What is wrong with a clip of more points than `IMAGE_CLIP_MOST`. */ +export const IMAGE_CLIP_MOST_PROBLEM = `An image's clip has at most ${IMAGE_CLIP_MOST} points`; + +/** What is wrong with `invertClip` on an image with no clip. */ +export const IMAGE_INVERT_WITHOUT_CLIP = IMAGE_INVERT_CLIP; + +/** What is wrong with two images of one file that give it other pixels. */ +export const IMAGE_PIXELS_SAME = IMAGE_PIXELS_DIFFER; + /** The fields of a block that an xref cannot have, since its file holds what it draws. */ export const XREF_REFUSED_FIELDS = ["entities", "base", "attributes"] as const; diff --git a/src/shape.ts b/src/shape.ts index f68727b..48b545b 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -10,6 +10,7 @@ import type { DimensionStyle, Drawing, Entity, + Image, Insert, Layer, Layout, @@ -58,6 +59,7 @@ const KINDS = [ "linear-dimension", "aligned-dimension", "leader", + "image", ] as const satisfies readonly Entity["kind"][]; /** What is wrong with an entity whose kind tsdraft does not know. */ @@ -513,6 +515,25 @@ function shapes(all: boolean, typed = all): Shapes { gap: ruled(number), }, ), + // A rule of `lint` reports the path, the pixels, the clip and the flags, whatever their type. + image: fields( + { + kind, + layer: string, + path: ruled(string), + pixels: ruled(point), + at: point, + width: number, + height: number, + }, + { + ...shared, + rotation: number, + clip: ruled(list(point)), + invertClip: ruled(boolean), + transparent: ruled(boolean), + }, + ), } satisfies Record; const entity: Check = (value, at, problems, extra) => { @@ -684,6 +705,7 @@ function shapes(all: boolean, typed = all): Shapes { layouts: ruled(table(layout)), dimensionStyles: ruled(table(dimensionStyle)), leaderStyles: ruled(table(leaderStyle)), + imageFrame: ruled(boolean), }, ); return { diff --git a/src/svg.ts b/src/svg.ts index 61785be..b60909b 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -14,6 +14,7 @@ import { type DimensionStyle, type Drawing, type Entity, + type Image, type Insert, type Layer, type Leader, @@ -41,6 +42,34 @@ import { type SideArc, } from "./polylines.ts"; import { boxer, type Boxer } from "./extents.ts"; +import { exactKey, imageCorners, imageDrawable, imageFrame, writtenImagePath } from "./images.ts"; +import { + base64, + base64Length, + hasAlpha, + opaquePng, + plotDecodes, + RASTER_PIXELS, + rasterInfo, + withoutExif, + type RasterInfo, +} from "./raster.ts"; + +/** + * The most pixels of a PNG with an alpha channel that a picture decodes and holds again without + * it: 4 megapixels, 16 MB of samples, where a logo has far fewer and the copy of an aerial would + * take more memory than a program has. + */ +export const OPAQUE_PIXELS = 4_194_304; + +/** + * Whether an image of a file that plots opaque is pictured from the file as it is, marked + * `data-opaque`: a PNG with an alpha channel of more than `OPAQUE_PIXELS`. + */ +const markedOpaque = (info: RasterInfo): boolean => + info.kind === "png" && + (info.color === 4 || info.color === 6) && + info.width * info.height > OPAQUE_PIXELS; import { fontInfo, STANDARD_FONT, capHeightOf } from "./fonts.ts"; import { fmt, written } from "./format.ts"; import { layerKey, layerKeys } from "./layers.ts"; @@ -230,11 +259,18 @@ export interface SvgOptions { readonly strokeWidth?: number; /** Draws the layers whose `plot` is false too. They are left out by default. */ readonly drawNoPlot?: boolean; + /** + * The bytes of each raster file the drawing's images show, by the image's path exactly as the + * drawing gives it: a PNG or a JPEG, which the picture holds. An image whose file is missing + * here, or is neither, is drawn as the leading CAD app draws an image whose file it cannot find: + * its frame, with its path written inside. + */ + readonly images?: Readonly>; /** * The drawing each xref stands for, by the xref's name. An insert of an xref draws the model * space of the drawing given here, and nothing when none is given. Given as * `{ drawing, xrefs }`, a drawing draws its attachments too, from the drawings its own `xrefs` - * gives, and so on down. + * gives, and so on down. `{ drawing, images }` gives the files of that drawing's images. */ readonly xrefs?: XrefDrawings; /** @@ -496,6 +532,159 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): }; /** The layout of each paragraph, a long value laid out once for the picture. */ const paragraphs = paragraphMeasurer(); + /** + * Each raster file the picture holds, by the files it was given in and the path it was given + * by: the drawing's own, or a referenced drawing's, whose paths start from its own folder. + */ + /** A file the picture can hold, and the id of each of its two pictures once written. */ + interface Raster { + readonly bytes: Uint8Array; + readonly info: RasterInfo; + /** False for a file the plot cannot draw, which the picture draws as a file not given. */ + readonly plotted: boolean; + /** Its pixels as they are, and with any transparency left out; null for one not read. */ + shown?: string | null; + opaque?: string | null; + } + // Keyed exactly, since a path may be long. + const rasters = new WeakMap>(); + let rastersHeld = 0; + /** Whether each clip an image gives can be drawn, read once however many images share it. */ + const clipsChecked = new WeakMap(); + const defs: string[] = []; + let clips = 0; + /** + * The raster file of an image's path, read once for the picture, or null for none it draws. An + * image of a referenced drawing, `from`, takes its file from that drawing's files alone. + */ + const rasterOf = (e: Image, from: Referenced | undefined): Raster | null => { + const given: unknown = from === undefined ? options.images : from.images; + if (typeof given !== "object" || given === null) return null; + let held = rasters.get(given); + if (!held) rasters.set(given, (held = new Map())); + const key = exactKey(e.path); + let found = held.get(key); + if (found === undefined) { + const item = Object.getOwnPropertyDescriptor(given, e.path); + const bytes = item && item.value instanceof Uint8Array ? item.value : undefined; + const info = bytes === undefined ? undefined : rasterInfo(bytes); + // A PNG the plot must decode and cannot, past `RASTER_PIXELS`, is drawn by neither. + const plotted = + info !== undefined && + (info.kind !== "png" || !plotDecodes(info) || info.width * info.height <= RASTER_PIXELS); + found = info === undefined ? null : { bytes: bytes!, info, plotted }; + held.set(key, found); + } + // Every image of a file is held to its pixels, whichever drawing it is in. + const info = found?.info; + if (info !== undefined && (info.width !== e.pixels[0] || info.height !== e.pixels[1])) { + throw new RangeError( + `The file of the image ${quoted(e.path)} is ${info.width} by ${info.height} pixels, and the drawing gives it ${e.pixels[0]} by ${e.pixels[1]}: the leading CAD app would plot it at the wrong size. Give it the file's pixels, which rasterSize reads`, + ); + } + return found; + }; + /** + * The id of the picture's image of a file, written the first time an image shows it: as it is, + * or for an image not marked transparent, with its transparency left out, as the leading CAD + * app plots one. A renderer drops the colors of a pixel of no alpha, which that app shows, so + * the picture holds the file again without its alpha, up to `OPAQUE_PIXELS`: past them it holds + * the file, and marks the image `data-opaque` for the plot. Null for a file that does not decode. + */ + const rasterId = (raster: Raster, opaque: boolean, path: string): string | null => { + const { info } = raster; + const copy = opaque && hasAlpha(info) && !markedOpaque(info); + const known = copy ? raster.opaque : raster.shown; + if (known !== undefined) 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++}`; + const kind = info.kind === "png" ? "image/png" : "image/jpeg"; + const head = ``); + } + if (copy) raster.opaque = id; + else raster.shown = id; + return id; + }; + /** + * An image: its file mapped onto its corners and cut to its clip, then its frame in its pen. + * One whose file is not given, or is not one the picture can hold, is its frame with its path + * inside it, as the leading CAD app draws one whose file it cannot find. + */ + const imageElement = ( + e: Image, + mark: string, + pen: Pen, + look: Look, + from: Referenced | undefined, + matrix: Matrix | undefined, + room: number, + ): string => { + const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + const raster = rasterOf(e, from); + const shown = + raster === null || !raster.plotted ? null : rasterId(raster, e.transparent !== true, e.path); + const parts: string[] = []; + // A closed outline, back to its first point, as a path of moves and lines. + const ring = (points: readonly Point[]) => + [...points, points[0]!] + .map(at) + .map(([x, y], i) => `${i === 0 ? "M" : "L"} ${precise(x)} ${precise(y)}`) + .join(" "); + if (shown !== null) { + const [p0, p1, , p3] = imageCorners(e).map(at) as [Point, Point, Point, Point]; + // The unit square of the picture's image, its top row first, onto the image's corners. + const place = [p1[0] - p0[0], p1[1] - p0[1], p0[0] - p3[0], p0[1] - p3[1], p3[0], p3[1]] + .map(precise) + .join(" "); + // A file too large to hold again is the file, which the plot shows opaque. + const marked = e.transparent !== true && markedOpaque(raster!.info); + const use = ``; + if (e.clip === undefined) parts.push(use); + else { + const id = `tsdraft-image-clip-${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}`, + ); + } + } else { + // The path as the file holds it, centered, as high as the image is wide over its letters. + const value = writtenImagePath(e.path); + const corners = imageCorners(e); + const middle: Point = [ + (corners[0][0] + corners[2][0]) / 2, + (corners[0][1] + corners[2][1]) / 2, + ]; + const text: Text = { + kind: "text", + layer: e.layer, + at: middle, + height: e.width / Math.max(1, value.length), + value, + rotation: e.rotation ?? 0, + align: "center", + valign: "middle", + }; + parts.push(entityToSvg(text, "", pen, look, undefined, matrix, room)); + } + if (drawing.imageFrame !== false) { + parts.push( + ``, + ); + } + return `${parts.join("")}`; + }; /** * The element of an entity that draws something of its own, where `matrix` puts it. Its * dashes stop once they pass the room left in the picture, and `write` then refuses it. @@ -522,6 +711,12 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const picture = style === undefined ? undefined : pictureOf(e, style, textStyle); return leaderToSvg(e, picture, textStyle, mark, drawnPen, look, matrix, room, sides); } + if (e.kind === "image") { + // One whose fields cannot be drawn, which `lint` refuses, draws nothing. + return imageDrawable(e, clipsChecked) + ? imageElement(e, mark, drawnPen, look, from, matrix, room) + : ""; + } if (e.kind !== "linear-dimension" && e.kind !== "aligned-dimension") { return entityToSvg(e, mark, drawnPen, look, styleOf(e, from), matrix, room, sides); } @@ -939,7 +1134,14 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ]; const tail = [` `, ``, ``]; if (!write([...head, ...tail].join("\n").length + 1)) refuse(space); - return [...head, ...parts.map((part) => ` ${part}`), ...tail].join("\n"); + const held = defs.length > 0 ? [` ${defs.join("")}`] : []; + return [ + head[0], + ...held, + ...head.slice(1), + ...parts.map((part) => ` ${part}`), + ...tail, + ].join("\n"); } // Each entity keeps its index in `drawing.entities`, for its element's data-entity. @@ -985,7 +1187,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ]; const tail = [` `, ``, ``]; if (!write([...head, ...tail].join("\n").length + 1)) refuse("model space"); - return [...head, ` ${body}`, ...tail].join("\n"); + const held = defs.length > 0 ? [` ${defs.join("")}`] : []; + return [head[0], ...held, ...head.slice(1), ` ${body}`, ...tail].join("\n"); } /** @@ -1085,7 +1288,7 @@ function viewOf(view: SvgOptions["view"]): [number, number, number, number] | un type Drawn = Exclude; /** An entity that is one shape, with a linetype and a lineweight it may have of its own. */ -type Shape = Exclude; +type Shape = Exclude; /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ function styled(e: Drawn): Pick { diff --git a/test/format.test.ts b/test/format.test.ts index 8ce9031..85cde93 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -39,7 +39,7 @@ function refusal(value: unknown): readonly Diagnostic[] { return assert.fail("fromJSON took the value"); } -const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension" or "leader"`; +const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader" or "image"`; test("a drawing goes to JSON and back unchanged", () => { const drawing = sample(); diff --git a/test/images.test.ts b/test/images.test.ts new file mode 100644 index 0000000..9ac666d --- /dev/null +++ b/test/images.test.ts @@ -0,0 +1,726 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { deflateSync } from "node:zlib"; +import { + createDrawing, + lint, + rasterSize, + readDXF, + toDXF, + toPDF, + toSVG, + type Drawing, + type Entity, + type ReadImage, +} from "../src/index.ts"; +import { + base64, + inflate, + pngPixels, + rasterInfo, + withoutExif, + type PngInfo, +} from "../src/raster.ts"; +import { OPAQUE_PIXELS, svgWithin } from "../src/svg.ts"; +import { timeLimit } from "./time-limit.ts"; + +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); +const crc = (bytes: Uint8Array): number => { + let c = 0xffffffff; + for (const b of bytes) c = crcTable[(c ^ b) & 0xff]! ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +}; +const chunk = (type: string, data: Uint8Array): Uint8Array => { + const out = new Uint8Array(12 + data.length); + const view = new DataView(out.buffer); + view.setUint32(0, data.length); + out.set( + [...type].map((c) => c.charCodeAt(0)), + 4, + ); + out.set(data, 8); + view.setUint32(8 + data.length, crc(out.subarray(4, 8 + data.length))); + return out; +}; + +/** A PNG of 8 bits a sample, its samples given pixel by pixel. */ +function png( + width: number, + height: number, + color: number, + pixel: (x: number, y: number) => number[], +): Uint8Array { + const samples = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color]!; + const raw = new Uint8Array((width * samples + 1) * height); + // Filter 0 on every row, so the samples are as given. + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + raw.set(pixel(x, y).slice(0, samples), y * (width * samples + 1) + 1 + x * samples); + } + } + const header = new Uint8Array(13); + new DataView(header.buffer).setUint32(0, width); + new DataView(header.buffer).setUint32(4, height); + header.set([8, color, 0, 0, 0], 8); + const parts = [ + new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), + chunk("IHDR", header), + ...(color === 3 ? [chunk("PLTE", new Uint8Array([255, 0, 0, 0, 255, 0, 0, 0, 255]))] : []), + chunk("IDAT", new Uint8Array(deflateSync(raw))), + chunk("IEND", new Uint8Array()), + ]; + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let at = 0; + for (const p of parts) { + out.set(p, at); + at += p.length; + } + return out; +} + +/** The smallest JPEG header: a start of image, an APP1 of EXIF, a start of frame and its end. */ +function jpeg(width: number, height: number): Uint8Array { + const exif = [0x45, 0x78, 0x69, 0x66, 0, 0, 0x4d, 0x4d, 0, 0x2a, 0, 0, 0, 8]; + const start = [0xff, 0xd8, 0xff, 0xe1, 0, exif.length + 2]; + const frame = [0xff, 0xc0, 0, 11, 8, height >> 8, height & 255, width >> 8, width & 255, 1]; + return new Uint8Array([...start, ...exif, ...frame, 1, 0x11, 0, 0xff, 0xda, 0, 2, 0xff, 0xd9]); +} + +const seeded = (seed: number) => () => { + seed = (seed * 1103515245 + 12345) % 2147483648; + return seed / 2147483648; +}; + +test("a PNG's pixels come back of each color type, and a JPEG's size from its header", () => { + for (const color of [0, 2, 3, 4, 6]) { + const file = png(5, 3, color, (x, y) => + Array.from({ length: 4 }, (_, k) => (x * 40 + y * 7 + k) % 3), + ); + const info = rasterInfo(file) as PngInfo; + assert.deepEqual([info.width, info.height, info.color], [5, 3, color]); + const pixels = pngPixels(info)!; + assert.equal(pixels.samples.length, 5 * 3 * pixels.channels); + } + assert.deepEqual(rasterSize(jpeg(640, 480)), [640, 480]); + // A JPEG keeps its pixels and loses the EXIF that would turn it in a browser. + assert.equal(withoutExif(jpeg(2, 2)).length, jpeg(2, 2).length - 18); + assert.equal(rasterSize(new Uint8Array([1, 2, 3])), undefined); +}); + +test("a broken raster file is answered with undefined, never a throw, and in time", () => { + const random = seeded(17); + const files = [ + ...[0, 2, 3, 4, 6].map((color) => png(9, 7, color, (x, y) => [x * 20, y * 30, 100, 200])), + jpeg(300, 200), + ]; + const limit = timeLimit(4000); + const start = performance.now(); + for (let n = 0; n < 3000; n++) { + const file = new Uint8Array(files[n % files.length]!); + const kind = Math.floor(random() * 4); + let bytes: Uint8Array = file; + if (kind === 0) { + for (let k = 0; k < 1 + random() * 8; k++) { + file[Math.floor(random() * file.length)]! ^= 1 << Math.floor(random() * 8); + } + } else if (kind === 1) bytes = file.subarray(0, Math.floor(random() * file.length)); + else if (kind === 2) { + // A size or a length made huge. + file.set([0xff, 0xff, 0xff, 0x7f], 8 + Math.floor(random() * Math.min(30, file.length - 12))); + } else file.fill(0, Math.floor(random() * file.length)); + const info = rasterInfo(bytes); + if (info?.kind === "png") pngPixels(info); + inflate(bytes.subarray(Math.floor(random() * bytes.length)), 1 << 16); + } + assert.ok(performance.now() - start < limit, "the fuzz finished in time"); +}); + +test("inflate stops at its limit, and a hostile size decodes to nothing", () => { + assert.equal(inflate(new Uint8Array(deflateSync(new Uint8Array(1 << 20))), 1000), undefined); + // A PNG that says it is 2^31-1 pixels wide. + const file = png(4, 4, 2, () => [1, 2, 3]); + new DataView(file.buffer).setUint32(16, 0x7fffffff); + const info = rasterInfo(file); + assert.ok(info === undefined || (info.kind === "png" && pngPixels(info) === undefined)); +}); + +/** A drawing with one image on a layout, its fields as given. */ +const withImage = (image: Readonly>): Drawing => ({ + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [], + layouts: [ + { + name: "S", + paper: "ANSI B", + viewports: [], + entities: [ + { + kind: "image", + layer: "0", + path: "a.png", + pixels: [4, 4], + at: [1, 1], + width: 2, + height: 2, + ...image, + } as unknown as Entity, + ], + }, + ], +}); + +test("lint never throws on an image of hostile fields, and the writers and plots stay bounded", () => { + const random = seeded(29); + // A list with two empty slots. + const holes: unknown[] = []; + holes.length = 2; + const values: unknown[] = [ + undefined, + null, + 0, + -1, + 1e99, + 1e100, + Number.NaN, + Infinity, + "", + "x", + true, + {}, + [], + [1], + [1, 2], + [0, 0], + [2 ** 31, 1], + [[1, 1]], + [ + [1, 1], + [1, 1], + ], + [ + [1, 1], + [3, 3], + ], + Array.from({ length: 10_001 }, (_, i) => [i, i % 7]), + [undefined, [1, 1]], + holes, + [ + [Number.NaN, 1], + [2, 2], + [3, 1], + ], + "C:\\a.png", + "/a.png", + "a".repeat(40_000), + ]; + const fields = [ + "path", + "pixels", + "at", + "width", + "height", + "rotation", + "clip", + "invertClip", + "transparent", + ]; + const files = { "a.png": png(4, 4, 6, (x) => [x * 60, 0, 0, x * 60]) }; + const limit = timeLimit(20_000); + const start = performance.now(); + for (let n = 0; n < 400; n++) { + const image: Record = {}; + for (let k = 0; k < 1 + Math.floor(random() * 3); k++) { + const field = fields[Math.floor(random() * fields.length)]!; + image[field] = values[Math.floor(random() * values.length)]; + } + const drawing = withImage(image); + if (lint(drawing).some((d) => d.severity === "error")) assert.throws(() => toDXF(drawing)); + else toDXF(drawing); + // The plots draw any drawing, and throw nothing but a RangeError. + try { + toSVG(drawing, { layout: "S", images: files }); + toPDF(drawing, { images: files }); + } catch (error) { + assert.ok(error instanceof RangeError, `drawing ${n}: ${(error as Error).message}`); + } + } + assert.ok(performance.now() - start < limit, "the fuzz finished in time"); +}); + +test("an image's rules are compile errors and runtime errors", () => { + const r12 = createDrawing({ dxf: "R12" }); + const d = createDrawing(); + const sized = { pixels: [4, 4], width: 1 } as const; + // @ts-expect-error: R12 holds no image. + assert.throws(() => r12.image("a.png", [0, 0], sized), /no images to R12/); + // @ts-expect-error: an absolute path is refused. + assert.throws(() => d.image("C:\\a.png", [0, 0], sized), /must start from the folder/); + // @ts-expect-error: an empty path is refused. + assert.throws(() => d.image("", [0, 0], sized), /cannot be empty/); + // @ts-expect-error: a width of 0. + assert.throws(() => d.image("a.png", [0, 0], { pixels: [4, 4], width: 0 }), /width/); + assert.throws(() => d.image("a.png", [0, 0], { pixels: [4, 0], width: 1 }), /from 1 to/); + const rectangle: [number, number][] = [ + [0, 0], + [1, 0], + ]; + assert.throws(() => d.image("a.png", [0, 0], { ...sized, clip: rectangle }), /apart along/); + const polygon: [number, number][] = [ + [0, 0], + [1, 1], + [0, 0], + ]; + assert.throws(() => d.image("a.png", [0, 0], { ...sized, clip: polygon }), /3 points that/); + assert.throws(() => d.image("a.png", [0, 0], { ...sized, invertClip: true }), /needs a clip/); + d.image("a.png", [0, 0], { pixels: [4, 2], width: 1 }); + const [made] = d.build().entities as Extract[]; + assert.equal(made!.height, 0.5); + // Two images of one file that give it other pixels. + d.image("a.png", [5, 0], { pixels: [4, 3], width: 1 }); + assert.match( + lint(d.build()) + .map((x) => x.message) + .join("\n"), + /same pixels/, + ); +}); + +test("readDXF reads tsdraft's images back, with each file's definition once", async () => { + const d = createDrawing(); + d.layer("0", {}, () => { + d.image("images/a.png", [0, 0], { + pixels: [4, 2], + width: 4, + clip: [ + [1, 0.5], + [3, 1.5], + ], + }); + d.image("images\\a.png", [5, 0], { + pixels: [4, 2], + width: 4, + invertClip: true, + clip: [ + [6, 0.5], + [8, 0.4], + [7, 1.5], + ], + }); + d.image("b.jpg", [9, 0], { pixels: [3, 3], width: 1, transparent: true }); + }); + const read = await readDXF(toDXF(d.build()), { geometry: true }); + assert.deepEqual( + read.images.map(({ name, path, images }) => [name, path, images]), + [ + ["a", "images\\a.png", 2], + ["b", "b.jpg", 1], + ], + ); + const [first, second, third] = (read.model.entities ?? []) as ReadImage[]; + const rounded = (points: readonly (readonly number[])[] | undefined) => + points?.map((p) => p.map((v) => Math.round(v * 1e6) / 1e6)); + assert.equal(first!.path, "images\\a.png"); + // Two opposite corners of the rectangle, as the file holds them: its top left in the image's + // pixels, then its bottom right. + assert.deepEqual(rounded(first!.clip), [ + [1, 1.5], + [3, 0.5], + ]); + assert.equal(second!.clip!.length, 3); + assert.equal(second!.invertClip, true); + assert.equal(third!.transparent, true); +}); + +test("many files of one name are named in time, each by the next free number", () => { + const d = createDrawing({ units: "ft", dxf: "R2018" }); + d.image("x/a.png", [0, 0], { pixels: [2, 2], width: 1 }); + d.image("a2.png", [2, 0], { pixels: [2, 2], width: 1 }); + for (let i = 0; i < 20_000; i++) d.image(`d${i}/a.png`, [i, 4], { pixels: [2, 2], width: 1 }); + const drawing = d.build(); + const start = performance.now(); + const dxf = toDXF(drawing); + assert.ok(performance.now() - start < timeLimit(8000), "written in time"); + // `a2` is the second file's own name, so the third file of `a` takes 3. + const names = [...dxf.matchAll(/\n *3\r?\n(a\d*)\r?\n *350\r?\n/g)].map((m) => m[1]); + assert.deepEqual(names.slice(0, 4), ["a", "a10", "a100", "a1000"]); + assert.equal(new Set(names).size, 20_002); + assert.ok(names.includes("a20002") && !names.includes("a20003")); +}); + +test("toPDF reads a file once however many times a sheet places it", () => { + // A megabyte of noise, which deflate cannot shrink. + const bytes = png(600, 600, 2, (x, y) => { + let h = Math.imul(x, 374761393) + Math.imul(y, 668265263); + h = Math.imul(h ^ (h >>> 13), 1274126177); + return [h & 255, (h >>> 8) & 255, (h >>> 16) & 255]; + }); + assert.ok(bytes.length > 1_000_000); + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.layout("S", { paper: "ANSI B" }, () => { + for (let i = 0; i < 600; i++) { + d.image("aerial.png", [(i % 30) * 0.5, Math.floor(i / 30) * 0.5], { + pixels: [600, 600], + width: 0.4, + }); + } + }); + const drawing = d.build(); + const start = performance.now(); + const pdf = toPDF(drawing, { images: { "aerial.png": bytes }, deflate: (b) => deflateSync(b) }); + assert.ok(performance.now() - start < timeLimit(1500), "plotted in time"); + // The file is embedded once. + assert.equal(new TextDecoder("latin1").decode(pdf).match(/\/Subtype \/Image/g)?.length, 1); +}); + +test("an xref's images take their files from the xref's own, never the sheet's", () => { + const sheetFile = png(4, 4, 2, () => [255, 0, 0]); + const baseFile = png(8, 8, 2, () => [0, 0, 255]); + const base = createDrawing({ units: "ft" }); + base.image("aerial.png", [0, 0], { pixels: [8, 8], width: 100 }); + const sheet = createDrawing({ units: "ft" }).xref("BASE", "../base/base.dwg"); + sheet.image("aerial.png", [200, 0], { pixels: [4, 4], width: 50 }).insert("BASE", [0, 0]); + const drawing = sheet.build(); + const images = { "aerial.png": sheetFile }; + // Without the base's files its image is drawn as one whose file is missing: its path. + const alone = toSVG(drawing, { xrefs: { BASE: base.build() }, images }); + assert.equal(alone.match(/aerial\.png + toSVG(drawing, { + xrefs: { BASE: { drawing: base.build(), images: { "aerial.png": sheetFile } } }, + images, + }), + RangeError, + ); +}); + +test("the box of a turned image's clip holds the frame's four corners", () => { + const d = createDrawing({ units: "ft", dxf: "R2018" }); + d.image("a.png", [0, 0], { + pixels: [1, 1], + width: 5, + rotation: 45, + clip: [ + [10, 0], + [0, 1], + ], + }); + const viewBox = /viewBox="([^"]+)"/.exec(toSVG(d.build(), { margin: 0 }))![1]!.split(" "); + // The picture's y runs down: the frame's lowest corner, 4.5 below the image, is its bottom. + const [, top, , height] = viewBox.map(Number) as [number, number, number, number]; + assert.ok(Math.abs(top + height - 4.5) < 1e-6, `${top + height}`); +}); + +test("the readers keep a clip that the display flags turn on, whatever its own flag says", async () => { + const d = createDrawing({ dxf: "R2018" }); + d.image("a.png", [0, 0], { + pixels: [4, 2], + width: 4, + clip: [ + [1, 0.5], + [3, 1.5], + ], + }); + d.image("a.png", [5, 0], { pixels: [4, 2], width: 4 }); + // The whole image's boundary inverted: a hole of it all. + d.image("a.png", [10, 0], { + pixels: [4, 2], + width: 4, + clip: [ + [10, 0], + [14, 2], + ], + invertClip: true, + }); + const dxf = toDXF(d.build()); + // Each clip turned off by its own flag, 280, which the display flags overrule: the IMAGE + // records' 280, which comes before their 281. + let turned = 0; + const off = dxf.replace(/\r\n0\r\nIMAGE\r\n5\r\n[^]*?\r\n281\r\n/g, (record) => { + if (record.includes("\r\n280\r\n1\r\n")) turned++; + return record.replace("\r\n280\r\n1\r\n", "\r\n280\r\n0\r\n"); + }); + assert.equal(turned, 2); + const read = await readDXF(off, { geometry: true }); + const [clipped, whole, hole] = read.model.entities!.filter( + (e) => e.kind === "image", + ) as ReadImage[]; + assert.equal(hole!.clip?.length, 2); + assert.equal(hole!.invertClip, true); + assert.deepEqual(clipped!.clip, [ + [1, 1.5], + [3, 0.5], + ]); + // The whole image's boundary, which the writer gives an image with no clip, is no clip. + assert.equal(whole!.clip, undefined); +}); + +test("an image not marked transparent is pictured with the colors of its transparent pixels", () => { + const file = png(10, 10, 6, () => [255, 0, 0, 0]); + const svgOf = (transparent: boolean) => { + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.image("a.png", [0, 0], { pixels: [10, 10], width: 1, transparent }); + return toSVG(d.build(), { images: { "a.png": file } }); + }; + const held = (svg: string) => { + const data = /href="data:image\/png;base64,([^"]+)"/.exec(svg)![1]!; + return rasterInfo(new Uint8Array(Buffer.from(data, "base64"))) as PngInfo; + }; + const opaque = held(svgOf(false)); + assert.equal(opaque.color, 2); + assert.deepEqual([...pngPixels(opaque)!.samples.subarray(0, 3)], [255, 0, 0]); + assert.doesNotMatch(svgOf(false), /filter/); + assert.equal(held(svgOf(true)).color, 6); + // The PDF compresses the picture's stored copy again, and shows it without a soft mask. + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.layout("S", { paper: "ANSI B" }, () => { + d.image("a.png", [1, 1], { pixels: [10, 10], width: 1 }); + }); + const pdf = new TextDecoder("latin1").decode( + toPDF(d.build(), { images: { "a.png": file }, deflate: (b) => deflateSync(b) }), + ); + assert.doesNotMatch(pdf, /SMask/); + assert.doesNotMatch(pdf, /Predictor/); +}); + +test("two long paths that agree where a long key is sampled are two files", () => { + const a = `${"a".repeat(16_500)}/x.png`; + const b = `${a.slice(0, 40)}b${a.slice(41)}`; + const d = createDrawing({ units: "in", dxf: "R2018" }); + for (const [i, path] of [a, b, a].entries()) { + d.image(path as "x.png", [i * 2, 0], { pixels: [1, 1], width: 1 }); + } + const drawing = d.build(); + assert.deepEqual(lint(drawing), []); + const dxf = toDXF(drawing); + assert.equal(dxf.match(/\r\n0\r\nIMAGEDEF\r\n/g)?.length, 2); +}); + +test("a damaged PNG is left out of the PDF, which stays whole", () => { + const file = png(4, 4, 6, (x) => [x * 60, 0, 0, 128]); + // Its compressed data broken: its header still reads. + const broken = file.slice(); + broken.fill(0, 41, 60); + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.layout("S", { paper: "ANSI B" }, () => { + d.image("a.png", [1, 1], { pixels: [4, 4], width: 1, transparent: true }); + }); + const pdf = new TextDecoder("latin1").decode( + toPDF(d.build(), { images: { "a.png": broken }, deflate: (b) => deflateSync(b) }), + ); + assert.doesNotMatch(pdf, /undefined/); + assert.doesNotMatch(pdf, /\/Subtype \/Image/); +}); + +test("an image of malformed fields draws nothing, and lint reports it without a throw", () => { + const sound = { kind: "image", layer: "0", path: "a.png", pixels: [1, 1], at: [0, 0] }; + const shapes: Record[] = [ + { ...sound, width: 1, height: 1, clip: [] }, + { ...sound, width: 1, height: 1, clip: [[0, 0]] }, + { ...sound, pixels: Object.assign([1, 1], { [Symbol.iterator]: null }), width: 1, height: 1 }, + { ...sound, width: 0, height: 1 }, + ]; + for (const image of shapes) { + const drawing: Drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [image as unknown as Entity], + }; + assert.ok(lint(drawing).some((found) => found.severity === "error")); + assert.doesNotMatch(toSVG(drawing, { images: {} }), /data-image/); + } +}); + +test("a clip many images share is read once a picture, and one with other keys is refused", () => { + let reads = 0; + const points = Array.from({ length: 1000 }, (_, i): [number, number] => [ + Math.cos(i / 100), + Math.sin(i / 100), + ]); + const shared = new Proxy(points, { + getOwnPropertyDescriptor(target, key) { + reads++; + return Reflect.getOwnPropertyDescriptor(target, key); + }, + }); + const entities = Array.from({ length: 100 }, (_, i) => ({ + kind: "image", + layer: "0", + path: "a.png", + pixels: [4, 4], + at: [i * 3 - 1.5, -1.5], + width: 3, + height: 3, + clip: shared, + })); + const drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities, + imageFrame: false, + } as unknown as Drawing; + toSVG(drawing); + assert.ok(reads < 5000, `${reads} reads`); + // A clip with a key beyond its indexes is no plain list, which lint refuses and toSVG leaves out. + const odd = Object.assign( + [ + [0, 0], + [1, 1], + ], + { map: null }, + ); + const one = { ...drawing, entities: [{ ...entities[0]!, clip: odd }] } as unknown as Drawing; + assert.ok(lint(one).some((found) => found.rule === "image" && found.severity === "error")); + assert.doesNotMatch(toSVG(one), /data-image/); +}); + +test("a PNG stored without compression that is too large to decode is embedded as it is", () => { + // A header of 10,001 by 10,000 gray pixels, its data an empty stored block and then any: + // the PDF holds it as it is, and does not decode it. + const header = new Uint8Array(13); + new DataView(header.buffer).setUint32(0, 10_001); + new DataView(header.buffer).setUint32(4, 10_000); + header.set([8, 0, 0, 0, 0], 8); + const file = new Uint8Array([ + 137, + 80, + 78, + 71, + 13, + 10, + 26, + 10, + ...chunk("IHDR", header), + ...chunk("IDAT", new Uint8Array([0x78, 0x01, 0, 0, 0, 255, 255, 3, 0])), + ...chunk("IEND", new Uint8Array()), + ]); + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.layout("S", { paper: "ANSI B" }, () => { + d.image("big.png", [1, 1], { pixels: [10_001, 10_000], width: 2 }); + }); + const pdf = new TextDecoder("latin1").decode( + toPDF(d.build(), { images: { "big.png": file }, deflate: (b) => deflateSync(b) }), + ); + assert.equal(pdf.match(/\/Subtype \/Image/g)?.length, 1); +}); + +test("every image of a file is held to its pixels, in an xref given the sheet's files too", () => { + const images = { "a.png": png(1, 1, 2, () => [1, 2, 3]) }; + const base = createDrawing({ units: "ft" }); + base.image("a.png", [0, 0], { pixels: [2, 2], width: 1 }); + const sheet = createDrawing({ units: "ft" }).xref("BASE", "base.dwg"); + sheet.image("a.png", [5, 0], { pixels: [1, 1], width: 1 }).insert("BASE", [0, 0]); + assert.throws( + () => toSVG(sheet.build(), { images, xrefs: { BASE: { drawing: base.build(), images } } }), + RangeError, + ); +}); + +test("a PNG with an alpha channel too large to copy is pictured as it is and plotted opaque", () => { + const side = 2049; + assert.ok(side * side > OPAQUE_PIXELS); + // Red with no alpha, every pixel. + const raw = new Uint8Array((side * 4 + 1) * side); + for (let y = 0; y < side; y++) { + for (let x = 0; x < side; x++) raw[y * (side * 4 + 1) + 1 + x * 4] = 255; + } + const header = new Uint8Array(13); + new DataView(header.buffer).setUint32(0, side); + new DataView(header.buffer).setUint32(4, side); + header.set([8, 6, 0, 0, 0], 8); + const file = new Uint8Array([ + 137, + 80, + 78, + 71, + 13, + 10, + 26, + 10, + ...chunk("IHDR", header), + ...chunk("IDAT", new Uint8Array(deflateSync(raw))), + ...chunk("IEND", new Uint8Array()), + ]); + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.layout("S", { paper: "ANSI B" }, () => { + d.image("big.png", [1, 1], { pixels: [side, side], width: 2 }); + }); + const drawing = d.build(); + const images = { "big.png": file }; + const svg = toSVG(drawing, { layout: "S", images }); + assert.match(svg, /]*data-opaque=""/); + assert.ok(svg.length < file.length * 2, "the file is held as it is"); + const pdf = new TextDecoder("latin1").decode( + toPDF(drawing, { images, deflate: (b) => deflateSync(b) }), + ); + assert.equal(pdf.match(/\/Subtype \/Image/g)?.length, 1); + assert.doesNotMatch(pdf, /SMask/); +}); + +test("base64 is one flat string, and a file too long for the picture is refused before it is read", () => { + for (let n = 0; n < 7; n++) { + const bytes = Uint8Array.from({ length: n }, (_, i) => i * 77 + 3); + assert.equal(base64(bytes), Buffer.from(bytes).toString("base64")); + } + const file = png(400, 400, 2, (x, y) => [x, y, (x * y) & 255]); + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.image("a.png", [0, 0], { pixels: [400, 400], width: 1 }); + // A walk limit of 100 holds 25,000 characters: the file's text takes more. + assert.ok(base64(file).length > 25_000); + assert.throws(() => svgWithin(d.build(), { images: { "a.png": file } }, 100), RangeError); +}); + +test("a PNG the plot must decode past the most pixels it decodes is its frame and path in both", () => { + const header = new Uint8Array(13); + new DataView(header.buffer).setUint32(0, 10_001); + new DataView(header.buffer).setUint32(4, 10_000); + header.set([8, 6, 0, 0, 0], 8); + const file = new Uint8Array([ + 137, + 80, + 78, + 71, + 13, + 10, + 26, + 10, + ...chunk("IHDR", header), + ...chunk("IDAT", new Uint8Array([0x78, 0x9c, 3, 0])), + ...chunk("IEND", new Uint8Array()), + ]); + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.layout("S", { paper: "ANSI B" }, () => { + d.image("big.png", [1, 1], { pixels: [10_001, 10_000], width: 2 }); + }); + const drawing = d.build(); + const images = { "big.png": file }; + const svg = toSVG(drawing, { layout: "S", images }); + assert.doesNotMatch(svg, /big\.png deflateSync(b) }), + ); + assert.doesNotMatch(pdf, /\/Subtype \/Image/); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index 4afe2fe..fa15273 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -17,6 +17,7 @@ import type { import { written, writtenAngle } from "../src/format.ts"; import { idHandle } from "../src/handles.ts"; import { findLeaderStyle, leaderPicture } from "../src/leaders.ts"; +import { fromImagePixels, imageClip, imageVectors, writtenImagePath } from "../src/images.ts"; import { layerKey } from "../src/layers.ts"; import { entityLinetype, lineweightCode } from "../src/linetypes.ts"; import { paragraphAttachment, paragraphTurn } from "../src/paragraphs.ts"; @@ -433,6 +434,43 @@ export function readProblems( } return; } + case "image": { + if (!kind("image") || got.kind !== "image") return; + if (got.path !== writtenImagePath(want.path)) + say(`${label}: path ${JSON.stringify(got.path)}`); + if (got.pixels[0] !== want.pixels[0] || got.pixels[1] !== want.pixels[1]) { + say(`${label}: pixels ${got.pixels.join(" by ")}`); + } + const [u, v] = imageVectors(want); + if (!nearPoint(got.at, point(want.at)) || !nearPoint(got.u, u) || !nearPoint(got.v, v)) { + say(`${label}: at ${got.at}, u ${got.u}, v ${got.v}`); + } + // The clip as both readers give it: in the world, a rectangle by its lower and upper + // corners in the image's pixels, a polygon without its first point again. + const clip = imageClip(want); + const at = point(want.at); + const world = + want.clip === undefined + ? undefined + : (clip.type === 2 ? clip.points.slice(0, -1) : clip.points).map((p) => + fromImagePixels(at, u, v, want.pixels, p), + ); + if ( + (world === undefined) !== (got.clip === undefined) || + (world !== undefined && + (world.length !== got.clip!.length || + world.some((p, k) => !nearPoint(got.clip![k]!, p)))) + ) { + say(`${label}: clip ${JSON.stringify(got.clip)}`); + } + if ((got.invertClip ?? false) !== (want.invertClip ?? false)) say(`${label}: invertClip`); + if ((got.transparent ?? false) !== (want.transparent ?? false)) + say(`${label}: transparent`); + for (const flag of ["hidden", "unclipped"] as const) { + if (got[flag]) say(`${label}: ${flag}`); + } + return; + } } }; diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index 5e03ec8..4ef4498 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -58,9 +58,38 @@ export function seedFiles(): Uint8Array[] { [1, 1], ]); }); - return [toDXF(sheet), toDXF(kitchen), toDXF(d.build(), { version: "R12" })].map((t) => - encoder.encode(t), + // Images in model space and in a block, clipped both ways, with their objects. + const images = createDrawing({ units: "ft" }); + images.block("LOGO", {}, () => + images.layer("0", {}, () => images.image("logo.png", [0, 0], { pixels: [8, 4], width: 2 })), ); + images.layer("A", { color: 1 }, () => { + images.image("a.png", [0, 0], { + pixels: [4, 2], + width: 4, + clip: [ + [1, 0.5], + [3, 1.5], + ], + }); + images.image("b/a.png", [5, 0], { + pixels: [4, 4], + width: 4, + invertClip: true, + clip: [ + [6, 1], + [8, 1], + [7, 3], + ], + }); + images.insert("LOGO", [0, 10]); + }); + return [ + toDXF(sheet), + toDXF(kitchen), + toDXF(d.build(), { version: "R12" }), + toDXF(images.build()), + ].map((t) => encoder.encode(t)); } const NUMBERS = ["0", "1", "-1", "4294967295", "1e308", "-1e308", "1e999", "NaN", "", "1.#QNAN"]; diff --git a/test/shape.test.ts b/test/shape.test.ts index 356431c..f4d8fda 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -153,6 +153,25 @@ const kinds: { gap: 0.02, id: "i", }, + image: { + kind: "image", + layer: "0", + path: "images/aerial.png", + pixels: [400, 200], + at: [50, 0], + width: 20, + height: 10, + rotation: 15, + clip: [ + [52, 2], + [60, 1], + [58, 8], + ], + invertClip: true, + transparent: true, + id: "m", + ...styled, + }, }; /** A polyline of one width, with every field the polyline of `kinds` leaves out. */ @@ -192,6 +211,7 @@ const full: Required & { units: "ft", dxf: "R2018", linetypeScale: 2, + imageFrame: false, linetypes: [{ name: "DD", description: "Dash dot", pattern: [0.5, -0.25, 0, -0.25] }], textStyles: [{ name: "NOTES", font: "Arial", widthFactor: 0.9, obliqueAngle: 10 }], dimensionStyles: [ @@ -517,7 +537,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #10: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #11: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ From 8c6ced25d2a45e881430a346ac0b0a2f762d8336 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 19 Nov 2026 22:39:21 -0500 Subject: [PATCH 08/35] Radius, diameter and jogged radius dimensions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Radius, diameter and jogged radius dimensions, drawn as the leading CAD app draws them: - `d.radiusDimension(center, point, options)` measures from the center of a circle or an arc to `point`, a point of the circle its line meets. The leading CAD app writes an R before the measurement, and `<>` in `text` stands for both: `"<> TYP."` reads `R2.50 TYP.`. - `d.diameterDimension(center, point, options)` measures twice that, read with a diameter sign, `∅5.00`, its line across the circle with an arrowhead at each end. - `d.joggedRadiusDimension(center, point, start, jog, options)` measures an arc whose center is far off: its line starts at `start`, jogs across at `jog`, and runs on toward the center to `point`. The text of a radius or a diameter stands outside the circle, past the arrowhead, unless `textFromCenter` places it along the line: inside the circle, outside it, or past the center for less than 0. The leading CAD app keeps a placed text two arrow sizes and a gap clear of the circle. The line to the center is always drawn. A dimension style sets two things of these kinds alone: `radialText: "horizontal"` levels their text, on a short landing outside a circle and across a jogged dimension's line, and `jogAngle` sets the angle of the jog, from 5 to 90 degrees, 45 by default. A standard's dimension style takes both. `lint` refuses a style with a `prefix` for these kinds, which the leading CAD app may put in place of its R or its diameter sign; a placed text in a style that levels the text or centers it in its line; a jogged dimension in a style that centers its text, or whose jog is so near the circle that the last stretch of its line cannot hold the text; and a radius of 0. `toDXF` writes the three kinds, and `readDXF` reads them as `radial-dimension`, with their center, their point, a jogged one's start and jog, and whether the text was placed. The command's dimension summary lists them. The font tables hold the diameter sign, with the advance a paragraph gives it in a font that lacks it, where the leading CAD app sets it in another font. Every other number of the tables is as it was. `toPDF` plots the diameter sign as Ø in a font that lacks it, as the leading CAD app plots it. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 9 + GUIDE.md | 6 +- cli/src/state.ts | 7 +- cli/src/worker.ts | 29 ++- docs/assets/site-plan-dark.svg | 8 + docs/assets/site-plan-light.svg | 8 + docs/dimensions.md | 37 ++- docs/reading.md | 8 +- examples/site-plan.ts | 8 + src/arrowheads.ts | 6 + src/dimensions.ts | 385 ++++++++++++++++++++++++++++- src/drawing.ts | 215 +++++++++++++++- src/dxf-r2018.ts | 90 ++++++- src/extents.ts | 3 + src/font-metrics.ts | 424 +++++++++++++++++--------------- src/index.ts | 9 + src/inspect.ts | 10 +- src/lint.ts | 18 +- src/pdf.ts | 18 +- src/read/check.ts | 17 ++ src/read/dxf.ts | 12 +- src/read/entities.ts | 40 ++- src/read/model.ts | 25 ++ src/rules.ts | 44 ++++ src/shape.ts | 27 ++ src/standard/document.ts | 7 + src/standard/lint.ts | 6 +- src/standard/literal.ts | 13 +- src/standard/shape.ts | 15 ++ src/svg.ts | 13 +- standard.json | 6 + standard.schema.json | 24 ++ test/bounded.test.ts | 18 ++ test/dimensions.test.ts | 59 +++++ test/measure.test.ts | 2 +- test/pdf.test.ts | 5 +- test/read-agreement.ts | 60 ++++- test/shape.test.ts | 40 ++- test/standard-lint.test.ts | 4 +- 39 files changed, 1463 insertions(+), 272 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4774d0..bc7d38c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,15 @@ coordinates, and lists the file's image definitions in `images`, with how many images name each, one that none names among them. The example sheet has a vicinity map above its key plan. [docs/images.md](docs/images.md) describes them. +- Radius, diameter and jogged radius dimensions: `radiusDimension(center, point, options)`, + `diameterDimension(center, point, options)` and `joggedRadiusDimension(center, point, start, + jog, options)`, drawn as the leading CAD app draws them, with the R and the diameter sign it + writes before the measurement. The text stands outside the circle past the arrowhead, or along + the line where `textFromCenter` places it. A dimension style's `radialText: "horizontal"` levels + their text, and `jogAngle` sets the jog's angle. `toDXF` writes them, and `readDXF` reads them + as `radial-dimension`. The font tables hold the diameter sign, with the advance a paragraph + gives it in a font that lacks it; every other number is as it was. `toPDF` plots the diameter + sign as Ø in a font that lacks it, as the leading CAD app plots it. - What a dimension style sets of how its dimensions look. In architectural units, `fraction` stacks the fraction of an inch over a bar, `"stacked"`, or beside a slash, `"diagonal"`, at `fractionScale` of the text's height, as `4'-1` and a stacked `7/16`. `textPlacement: diff --git a/GUIDE.md b/GUIDE.md index 54b265d..a3f5fc3 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -376,6 +376,10 @@ d.linearDimension([24, 30], [76, 30], [0, 20], { style: "PLAN" }); the text in a break of the line, `textFit: "leader"` moves a text with no room out on a leader, `arrowhead: "oblique"` draws a thin tick, and `dimensionLineweight` and `extensionLineweight` set the pens. +- `radiusDimension(center, point, options)`, `diameterDimension(center, point, options)` and + `joggedRadiusDimension(center, point, start, jog, options)` dimension circles and arcs; CAD + writes the R and the diameter sign. `textFromCenter` places the text along the line, and a + style's `radialText: "horizontal"` levels it. - Never draw a dimension from lines and text. [docs/dimensions.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/dimensions.md) has the rest. @@ -599,7 +603,7 @@ writeFileSync("plan.dxf", toDXF(drawing)); ## What tsdraft cannot draw yet -- Hatches, fills, and dimensions that are not linear or aligned. +- Hatches, fills, and angular, arc length and ordinate dimensions. - A leader with two roots, a curved shaft, a block in place of its note, or a note attached at its top or bottom. - A block read from another file. A block is drawn in the drawing that inserts it. An xref diff --git a/cli/src/state.ts b/cli/src/state.ts index 38cd4dc..3738547 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -354,8 +354,11 @@ export interface DimensionSummary { /** The dimension's id, or `null`. */ readonly id: string | null; readonly layer: string; - /** `linear` measures along one direction, and `aligned` from point to point. */ - readonly kind: "linear" | "aligned"; + /** + * `linear` measures along one direction, `aligned` from point to point, and `radius`, + * `diameter` and `jogged-radius` a circle or an arc. + */ + readonly kind: "linear" | "aligned" | "radius" | "diameter" | "jogged-radius"; /** The dimension style as the dimension names it. */ readonly style: string; /** diff --git a/cli/src/worker.ts b/cli/src/worker.ts index c8d86d7..bb6a333 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -16,7 +16,6 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { types } from "node:util"; import { Worker } from "node:worker_threads"; import type { - AlignedDimension, Block, Diagnostic, DimensionPicture, @@ -26,7 +25,6 @@ import type { Intent, IntentWarning, Layout, - LinearDimension, PaperInfo, PaperUnit, TextWarning, @@ -189,8 +187,9 @@ interface Library { readonly drawnXrefs?: (drawing: Drawing, xrefs: GivenXrefs) => GivenXrefs; /** A dimension's style and what it draws. A copy of tsdraft from before dimensions has neither. */ readonly findDimensionStyle?: (drawing: Drawing, name: string) => DimensionStyle | undefined; + /** An older copy throws for a kind of dimension it does not know, which the caller catches. */ readonly dimensionPicture?: ( - dimension: LinearDimension | AlignedDimension, + dimension: Extract, style: DimensionStyle, ) => DimensionPicture; } @@ -1547,6 +1546,15 @@ function insertSummaries( }); } +/** The kind a dimension summary names for each kind of dimension. */ +const SUMMARY_KINDS = { + "linear-dimension": "linear", + "aligned-dimension": "aligned", + "radius-dimension": "radius", + "diameter-dimension": "diameter", + "jogged-radius-dimension": "jogged-radius", +} as const; + /** Each dimension among some entities, with what the library the drawing loaded says it reads. */ function dimensionSummaries( library: Library, @@ -1554,12 +1562,15 @@ function dimensionSummaries( entities: readonly Entity[] = drawing.entities, ): DimensionSummary[] { return entities.flatMap((e, entity): DimensionSummary[] => { - if (e.kind !== "linear-dimension" && e.kind !== "aligned-dimension") return []; + if (!Object.hasOwn(SUMMARY_KINDS, e.kind)) return []; + const dimension = e as Extract; let read: { measurement: number; text: string } | undefined; try { const style = - typeof e.style === "string" ? library.findDimensionStyle?.(drawing, e.style) : undefined; - const picture = style && library.dimensionPicture?.(e, style); + typeof dimension.style === "string" + ? library.findDimensionStyle?.(drawing, dimension.style) + : undefined; + const picture = style && library.dimensionPicture?.(dimension, style); if (picture && Number.isFinite(picture.measurement)) { read = { measurement: picture.measurement, text: picture.label.value }; } @@ -1570,9 +1581,9 @@ function dimensionSummaries( { entity, id: e.id ?? null, - layer: e.layer, - kind: e.kind === "linear-dimension" ? "linear" : "aligned", - style: e.style, + layer: dimension.layer, + kind: SUMMARY_KINDS[dimension.kind], + style: dimension.style, measurement: read?.measurement ?? null, text: read?.text ?? null, }, diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index fdc77ad..7ab1b83 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -132,6 +132,14 @@ BUILDING + + + + + + R5.0' TYP. + + N 90°00'00" E 100.00' S 00°00'00" E 140.00' S 90°00'00" W 100.00' diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index c568fce..4626cab 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -132,6 +132,14 @@ BUILDING + + + + + + R5.0' TYP. + + N 90°00'00" E 100.00' S 00°00'00" E 140.00' S 90°00'00" W 100.00' diff --git a/docs/dimensions.md b/docs/dimensions.md index 7011f74..fcad012 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -129,7 +129,7 @@ long. The ticks stay inward unless the line is shorter than two gaps. `lint` ref not laid out yet: words below the line of a text that moves out, arrowheads twice the text's height or longer in such a style, and closed filled arrowheads with the text centered. -## The two kinds +## The kinds `d.linearDimension(from, to, line, options)` measures the distance from `from` to `to` along one direction: along X unless `options.along` is `"y"` or an angle in degrees counterclockwise @@ -156,6 +156,38 @@ A dimension is on the current layer, and is drawn in that layer's color and line takes no linetype or lineweight of its own. It goes in model space or on a [layout](layouts.md), and not in a block. +### Radius, diameter and jogged radius + +`d.radiusDimension(center, point, options)` measures the radius of a circle or an arc: the +distance from `center` to `point`, a point of the circle its line meets. The leading CAD app writes +an R before the measurement, and `<>` in `text` stands for both: `"<> TYP."` reads `R2.50 TYP.`. +Its line runs from the center through `point`. The line to the center is always drawn. + +`d.diameterDimension(center, point, options)` measures twice that, read with a diameter sign: +`∅5.00`. Its line runs across the circle through the center, with an arrowhead at `point` and +one at the point opposite, and its text stands at `point`'s end. + +The text of both stands outside the circle, past the arrowhead, which points in at the circle +from outside, unless `options.textFromCenter` places it: the distance of the middle of the text +from the center along the line, inside the circle, outside it, or past the center for less than 0. The leading CAD app keeps a placed text two arrow sizes and a gap clear of the circle. Inside, +the arrowhead points out at the circle, and the line runs from beyond the text to it. + +`d.joggedRadiusDimension(center, point, start, jog, options)` measures the radius of an arc +whose center is too far off to draw to. Its line starts at `start`, standing in for the center, +crosses over at a jog centered on `jog`, and runs on toward the center to `point`, with the +arrowhead pointing out at the arc and the text along the last stretch, inside the arc. + +A dimension style sets two things of these kinds alone: + +- `radialText: "horizontal"` levels their text: outside a circle on a short level landing, and + across a jogged one's line, which breaks round it. `"aligned"`, the default, keeps it along the + line. Linear and aligned dimensions take no notice of it. +- `jogAngle`, the angle of the jog to the line, in degrees from 5 to 90. Defaults to 45. + +`lint` refuses a style with a `prefix` for them, which the leading CAD app may put in place of its R +or its diameter sign; a placed text in a style that levels the text or centers it in the line; a +jogged one in a style that centers its text; and a radius of 0. + ## How a measurement is written A measurement is the length between the points as the file holds them, with 6 decimals, @@ -330,7 +362,8 @@ no dimension style holds nothing else for dimensions. ## What is not drawn yet -Angular, radial, diameter, arc length and ordinate dimensions. Tolerances and alternate +Angular, arc length and ordinate dimensions. A radial dimension's center mark, which the leading +CAD app draws only without the line to the center, and a level text placed along its line. Tolerances and alternate units, and the unit formats but decimal and feet and inches. The other fits of a text, such as moving the arrowheads first, and a text a drafter placed. A dimension tied to an entity, which follows it when it moves: a dimension's points are the ones the code gives it. diff --git a/docs/reading.md b/docs/reading.md index 725c835..66ad733 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -117,8 +117,12 @@ A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers - `dimension`: a linear or aligned dimension, with its two points, the point where its dimension line meets its second extension line, its direction, the middle of its text, what it measures, its text and the words below its line, which the file holds after `\X`, its style and the - block of its picture. The other kinds of dimension are counted - under `other`. + block of its picture. Angular and ordinate dimensions are counted under `other`. +- `radial-dimension`: a radius, a diameter or a jogged radius dimension, its `type`, with its + center, the point of the circle or arc its line meets, a jogged one's start and jog, the + middle of its text, `placed` where the file holds the text where it was placed, what it + measures, its text, its style and the block of its picture. A file holds a diameter's far + point, and the center is halfway to the point. - `multileader`: one with straight shafts, one root and a note, with its style, each shaft from its tip, the point where the shafts meet, the landing's direction and length, its note, where the note is held, and the note's height and style. Any other is counted under `other`. diff --git a/examples/site-plan.ts b/examples/site-plan.ts index 197150f..c4a21de 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -410,6 +410,14 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee [houseX - plan.paper(3 / 8), 0], { view: plan, along: "y", style: "feet-inches", textBelow: "BUILDING" }, ); + // The radius of the driveway's flares, on the west one, which the east one repeats, its text + // clear of the sidewalk. + const flareCenter: Point = [driveX - driveway.flare, pavement.near + driveway.flare]; + const flarePoint: Point = [ + flareCenter[0] + driveway.flare / 2, + flareCenter[1] - (driveway.flare * Math.sqrt(3)) / 2, + ]; + d.radiusDimension(flareCenter, flarePoint, { view: plan, text: "<> TYP." }); }); d.layer("C-ANNO-TEXT", () => { diff --git a/src/arrowheads.ts b/src/arrowheads.ts index ce44fc7..25f3672 100644 --- a/src/arrowheads.ts +++ b/src/arrowheads.ts @@ -192,6 +192,12 @@ export const DIMENSION_TEXT_PLACEMENTS = ["above", "centered"] as const; */ export const DIMENSION_TEXT_FITS = ["inside", "leader"] as const; +/** How a radius, a diameter or a jogged radius dimension's text reads: along its line, or level. */ +export const DIMENSION_RADIAL_TEXTS = ["aligned", "horizontal"] as const; + +/** The angle of a jogged radius dimension's jog to its line, in degrees, by default and at most. */ +export const JOG_ANGLE = { default: 45, least: 5, most: 90 } as const; + /** The most decimals the leading CAD app writes a measurement with. */ export const MAX_PRECISION = 8; diff --git a/src/dimensions.ts b/src/dimensions.ts index 76bffc1..727b78d 100644 --- a/src/dimensions.ts +++ b/src/dimensions.ts @@ -3,16 +3,20 @@ // for a measurement, and the lines, arrowheads and text that app draws for a dimension. import type { AlignedDimension, + DiameterDimension, DimensionStyle, Drawing, + JoggedRadiusDimension, LinearDimension, Point, + RadiusDimension, TextStyle, } from "./drawing.ts"; import { arrowheadInfo, ARROWHEADS, DEFAULT_ARROWHEAD, + JOG_ANGLE, MAX_PRECISION, type Arrowhead, } from "./arrowheads.ts"; @@ -32,6 +36,11 @@ import { DIMENSION_LEADER_ARROWS, DIMENSION_LEADER_BELOW, dimensionMeasureProblem, + RADIAL_CENTERED, + RADIAL_JOG_SHORT, + RADIAL_NO_RADIUS, + RADIAL_PLACED_LEVEL, + RADIAL_PREFIX, dimensionStyleNameProblem, idKey, idProblem, @@ -40,8 +49,32 @@ import { pictureNumberProblem, } from "./rules.ts"; -/** A dimension of either kind. */ -export type Dimension = LinearDimension | AlignedDimension; +/** A dimension along a line: linear or aligned. */ +export type StraightDimension = LinearDimension | AlignedDimension; + +/** A dimension of a circle or an arc: a radius, a diameter or a jogged radius. */ +export type RadialDimension = RadiusDimension | DiameterDimension | JoggedRadiusDimension; + +/** A dimension of any kind. */ +export type Dimension = StraightDimension | RadialDimension; + +/** Whether an entity is a dimension. */ +export function isDimension( + entity: E, +): entity is Extract { + return ( + entity.kind === "linear-dimension" || entity.kind === "aligned-dimension" || isRadial(entity) + ); +} + +/** Whether a dimension measures a circle or an arc. */ +export function isRadial(dimension: { readonly kind: string }): dimension is RadialDimension { + return ( + dimension.kind === "radius-dimension" || + dimension.kind === "diameter-dimension" || + dimension.kind === "jogged-radius-dimension" + ); +} /** * A dimension style's name as its handle is keyed: A to Z in lower case and nothing else @@ -572,6 +605,15 @@ export function dimensionMeasure(dimension: Dimension): { readonly angle: number; readonly measurement: number; } { + if (isRadial(dimension)) { + const [x1, y1] = [written(dimension.center[0]), written(dimension.center[1])]; + const [x2, y2] = [written(dimension.point[0]), written(dimension.point[1])]; + const radius = Math.hypot(x2 - x1, y2 - y1); + return { + angle: Math.atan2(y2 - y1, x2 - x1) / RADIANS, + measurement: dimension.kind === "diameter-dimension" ? 2 * radius : radius, + }; + } const [x1, y1] = [written(dimension.from[0]), written(dimension.from[1])]; const [x2, y2] = [written(dimension.to[0]), written(dimension.to[1])]; if (dimension.kind === "aligned-dimension") { @@ -612,6 +654,7 @@ export function dimensionPicture( style: DimensionStyle, textStyle?: DimensionFont, ): DimensionPicture { + if (isRadial(dimension)) return radialPicture(dimension, style, textStyle); const from: Point = [written(dimension.from[0]), written(dimension.from[1])]; const to: Point = [written(dimension.to[0]), written(dimension.to[1])]; const { angle, measurement } = dimensionMeasure(dimension); @@ -824,6 +867,271 @@ export function dimensionPicture( }; } +/** What the leading CAD app writes before a radial dimension's measurement. */ +export const RADIAL_PREFIXES = { + "radius-dimension": "R", + "diameter-dimension": "\u2205", + "jogged-radius-dimension": "R", +} as const; + +/** A style's way of writing a radial dimension's measurement: with the prefix of its kind. */ +export function radialFormat( + dimension: Pick, + style: DimensionStyle, +): MeasurementFormat { + // The fields a measurement's writing reads, and no others: a style may hold any number. + const { units, precision, suffix, suppressZeros, feetInchZeros, measurementScale } = style; + const { fraction, fractionScale } = style; + return { + units, + precision, + prefix: `${RADIAL_PREFIXES[dimension.kind]}${style.prefix ?? ""}`, + suffix, + suppressZeros, + feetInchZeros, + measurementScale, + fraction, + fractionScale, + } as MeasurementFormat; +} + +/** + * What the leading CAD app draws for a radius, a diameter or a jogged radius dimension in a style. + * Its line runs from the center through the point of the circle, and on through the center to the + * point opposite for a diameter. Its text stands outside the circle past the arrowhead, along the + * line or level on a landing, unless the dimension places it along the line; a jogged one's stands + * along the last stretch, inside the arc. The arrowhead points at the circle from the side the text + * is on. + */ +function radialPicture( + dimension: RadialDimension, + style: DimensionStyle, + textStyle: DimensionFont | undefined, +): DimensionPicture { + const center: Point = [written(dimension.center[0]), written(dimension.center[1])]; + const point: Point = [written(dimension.point[0]), written(dimension.point[1])]; + const { angle, measurement } = dimensionMeasure(dimension); + const radius = Math.hypot(point[0] - center[0], point[1] - center[1]); + const u: Point = + radius > 0 ? [(point[0] - center[0]) / radius, (point[1] - center[1]) / radius] : [1, 0]; + const left: Point = [-u[1], u[0]]; + const move = (from: Point, by: Point, distance: number): Point => [ + from[0] + by[0] * distance, + from[1] + by[1] * distance, + ]; + const at = (distance: number): Point => move(center, u, distance); + const sizes = dimensionSizes(style); + const size = sizes.arrowSize; + const gap = sizes.textGap; + const info = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD); + const stroke = info?.stroke; + const tick = stroke !== undefined; + + const [aboveText, belowText] = dimensionTexts( + dimension, + measurement, + radialFormat(dimension, style), + ); + const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => + layoutDimensionText({ + value, + height: sizes.textHeight, + font, + widthFactor: written(textStyle?.widthFactor ?? 1), + obliqueAngle: written(textStyle?.obliqueAngle ?? 0), + align: "center", + valign: "middle", + }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => + layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + const topLayout = lay(mtextOfLabel(aboveText)); + const belowLayout = + belowText === undefined ? undefined : lay(belowText === "" ? "" : mtextOfLabel(belowText)); + const textWidth = Math.max(widest(topLayout), belowLayout ? widest(belowLayout) : 0); + const centered = style.textPlacement === "centered"; + + const lines: (readonly [Point, Point])[] = []; + const arrowheads: Point[][] = []; + const arrowheadEntities: ArrowheadEntity[] = []; + /** An arrowhead with its tip on `tip`, pointing `inward` toward the center or away from it. */ + const arrow = (tip: Point, inward: boolean): void => { + if (!(size > 0)) return; + const way: Point = inward ? [-u[0], -u[1]] : u; + if (tick) { + const rotation = (((angle + (inward ? 180 : 0)) % 360) + 360) % 360; + arrowheadEntities.push({ + kind: "insert", + block: info!.block!, + at: tip, + rotation, + scale: size, + }); + const half = move( + move([0, 0], way, stroke.to[0] * size), + [-way[1], way[0]], + stroke.to[1] * size, + ); + const wide = (stroke.width * size) / 2 / Math.SQRT2; + const edge: Point = [(way[0] + way[1]) * wide, (way[1] - way[0]) * wide]; + arrowheads.push([ + [tip[0] - half[0] + edge[0], tip[1] - half[1] + edge[1]], + [tip[0] + half[0] + edge[0], tip[1] + half[1] + edge[1]], + [tip[0] + half[0] - edge[0], tip[1] + half[1] - edge[1]], + [tip[0] - half[0] - edge[0], tip[1] - half[1] - edge[1]], + ]); + return; + } + const base = move(tip, way, -size); + arrowheads.push([tip, move(base, left, size / 6), move(base, left, -size / 6)]); + // The leading CAD app gives the corner to the left of the way out from the center first. + arrowheadEntities.push({ + kind: "solid", + corners: [move(base, left, size / 6), move(base, left, -size / 6), tip], + }); + }; + + // The text along the line reads from below or from the right; level, it reads along X. + const along = readable(angle); + const alongUp: Point = [-Math.sin(along * RADIANS), Math.cos(along * RADIANS)]; + const alongQuarter = direction(along); + const alongAbove: Point = along % 90 === 0 ? [-alongQuarter[1], alongQuarter[0]] : alongUp; + const horizontal = style.radialText === "horizontal"; + let rotation = along; + let quarter = alongQuarter; + let above = alongAbove; + let textMiddle: Point; + let lineMiddle: Point; + const half = boxHeight(topLayout) / 2; + const reach = tick ? 0 : size; + const placed = + dimension.kind === "jogged-radius-dimension" ? undefined : dimension.textFromCenter; + const inside = placed !== undefined && written(placed) < radius; + if (dimension.kind === "jogged-radius-dimension") { + const start: Point = [written(dimension.start[0]), written(dimension.start[1])]; + const jog: Point = [written(dimension.jog[0]), written(dimension.jog[1])]; + // The jog crosses the line at the style's angle, centered on its point, from where it meets + // the way to the center to the same distance on the other side. + const jogAngle = written(style.jogAngle ?? JOG_ANGLE.default); + const across = direction(angle + 180 - jogAngle); + const denominator = across[0] * u[1] - across[1] * u[0]; + const t = + denominator === 0 + ? 0 + : ((center[0] - jog[0]) * u[1] - (center[1] - jog[1]) * u[0]) / denominator; + const near = move(jog, across, t); + const far = move(jog, across, -t); + const end = at(radius - reach); + // A tick's line runs on past the arc by the style's DIMDLE, one arrow size as tsdraft writes + // it, and a level text's break widens by as much toward the center. The text keeps its place. + const beyond = tick ? size : 0; + lines.push([start, far], [far, near]); + arrow(point, false); + lineMiddle = [(near[0] + end[0]) / 2, (near[1] + end[1]) / 2]; + if (horizontal) { + // A level text sits on the last stretch, which breaks where it meets the text's box and a + // gap round it. + rotation = 0; + quarter = [1, 0]; + above = [0, 1]; + textMiddle = lineMiddle; + const middle = (lineMiddle[0] - center[0]) * u[0] + (lineMiddle[1] - center[1]) * u[1]; + const wide = Math.abs(u[0]) > 0 ? (gap + textWidth / 2) / Math.abs(u[0]) : Infinity; + const high = Math.abs(u[1]) > 0 ? (gap + half) / Math.abs(u[1]) : Infinity; + const out = Math.min(wide, high); + lines.push( + [at(middle - out - beyond), near], + [at(radius - reach + beyond), at(middle + out)], + ); + } else { + lines.push([near, at(radius - reach + beyond)]); + textMiddle = move(lineMiddle, above, gap + half); + } + } else if (inside) { + // A text placed inside: one line from beyond it to the arrowhead, which points out. The text + // stays two arrow sizes and a gap clear of the circle. + const middle = Math.min(written(placed!), radius - 2 * size - gap - textWidth / 2); + lineMiddle = at(middle); + const ends = [at(middle - textWidth / 2 - gap), at(radius - reach)] as const; + // A diameter's placed text inside takes one arrowhead too, at its point. + lines.push(ends); + arrow(point, false); + textMiddle = centered ? lineMiddle : move(lineMiddle, above, gap + half); + } else { + // Outside: the arrowhead points in at the circle, and the line runs out past the text. + const out = placed === undefined ? radius + 2 * size + gap + textWidth / 2 : written(placed); + const opposite = at(-radius); + // A level line takes its text along it, as if it were not level. + if (horizontal && u[1] !== 0) { + // Above a line that runs down, the elbow stands a box further out. + const lower = !centered && u[1] < 0 ? 2 * half : 0; + const elbow = at(radius + 2 * size + lower); + const level: Point = u[0] < 0 ? [-1, 0] : [1, 0]; + const landing = move(elbow, level, size); + lines.push([landing, elbow], [elbow, at(radius + reach)]); + rotation = 0; + quarter = [1, 0]; + above = [0, 1]; + lineMiddle = move(landing, level, gap + textWidth / 2); + textMiddle = lineMiddle; + } else if (centered) { + lines.push([at(radius + 2 * size), at(radius + reach)]); + lineMiddle = at(out); + textMiddle = lineMiddle; + } else { + lines.push([at(out + textWidth / 2 + gap), at(radius + reach)]); + lineMiddle = at(out); + textMiddle = move(lineMiddle, above, gap + half); + } + // A diameter's line runs across, with a tail past an arrowhead at the far point, and none + // past a tick. + if (dimension.kind === "diameter-dimension") { + lines.push( + [opposite, point], + ...(tick ? [] : [[at(-radius - reach), at(-radius - reach - size)] as const]), + ); + } else lines.push([center, point]); + arrow(point, true); + if (dimension.kind === "diameter-dimension") arrow(opposite, false); + } + const belowMiddle = belowLayout && move(lineMiddle, above, -(gap + boxHeight(belowLayout) / 2)); + // A placed text, and one with words below, is held by its point on the line. + const textPoint = belowLayout === undefined && placed === undefined ? textMiddle : lineMiddle; + const textStyleName = style.textStyle; + const label = (value: string, middle: Point, layout: ParagraphLayout): DimensionLabel => ({ + value, + at: move(middle, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + ...(textStyleName === undefined ? {} : { style: textStyleName }), + }); + const definition = dimension.kind === "diameter-dimension" ? at(-radius) : center; + return { + measurement, + definitionPoint: [written(definition[0]), written(definition[1])], + extensionLines: [], + dimensionLine: [center, point], + dimensionLines: lines, + leader: [], + arrowheads, + arrowheadEntities, + label: label(aboveText, textMiddle, topLayout), + textMiddle, + textPoint, + textWidth, + ...(belowLayout && + belowMiddle && { + below: { label: label(belowText!, belowMiddle, belowLayout), middle: belowMiddle }, + }), + lineweights: { + dimension: lineweightCode(style.dimensionLineweight), + extension: lineweightCode(style.extensionLineweight), + }, + }; +} + /** * The widest a character of any font in `FONTS` is drawn, as a share of the text's height, * before its style's width factor: for the characters of a measurement, the widest the leading CAD @@ -920,6 +1228,7 @@ export function dimensionDrawnProblem( textStyle: TextStyle | undefined, ): string | undefined { const { measurement } = dimensionMeasure(dimension); + if (isRadial(dimension)) return radialDrawnProblem(dimension, measurement, style, textStyle); // The arrowheads need room for the wider of the texts above and below the line. const [above, below] = dimensionTexts(dimension, measurement, style); let drawn = above; @@ -956,6 +1265,78 @@ export function dimensionDrawnProblem( ) { return DIMENSION_CENTERED_WIDE; } + return pictureNumbersProblem(picture); +} + +/** What is wrong with a radius, a diameter or a jogged radius dimension in its style, or undefined. */ +function radialDrawnProblem( + dimension: RadialDimension, + measurement: number, + style: DimensionStyle, + textStyle: TextStyle | undefined, +): string | undefined { + if (written(measurement) === 0) return RADIAL_NO_RADIUS; + if ((style.prefix ?? "") !== "") return RADIAL_PREFIX; + if ( + style.radialText === "horizontal" && + dimension.kind !== "jogged-radius-dimension" && + dimension.textFromCenter !== undefined + ) + return RADIAL_PLACED_LEVEL; + if ( + style.textPlacement === "centered" && + (dimension.kind === "jogged-radius-dimension" || dimension.textFromCenter !== undefined) + ) + return RADIAL_CENTERED; + const format = radialFormat(dimension, style); + const problem = dimensionMeasureProblem( + measurement, + measurement * written(style.measurementScale ?? 1), + roundedMeasurement(measurement, format), + false, + measurementText(measurement, format, dimension.text), + undefined, + ); + if (problem) return problem; + const picture = dimensionPicture(dimension, style, textStyle); + if ( + dimension.kind === "jogged-radius-dimension" && + !joggedStretchFits(dimension, style, picture) + ) { + return RADIAL_JOG_SHORT; + } + return pictureNumbersProblem(picture); +} + +/** + * Whether a jogged radius dimension's last stretch, from its jog to its arrowhead, holds its text: + * the text and a gap each side along it, or a level text's break within it. + */ +function joggedStretchFits( + dimension: JoggedRadiusDimension, + style: DimensionStyle, + picture: DimensionPicture, +): boolean { + const center: Point = [written(dimension.center[0]), written(dimension.center[1])]; + const point: Point = [written(dimension.point[0]), written(dimension.point[1])]; + const radius = Math.hypot(point[0] - center[0], point[1] - center[1]); + const u: Point = [(point[0] - center[0]) / radius, (point[1] - center[1]) / radius]; + const along = (p: Point): number => (p[0] - center[0]) * u[0] + (p[1] - center[1]) * u[1]; + const lines = picture.dimensionLines; + const near = along(lines[1]![1]); + if (lines.length > 3) { + // A level text: the stretch is broken on each side of it, from the jog and from the arrowhead. + return along(lines[2]![0]) >= near && along(lines[3]![1]) <= along(lines[3]![0]); + } + // The text is centered short of a tick's line past the arc. + const sizes = dimensionSizes(style); + const tick = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke !== undefined; + const end = along(lines[2]![1]) - (tick ? sizes.arrowSize : 0); + return end - near >= picture.textWidth + 2 * sizes.textGap; +} + +/** What is wrong with the numbers of a dimension's picture, each of which must be under 1e100. */ +function pictureNumbersProblem(picture: DimensionPicture): string | undefined { const numbers = [ ...picture.definitionPoint, ...picture.extensionLines.flat(2), diff --git a/src/drawing.ts b/src/drawing.ts index 3e252a7..23ba4d0 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -9,12 +9,14 @@ import { arrowheadInfo, DEFAULT_ARROWHEAD, DEFAULT_LEADER_ARROWHEAD, + JOG_ANGLE, STANDARD_LEADER_STYLE, type Arrowhead, type DIMENSION_UNITS, type DIMENSION_FRACTIONS, type DIMENSION_TEXT_PLACEMENTS, type DIMENSION_TEXT_FITS, + type DIMENSION_RADIAL_TEXTS, type FEET_INCH_ZEROS, type LeaderArrowhead, type ZERO_SUPPRESSIONS, @@ -28,6 +30,7 @@ import { pictureOwner, validDimensionPictureHandles, validDimensionStyleHandle, + type Dimension, type DimensionPlace, } from "./dimensions.ts"; import { STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; @@ -557,6 +560,59 @@ export interface AlignedDimension extends DimensionBase { readonly offset: number; } +/** What a radius, a diameter and a jogged radius dimension have. */ +interface RadialDimensionBase extends Placed { + /** A dimension style of the drawing. */ + readonly style: string; + /** The center of the circle or arc it measures. */ + readonly center: Point; + /** The point of the circle or arc its line meets, which the radius reaches. */ + readonly point: Point; + /** A text to draw in place of the measurement, as a linear dimension's `text`. */ + readonly text?: string; + /** Words drawn under its line, opposite the text, as a linear dimension's `textBelow`. */ + readonly textBelow?: string; +} + +/** + * A radius dimension: the distance from the center of a circle or an arc to `point`, read with + * an R before it. Its line runs from the center through `point`, and its arrowhead points at the + * circle there from outside. The line to the center is always drawn. + */ +export interface RadiusDimension extends RadialDimensionBase { + readonly kind: "radius-dimension"; + /** + * How far the middle of its text is from the center, along its line: inside the circle, outside + * it, or past the center for less than 0. Left out, the text stands outside the circle, past the + * arrowhead, as the leading CAD app places it. + */ + readonly textFromCenter?: number; +} + +/** + * A diameter dimension: twice the distance from the center of a circle to `point`, read with a + * diameter sign before it. Its line runs through the center from `point` to the point opposite, + * with an arrowhead at each, and its text stands at `point`'s end. + */ +export interface DiameterDimension extends RadialDimensionBase { + readonly kind: "diameter-dimension"; + /** How far the middle of its text is from the center, as a radius dimension's. */ + readonly textFromCenter?: number; +} + +/** + * A jogged radius dimension: the radius of an arc whose center is far off, read with an R before + * it. Its line starts at `start` instead of the center, runs to a jog across the line at `jog`, + * and goes on toward the center to `point`, with its text along the last stretch, inside the arc. + */ +export interface JoggedRadiusDimension extends RadialDimensionBase { + readonly kind: "jogged-radius-dimension"; + /** Where its line starts, standing in for the center. */ + readonly start: Point; + /** The middle of the jog. */ + readonly jog: Point; +} + /** Which side of the point where its shafts meet a leader's note is on. */ export type LeaderSide = (typeof LEADER_SIDES)[number]; @@ -651,6 +707,9 @@ export type Entity = | Insert | LinearDimension | AlignedDimension + | RadiusDimension + | DiameterDimension + | JoggedRadiusDimension | Leader | Image; @@ -769,6 +828,14 @@ export interface DimensionStyle { readonly dimensionLineweight?: number; /** The same for the extension lines. Defaults to the dimension's own. */ readonly extensionLineweight?: number; + /** + * How the text of a radius, a diameter or a jogged radius dimension reads: `"aligned"` along its + * line, the default, or level, `"horizontal"`: on a short level landing outside a circle, and + * across a jogged one's line. Linear and aligned dimensions take no notice of it. + */ + readonly radialText?: (typeof DIMENSION_RADIAL_TEXTS)[number]; + /** The angle of a jogged radius dimension's jog to its line, in degrees from 5 to 90. Defaults to 45. */ + readonly jogAngle?: number; } /** @@ -1594,6 +1661,10 @@ export interface DimensionStyleDefinition< readonly dimensionLineweight?: number; /** The lineweight of the extension lines, in millimetres, one of `Lineweight`. */ readonly extensionLineweight?: number; + /** A radial dimension's text `"aligned"` along its line, the default, or `"horizontal"`. */ + readonly radialText?: (typeof DIMENSION_RADIAL_TEXTS)[number]; + /** The angle of a jogged radius dimension's jog to its line, in degrees from 5 to 90. Defaults to 45. */ + readonly jogAngle?: number; } /** What every dimension is drawn with. */ @@ -1639,6 +1710,33 @@ export type AlignedDimensionOptions< I extends string = string, > = DimensionOptions; +/** The options of `radiusDimension()`. */ +export interface RadiusDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, +> extends DimensionOptions { + /** + * How far the middle of its text is from the center, along its line, past the center for less + * than 0. Left out, the text stands outside the circle, past the arrowhead. + */ + readonly textFromCenter?: number; +} + +/** The options of `diameterDimension()`. */ +export type DiameterDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, +> = RadiusDimensionOptions; + +/** The options of `joggedRadiusDimension()`. */ +export type JoggedRadiusDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, +> = DimensionOptions; + /** * What a dimension is drawn with under the standard `Z`: a dimension style of the standard by its * id, and in model space the view it is read in. The builder defines the drawing's own dimension @@ -1668,6 +1766,17 @@ export interface StandardAlignedDimensionOptions< readonly id?: EntityId; } +/** The options of `radiusDimension()` and `diameterDimension()` under the standard `Z`. */ +export interface StandardRadiusDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, + Z extends Standard = Standard, +> extends StandardAlignedDimensionOptions { + /** How far the middle of its text is from the center, as `RadiusDimensionOptions` says. */ + readonly textFromCenter?: number; +} + /** The options of `linearDimension()` under the standard `Z`. */ export interface StandardLinearDimensionOptions< S extends string = string, @@ -3352,7 +3461,7 @@ export class DrawingBuilder< if (block !== undefined) this.#arrowheadBlocks.add(block); const { prefix, suffix, suppressZeros, feetInchZeros } = definition; const { fraction, fractionScale, textPlacement, textFit } = definition; - const { dimensionLineweight, extensionLineweight } = definition; + const { dimensionLineweight, extensionLineweight, radialText, jogAngle } = definition; const units = definition.units ?? "decimal"; const scale = definition.scale ?? 1; const measurementScale = definition.measurementScale ?? 1; @@ -3379,6 +3488,8 @@ export class DrawingBuilder< ...(textFit === undefined || textFit === "inside" ? {} : { textFit }), ...(dimensionLineweight === undefined ? {} : { dimensionLineweight }), ...(extensionLineweight === undefined ? {} : { extensionLineweight }), + ...(radialText === undefined || radialText === "aligned" ? {} : { radialText }), + ...(jogAngle === undefined || written(jogAngle) === JOG_ANGLE.default ? {} : { jogAngle }), }); this.#dimensionStylesAudited.set(layerAuditKey(named), named); } @@ -3450,8 +3561,106 @@ export class DrawingBuilder< ); } + /** + * Draws a radius dimension on the current layer: the distance from `center` to `point`, a point + * of the circle or arc it measures, read with an R. Its line runs from the center through + * `point`, and its text stands outside the circle unless `options.textFromCenter` places it. + */ + radiusDimension( + center: Point, + point: Point, + options: Z extends Standard + ? StandardRadiusDimensionOptions + : V extends "R12" + ? R12Dimensions + : RadiusDimensionOptions, + ): this { + return this.#add(DrawingBuilder.prototype.radiusDimension, idOf(options), () => + this.#radial("radius-dimension", center, point, options), + ); + } + + /** + * Draws a diameter dimension on the current layer: twice the distance from `center` to `point`, + * read with a diameter sign. Its line runs through the center from `point` to the point + * opposite, and its text stands at `point`'s end, outside the circle unless + * `options.textFromCenter` places it. + */ + diameterDimension( + center: Point, + point: Point, + options: Z extends Standard + ? StandardRadiusDimensionOptions + : V extends "R12" + ? R12Dimensions + : DiameterDimensionOptions, + ): this { + return this.#add(DrawingBuilder.prototype.diameterDimension, idOf(options), () => + this.#radial("diameter-dimension", center, point, options), + ); + } + + /** + * Draws a jogged radius dimension on the current layer: the distance from `center` to `point`, + * for an arc whose center is far off. Its line starts at `start`, jogs across at `jog`, and runs + * on toward the center to `point`, with its text along the last stretch. + */ + joggedRadiusDimension( + center: Point, + point: Point, + start: Point, + jog: Point, + options: Z extends Standard + ? StandardAlignedDimensionOptions + : V extends "R12" + ? R12Dimensions + : JoggedRadiusDimensionOptions, + ): this { + return this.#add(DrawingBuilder.prototype.joggedRadiusDimension, idOf(options), () => + this.#dimension( + options as unknown as JoggedRadiusDimensionOptions | undefined, + (style, text) => ({ + kind: "jogged-radius-dimension", + layer: this.#current, + style, + center: pt(center), + point: pt(point), + start: pt(start), + jog: pt(jog), + ...text, + }), + ), + ); + } + + /** A radius or a diameter dimension, with its text where `options.textFromCenter` says. */ + #radial( + kind: K, + center: Point, + point: Point, + options: unknown, + ): RadiusDimension | DiameterDimension { + const o = options as RadiusDimensionOptions | undefined; + const along: unknown = o?.textFromCenter; + return this.#dimension( + o, + (style, text) => + ({ + kind, + layer: this.#current, + style, + center: pt(center), + point: pt(point), + ...(along === undefined + ? {} + : { textFromCenter: kept(along as number, "textFromCenter") }), + ...text, + }) as RadiusDimension | DiameterDimension, + ); + } + /** Checks what a dimension names and what it measures, and returns the dimension `make` gives. */ - #dimension( + #dimension( options: | { readonly style?: unknown; @@ -3586,6 +3795,8 @@ export class DrawingBuilder< ...(fields.textFit === "inside" ? {} : { textFit: fields.textFit }), ...(dimensionLineweight === undefined ? {} : { dimensionLineweight }), ...(extensionLineweight === undefined ? {} : { extensionLineweight }), + ...(fields.radialText === "aligned" ? {} : { radialText: fields.radialText }), + ...(fields.jogAngle === JOG_ANGLE.default ? {} : { jogAngle: fields.jogAngle }), }); return this.#dimensionStyles.get(layerKey(name))!; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 3311a0b..9b96d1e 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -10,6 +10,7 @@ import { arrowheadInfo, DEFAULT_ARROWHEAD, DEFAULT_LEADER_ARROWHEAD, + JOG_ANGLE, leaderArrowheadInfo, type LeaderArrowheadStroke, } from "./arrowheads.ts"; @@ -28,6 +29,8 @@ import { type DimensionPicture, type DimensionPictureHandles, type Dimension, + isDimension, + isRadial, } from "./dimensions.ts"; import type { AttributeDefinition, @@ -191,6 +194,16 @@ export function toDXFR2018( g(0, "SECTION"); g(2, "CLASSES"); + // A jogged radius dimension is an entity of a class, which a drawing that has one lists. + const jogged = [drawing.entities, ...sheets.map((sheet) => sheet.layout.entities)] + .flat() + .filter((e) => e.kind === "jogged-radius-dimension").length; + if (jogged > 0) { + writeClass(g, "LARGE_RADIAL_DIMENSION", "AcDbRadialDimensionLarge", "ObjectDBX Classes", 1025, { + count: jogged, + entity: true, + }); + } // A multileader and its style are objects of classes, which a drawing that has them lists. if (leaderStyles.length > 0) { writeClass(g, "MLEADERSTYLE", "AcDbMLeaderStyle", "ACDB_MLEADERSTYLE_CLASS", 4095, { @@ -370,7 +383,7 @@ export function toDXFR2018( const pictures = new Map(); [drawing.entities, ...sheets.map((sheet) => sheet.layout.entities)].forEach((entities, space) => { entities.forEach((entity, index) => { - if (entity.kind !== "linear-dimension" && entity.kind !== "aligned-dimension") return; + if (!isDimension(entity)) return; const style = dimensionStylesByKey.get(layerKey(entity.style)); if (style === undefined) return; const layout = space === 0 ? undefined : sheets[space - 1]!.layout.name; @@ -498,7 +511,7 @@ export function toDXFR2018( }); return; } - if (entity.kind === "linear-dimension" || entity.kind === "aligned-dimension") { + if (isDimension(entity)) { const picture = space === undefined ? undefined : pictures.get(`${space}/${index}`); writeDimension( g, @@ -1199,9 +1212,10 @@ function writeDimension( drawn: DimensionPicture | undefined, ): void { // `lint` refuses a dimension in a style the drawing does not have, which has no picture. - const at = e.kind === "linear-dimension" ? e.line : e.to; + const at = isRadial(e) ? e.center : e.kind === "linear-dimension" ? e.line : e.to; const picture = drawn ?? { definitionPoint: at, textPoint: at }; - g(0, "DIMENSION"); + const jogged = e.kind === "jogged-radius-dimension"; + g(0, jogged ? "LARGE_RADIAL_DIMENSION" : "DIMENSION"); g(5, handle); g(330, owner); g(100, "AcDbEntity"); @@ -1211,8 +1225,9 @@ function writeDimension( if (block !== undefined) g(2, block); point(g, 10, ...picture.definitionPoint); point(g, 11, ...picture.textPoint); - // 32: the dimension has a picture of its own. 1: it is aligned. - g(70, e.kind === "aligned-dimension" ? 33 : 32); + // The kind, and 32: the dimension has a picture of its own; 128: its text is where it was placed. + const placed = "textFromCenter" in e && e.textFromCenter !== undefined ? 128 : 0; + g(70, DIMENSION_TYPES[e.kind] + 32 + placed); const text = dimensionFileText(e); if (text !== undefined) g(1, dxfOnce(text)); g(71, 5); // the text is placed by its middle @@ -1220,6 +1235,32 @@ function writeDimension( // itself, and keeps the picture the file holds. if (style) g(42, measurementValue(e, style)); g(3, style?.name ?? e.style); + if (isRadial(e)) { + if (e.kind === "jogged-radius-dimension") { + g(100, "AcDbRadialDimensionLarge"); + point(g, 13, ...e.start); + point(g, 14, ...e.jog); + } else { + g(100, e.kind === "radius-dimension" ? "AcDbRadialDimension" : "AcDbDiametricDimension"); + } + point(g, 15, ...e.point); + g(40, 0); // no leader length: the text's place is group 11 + // What the style sets of a radial dimension alone is the dimension's override: a jog angle + // other than the leading CAD app's own, and a level text. + const overrides = radialOverrides(e, style); + if (overrides.length > 0) { + g(1001, "ACAD"); + g(1000, "DSTYLE"); + g(1002, "{"); + for (const [code, value] of overrides) { + g(1070, code); + if (code === 50) g(1040, value); + else g(1070, value); + } + g(1002, "}"); + } + return; + } g(100, "AcDbAlignedDimension"); point(g, 13, ...e.from); point(g, 14, ...e.to); @@ -1230,6 +1271,38 @@ function writeDimension( } } +/** + * The overrides a radial dimension holds of what its style sets of it alone, by the group each + * has in a dimension style: DIMJOGANG (50) in radians, and DIMTIH (73) and DIMTOH (74) for a level + * text. A linear or an aligned dimension holds none. + */ +export function radialOverrides( + e: Dimension, + style: DimensionStyle | undefined, +): (readonly [code: number, value: number])[] { + if (!isRadial(e) || style === undefined) return []; + const out: [number, number][] = []; + const jog = style.jogAngle; + if ( + e.kind === "jogged-radius-dimension" && + jog !== undefined && + written(jog) !== JOG_ANGLE.default + ) { + out.push([50, (written(jog) * Math.PI) / 180]); + } + if (style.radialText === "horizontal") out.push([73, 1], [74, 1]); + return out; +} + +/** Group 70's kind of each dimension. */ +const DIMENSION_TYPES = { + "linear-dimension": 0, + "aligned-dimension": 1, + "diameter-dimension": 3, + "radius-dimension": 4, + "jogged-radius-dimension": 9, +} as const; + /** The block of a dimension's picture, with what the writer needs for it. */ interface Picture { /** The block's name, `*D` and a number. */ @@ -1273,8 +1346,9 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi string, number, ])[] = [ - [...picture.extensionLines[0]!, handles.extensionLines[0], weights.extension], - [...picture.extensionLines[1]!, handles.extensionLines[1], weights.extension], + ...picture.extensionLines.map( + ([from, to], i) => [from, to, handles.extensionLines[i]!, weights.extension] as const, + ), ...picture.dimensionLines.map( ([from, to], i) => [from, to, handles.dimensionLines[i]!, weights.dimension] as const, ), diff --git a/src/extents.ts b/src/extents.ts index c47b693..3345cd7 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -308,6 +308,9 @@ export function boxer( } case "linear-dimension": case "aligned-dimension": + case "radius-dimension": + case "diameter-dimension": + case "jogged-radius-dimension": dimension(e, from, add); break; case "leader": { diff --git a/src/font-metrics.ts b/src/font-metrics.ts index e4538cd..da4afb5 100644 --- a/src/font-metrics.ts +++ b/src/font-metrics.ts @@ -66,6 +66,7 @@ export interface FontFace { export const FONT_METRICS_RANGES: readonly (readonly [number, number])[] = [ [0x20, 0x7e], [0xa0, 0xff], + [0x2205, 0x2205], ]; export const FONT_METRICS: Readonly> = { @@ -85,7 +86,7 @@ export const FONT_METRICS: Readonly> = { 0.83333333333, 0.83333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 0.83333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 0.66666666667, - 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], tails: [ 0, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, @@ -125,7 +126,7 @@ export const FONT_METRICS: Readonly> = { -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, - -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, + -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -134,7 +135,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.08333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -145,7 +146,7 @@ export const FONT_METRICS: Readonly> = { 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, 0, 0, 0, 0, 0.02251023192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, ], rights: [ 1, 0, 0.33333333333, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, @@ -177,7 +178,7 @@ export const FONT_METRICS: Readonly> = { 0.66666666667, 0.66666666667, 0.66666666667, 0.33333333333, 0.33333333333, 0.33333333333, 0.33333333333, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, - 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, ], tops: [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -186,7 +187,7 @@ export const FONT_METRICS: Readonly> = { 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -198,7 +199,7 @@ export const FONT_METRICS: Readonly> = { 0, -0.28717598909, 0, 0, 0, 0, 0, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, 0, -0.33333333333, + -0.33333333333, 0, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.33333333333, 1, 1, 1, 1, 0.33333333333, 1, 1, 0.66666666667, 0.66666666667, @@ -212,7 +213,7 @@ export const FONT_METRICS: Readonly> = { 1, 1, 1, 1, 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 0.91666666667, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, - 1.33333333333, + 1.33333333333, 1, ], afterStack: 0.33333333333, }, @@ -225,7 +226,7 @@ export const FONT_METRICS: Readonly> = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, ], tails: [ 0, -1, -0.66666666667, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, @@ -259,7 +260,7 @@ export const FONT_METRICS: Readonly> = { -0.5, -0.5, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, -0.33333333333, - -0.33333333333, + -0.33333333333, -0.33333333333, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -270,7 +271,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0.16666666667, 0.16666666667, 0.16666666667, -0.08333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0.16666666667, 0.16666666667, 0.16666666667, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -283,7 +284,7 @@ export const FONT_METRICS: Readonly> = { 0.02251023192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0.16666666667, 0.16666666667, 0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.16666666667, 0.16666666667, 0.16666666667, 0.16666666667, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], rights: [ 1, 0, 0.33333333333, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, @@ -314,7 +315,7 @@ export const FONT_METRICS: Readonly> = { 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.5, 0.5, 0.5, 0.5, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, - 0.66666666667, 0.66666666667, 0.66666666667, + 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, ], tops: [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -323,7 +324,7 @@ export const FONT_METRICS: Readonly> = { 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1.017053206, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.017053206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.16666666667, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -335,7 +336,7 @@ export const FONT_METRICS: Readonly> = { 0, -0.28717598909, 0, 0, 0, 0, 0, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, 0, -0.33333333333, + -0.33333333333, 0, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.33333333333, 1, 1, 1, 1, 0.33333333333, 1, 1, 0.66666666667, 0.66666666667, @@ -349,7 +350,7 @@ export const FONT_METRICS: Readonly> = { 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.33333333333, 1, 1, 1, 1, 0.91666666667, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, - 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, + 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, 1, ], afterStack: 0.33333333333, }, @@ -386,7 +387,7 @@ export const FONT_METRICS: Readonly> = { 0.85714285714, 0.85714285714, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.85714285714, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, - 0.90476190476, 0.7619047619, 1, 0.7619047619, + 0.90476190476, 0.7619047619, 1, 0.7619047619, 0.90476190476, ], tails: [ 0, -0.52380952381, -0.33333333333, -0.19047619048, -0.28571428571, -0.19047619048, @@ -425,7 +426,7 @@ export const FONT_METRICS: Readonly> = { -0.28571428571, -0.28571428571, -0.28571428571, -0.28571428571, -0.38095238095, -0.28571428571, -0.28571428571, -0.28571428571, -0.28571428571, -0.28571428571, -0.28571428571, -0.28571428571, -0.38095238095, -0.38095238095, -0.38095238095, - -0.38095238095, -0.14285714286, -0.33333333333, -0.14285714286, + -0.38095238095, -0.14285714286, -0.33333333333, -0.14285714286, -0.28571428571, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -434,7 +435,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.09523809524, 0, -0.09523809524, -0.14285714286, -0.14285714286, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -445,6 +446,7 @@ export const FONT_METRICS: Readonly> = { 0.16234652115, 0.07298772169, 0.07298772169, 0, 0, 0, 0, 0.02251023192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, ], rights: [ 0.90476190476, 0.09523809524, 0.38095238095, 0.71428571429, 0.66666666667, 0.85714285714, @@ -477,7 +479,7 @@ export const FONT_METRICS: Readonly> = { 0.57142857143, 0.57142857143, 0.57142857143, 0.38095238095, 0.38095238095, 0.38095238095, 0.38095238095, 0.61904761905, 0.52380952381, 0.61904761905, 0.61904761905, 0.61904761905, 0.61904761905, 0.61904761905, 0.57142857143, 0.61904761905, 0.52380952381, 0.52380952381, - 0.52380952381, 0.52380952381, 0.61904761905, 0.66666666667, 0.61904761905, + 0.52380952381, 0.52380952381, 0.61904761905, 0.66666666667, 0.61904761905, 0.61904761905, ], tops: [ 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, @@ -492,7 +494,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1.04761904762, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1.04761904762, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, @@ -506,7 +508,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, 0, -0.33333333333, + -0.33333333333, 0, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, @@ -526,7 +528,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, - 1, 1.33333333333, + 1, 1.33333333333, 0.95238095238, ], afterStack: 0.28571428571, }, @@ -562,7 +564,7 @@ export const FONT_METRICS: Readonly> = { 0.85714285714, 0.85714285714, 0.85714285714, 0.52380952381, 0.52380952381, 0.52380952381, 0.52380952381, 0.85714285714, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.85714285714, 0.95238095238, 0.90476190476, 0.90476190476, - 0.90476190476, 0.90476190476, 0.7619047619, 0.85714285714, 0.7619047619, + 0.90476190476, 0.90476190476, 0.7619047619, 0.85714285714, 0.7619047619, 0.90476190476, ], tails: [ 0, -0.19047619048, -0.09523809524, -0.14285714286, -0.14285714286, -0.14285714286, @@ -601,7 +603,7 @@ export const FONT_METRICS: Readonly> = { -0.14285714286, -0.14285714286, 0, 0, 0, 0, -0.14285714286, -0.19047619048, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.19047619048, -0.19047619048, -0.19047619048, -0.19047619048, -0.19047619048, - -0.09523809524, -0.14285714286, -0.09523809524, + -0.09523809524, -0.14285714286, -0.09523809524, -0.14285714286, ], heads: [ 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, @@ -635,7 +637,7 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.04761904762, - 0.14285714286, 0.04761904762, + 0.14285714286, 0.04761904762, 0.14285714286, ], lefts: [ 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, @@ -669,6 +671,7 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.14285714286, 0.04979536153, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.04761904762, 0.09208731242, 0.04761904762, + 0.14285714286, ], rights: [ 1, 0.28571428571, 0.57142857143, 0.85714285714, 0.80952380952, 1, 1.09523809524, @@ -702,7 +705,7 @@ export const FONT_METRICS: Readonly> = { 0.52380952381, 0.52380952381, 0.52380952381, 0.52380952381, 0.7210095498, 0.71428571429, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.71428571429, 0.76190476191, 0.71428571429, 0.71428571429, 0.71428571429, 0.71428571429, 0.66666666667, - 0.7210095498, 0.66666666667, + 0.7210095498, 0.66666666667, 0.76190476191, ], tops: [ 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, @@ -717,7 +720,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, @@ -731,7 +734,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, -0.27762619372, -0.33333333333, + -0.33333333333, -0.27762619372, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.28571428571, 1.52380952381, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, @@ -751,7 +754,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, - 1.33333333333, + 1.33333333333, 0.95238095238, ], afterStack: 0.14285714286, }, @@ -788,7 +791,7 @@ export const FONT_METRICS: Readonly> = { 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, 0.7619047619, 0.7619047619, 0.7619047619, 0.7619047619, 0.90476190476, 0.95238095238, 0.90476190476, 0.90476190476, 0.90476190476, 1, 0.90476190476, 0.90476190476, 0.95238095238, 0.95238095238, 0.95238095238, - 0.95238095238, 0.95238095238, 0.7619047619, 0.90476190476, 0.7619047619, + 0.95238095238, 0.95238095238, 0.7619047619, 0.90476190476, 0.7619047619, 0.95238095238, ], tails: [ 0, -0.19047619048, -0.19047619048, -0.11904761905, -0.14285714286, -0.14285714286, @@ -828,7 +831,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.14285714286, -0.14285714286, -0.19047619048, -0.14285714286, -0.14285714286, -0.14285714286, -0.19047619048, -0.14285714286, -0.14285714286, -0.19047619048, -0.19047619048, -0.19047619048, -0.19047619048, -0.19047619048, - -0.09523809524, -0.14285714286, -0.09523809524, + -0.09523809524, -0.14285714286, -0.09523809524, -0.14285714286, ], heads: [ 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, @@ -862,6 +865,7 @@ export const FONT_METRICS: Readonly> = { 0.19047619048, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, 0.09523809524, 0.14285714286, 0.09523809524, + 0.14285714286, ], lefts: [ 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, @@ -894,7 +898,7 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.14285714286, 0.04979536153, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.19047619048, 0.19047619048, 0.19047619048, 0.19047619048, - 0.09523809524, 0.09208731242, 0.09523809524, + 0.09523809524, 0.09208731242, 0.09523809524, 0.14285714286, ], rights: [ 1, 0.33333333333, 0.66666666667, 0.92857142857, 0.7619047619, 1.04761904762, 1.04761904762, @@ -927,7 +931,7 @@ export const FONT_METRICS: Readonly> = { 0.71428571429, 0.57142857143, 0.57142857143, 0.57142857143, 0.61904761905, 0.7210095498, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.80952380952, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, - 0.66666666667, 0.7210095498, 0.66666666667, + 0.66666666667, 0.7210095498, 0.66666666667, 0.80952380952, ], tops: [ 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, @@ -941,7 +945,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1.2380952381, 1.2380952381, 1.2380952381, 1.2380952381, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.14285714286, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.2380952381, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, @@ -955,7 +959,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, -0.27762619372, -0.33333333333, + -0.33333333333, -0.27762619372, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.33333333333, 1.33333333333, 1.38095238095, 1, 1, 0.33333333333, 1.52380952381, @@ -975,7 +979,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1.19047619048, 1.14285714286, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.2380952381, 1, 1, 1, 1, 1, 0.95238095238, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.95238095238, - 1, 0.71428571429, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, + 1, 0.71428571429, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, 0.95238095238, ], afterStack: 0.14285714286, }, @@ -1011,7 +1015,7 @@ export const FONT_METRICS: Readonly> = { 0.90476190476, 0.90476190476, 0.90476190476, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.85714285714, 1.04761904762, 0.95238095238, 0.95238095238, 0.95238095238, 0.95238095238, 0.95238095238, 0.85714285714, 0.90476190476, 1.04761904762, 1.04761904762, - 1.04761904762, 1.04761904762, 0.90476190476, 0.85714285714, 0.90476190476, + 1.04761904762, 1.04761904762, 0.90476190476, 0.85714285714, 0.90476190476, 0.95238095238, ], tails: [ 0, -0.19047619048, -0.09523809524, -0.14285714286, -0.14285714286, -0.14285714286, @@ -1051,7 +1055,7 @@ export const FONT_METRICS: Readonly> = { -0.09523809524, -0.14285714286, -0.09523809524, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.09523809524, -0.09523809524, -0.09523809524, -0.09523809524, -0.09523809524, -0.04761904762, - -0.14285714286, -0.04761904762, + -0.14285714286, -0.04761904762, -0.14285714286, ], heads: [ 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, @@ -1085,7 +1089,7 @@ export const FONT_METRICS: Readonly> = { 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, - 0.14285714286, 0.09523809524, + 0.14285714286, 0.09523809524, 0.14285714286, ], lefts: [ 0, 0.19047619048, 0.19047619048, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, @@ -1118,7 +1122,7 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.04979536153, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, - 0.09523809524, 0.09523809524, 0.09523809524, 0.09208731242, 0.09523809524, + 0.09523809524, 0.09523809524, 0.09523809524, 0.09208731242, 0.09523809524, 0.14285714286, ], rights: [ 1, 0.28571428571, 0.57142857143, 0.85714285714, 0.80952380952, 1, 1.04761904762, @@ -1151,7 +1155,7 @@ export const FONT_METRICS: Readonly> = { 0.76190476191, 0.76190476191, 0.76190476191, 0.57142857143, 0.57142857143, 0.57142857143, 0.57142857143, 0.7210095498, 0.95238095238, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.71428571429, 0.80952380952, 0.95238095238, 0.95238095238, - 0.95238095238, 0.95238095238, 0.85714285714, 0.7210095498, 0.85714285714, + 0.95238095238, 0.95238095238, 0.85714285714, 0.7210095498, 0.85714285714, 0.80952380952, ], tops: [ 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, @@ -1166,7 +1170,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.2380952381, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, @@ -1180,7 +1184,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, -0.27762619372, -0.33333333333, + -0.33333333333, -0.27762619372, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, @@ -1200,7 +1204,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1, 1.2380952381, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 0.95238095238, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.95238095238, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, - 1.33333333333, + 1.33333333333, 0.95238095238, ], afterStack: 0.14285714286, }, @@ -1237,7 +1241,7 @@ export const FONT_METRICS: Readonly> = { 0.61904761905, 0.57142857143, 0.61904761905, 0.90476190476, 1.09523809524, 0.95238095238, 0.95238095238, 0.95238095238, 0.95238095238, 0.95238095238, 0.90476190476, 0.95238095238, 1.09523809524, 1.09523809524, 1.09523809524, 1.14285714286, 0.90476190476, 0.90476190476, - 0.90476190476, + 0.90476190476, 0.95238095238, ], tails: [ 0, -0.28571428571, -0.19047619048, -0.11904761905, -0.14285714286, -0.14285714286, @@ -1277,7 +1281,7 @@ export const FONT_METRICS: Readonly> = { -0.09523809524, -0.14285714286, -0.09523809524, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.14285714286, -0.09523809524, -0.09523809524, -0.09523809524, -0.09523809524, -0.04761904762, - -0.14285714286, -0.04761904762, + -0.14285714286, -0.04761904762, -0.09523809524, ], heads: [ 0, 0.09523809524, 0.19047619048, 0.14285714286, 0.14285714286, 0.09523809524, 0.19047619048, @@ -1311,7 +1315,7 @@ export const FONT_METRICS: Readonly> = { 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.14285714286, 0.04761904762, 0.14285714286, - 0.04761904762, + 0.04761904762, 0.09523809524, ], lefts: [ 0, 0.09523809524, 0.19047619048, 0.14285714286, 0.14285714286, 0.09523809524, 0.19047619048, @@ -1344,7 +1348,7 @@ export const FONT_METRICS: Readonly> = { 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, 0.09523809524, 0.04979536153, 0.09523809524, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.14285714286, 0.09523809524, 0.09523809524, 0.09523809524, - 0.14285714286, 0.04761904762, 0.09208731242, 0.04761904762, + 0.14285714286, 0.04761904762, 0.09208731242, 0.04761904762, 0.09523809524, ], rights: [ 1, 0.2380952381, 0.66666666667, 0.92857142857, 0.80952380952, 1.09523809524, 1.09523809524, @@ -1375,7 +1379,7 @@ export const FONT_METRICS: Readonly> = { 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.76190476191, 0.52380952381, 0.52380952381, 0.47619047619, 0.52380952381, 0.7210095498, 1, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.76190476191, 0.80952380952, 1, 1, 1, - 1.04761904762, 0.85714285714, 0.7210095498, 0.85714285714, + 1.04761904762, 0.85714285714, 0.7210095498, 0.85714285714, 0.85714285714, ], tops: [ 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, @@ -1390,7 +1394,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, @@ -1404,7 +1408,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.017053206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, -0.27762619372, -0.33333333333, + -0.33333333333, -0.27762619372, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.33333333333, 1.33333333333, 1.38095238095, 1, 1, 0.33333333333, 1.52380952381, @@ -1424,7 +1428,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.71428571429, - 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, + 0.66666666667, 1, 1, 1, 1, 1.33333333333, 1, 1.33333333333, 0.95238095238, ], afterStack: 0.14285714286, }, @@ -1459,7 +1463,7 @@ export const FONT_METRICS: Readonly> = { 0.90476190476, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.90476190476, 1.04761904762, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.90476190476, 0.85714285714, 0.90476190476, 1.04761904762, 1.04761904762, 1.04761904762, 1.04761904762, - 0.90476190476, 1, 0.90476190476, + 0.90476190476, 1, 0.90476190476, 0.90476190476, ], tails: [ 0, -0.42857142857, -0.33333333333, -0.28571428571, -0.28571428571, -0.28571428571, @@ -1496,7 +1500,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.19047619048, -0.19047619048, -0.19047619048, -0.2380952381, -0.19047619048, -0.2380952381, -0.2380952381, -0.2380952381, -0.2380952381, -0.2380952381, -0.28571428571, -0.2380952381, -0.19047619048, -0.19047619048, -0.19047619048, -0.19047619048, -0.14285714286, - -0.19047619048, -0.14285714286, + -0.19047619048, -0.14285714286, -0.2380952381, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -1505,7 +1509,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -1516,7 +1520,7 @@ export const FONT_METRICS: Readonly> = { 0.00068212824, 0.16234652115, 0.07298772169, 0.07298772169, 0, 0, 0, 0, 0.02251023192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10982264666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, ], rights: [ 1, 0.09523809524, 0.38095238095, 0.71428571429, 0.66666666667, 0.85714285714, 0.90476190476, @@ -1549,7 +1553,7 @@ export const FONT_METRICS: Readonly> = { 0.61904761905, 0.47619047619, 0.47619047619, 0.47619047619, 0.47619047619, 0.66666666667, 0.85714285714, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.66666666667, 0.57142857143, 0.66666666667, 0.85714285714, 0.85714285714, 0.85714285714, 0.85714285714, - 0.76190476191, 0.80952380952, 0.76190476191, + 0.76190476191, 0.80952380952, 0.76190476191, 0.66666666667, ], tops: [ 1, 1, 1.19047619048, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, @@ -1564,7 +1568,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, @@ -1578,7 +1582,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0.33333333333, 0, -0.33333333333, + -0.33333333333, 0, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, @@ -1598,7 +1602,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, 1, 1, 1, 1.33333333333, - 1, 1.33333333333, + 1, 1.33333333333, 0.95238095238, ], afterStack: 0.28571428571, }, @@ -1631,7 +1635,7 @@ export const FONT_METRICS: Readonly> = { 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.7619047619, 0.7619047619, 0.7619047619, 0.7619047619, 0.80952380952, 1.14285714286, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 0.80952380952, 1.09523809524, - 1.09523809524, 1.09523809524, 1.09523809524, 1, 1.21428571429, 1, + 1.09523809524, 1.09523809524, 1.09523809524, 1, 1.21428571429, 1, 0.80952380952, ], tails: [ 0, -0.38095238095, -0.33333333333, -0.19047619048, -0.19047619048, -0.19047619048, @@ -1666,7 +1670,7 @@ export const FONT_METRICS: Readonly> = { -0.19047619048, -0.09523809524, -0.19047619048, -0.14285714286, -0.19047619048, -0.09523809524, -0.2380952381, -0.14285714286, -0.2380952381, -0.14285714286, -0.19047619048, -0.14285714286, -0.09523809524, -0.28571428571, -0.2380952381, -0.09523809524, -0.09523809524, - -0.09523809524, -0.09523809524, -0.14285714286, -0.2380952381, -0.14285714286, + -0.09523809524, -0.09523809524, -0.14285714286, -0.2380952381, -0.14285714286, -0.2380952381, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0.2380952381, 0, 0, 0.04761904762, 0.09523809524, 0, 0, 0, 0, 0, @@ -1679,7 +1683,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0, 0, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0.14285714286, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904762, 0.04761904762, - 0.04761904762, 0.04761904762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0.04761904762, 0.04761904762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0, 0, 0, 0, 0, 0, 0.2380952381, 0, 0, 0.04761904762, 0.09523809524, 0, 0, 0, 0, 0, @@ -1694,7 +1698,7 @@ export const FONT_METRICS: Readonly> = { 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0.10982264666, 0, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0.14285714286, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04761904762, 0.04761904762, 0.04761904762, 0.04761904762, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, ], rights: [ 1, 0.33333333333, 0.52380952381, 0.71428571429, 0.80952380952, 0.85714285714, 1.04761904762, @@ -1725,7 +1729,7 @@ export const FONT_METRICS: Readonly> = { 0.57142857143, 0.57142857143, 0.66666666667, 0.61904761905, 0.71428571429, 0.57142857143, 0.61904761905, 0.57142857143, 0.66666666667, 0.57142857143, 1, 0.57142857143, 0.66666666667, 0.61904761905, 0.66666666667, 0.71428571429, 0.52380952381, 0.57142857143, 1, 1, 1, 1, - 0.85714285714, 0.97619047619, 0.85714285714, + 0.85714285714, 0.97619047619, 0.85714285714, 0.57142857143, ], tops: [ 1, 1, 1, 1, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, @@ -1740,7 +1744,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ], bottoms: [ 0, 0, 0, -0.33333333333, -0.19047619048, 0, 0, 0, -0.33333333333, -0.33333333333, 0, 0, @@ -1754,7 +1758,7 @@ export const FONT_METRICS: Readonly> = { 0, -0.28717598909, 0, 0, 0, -0.19047619048, -0.19047619048, -0.03888130969, 0, 0, 0, 0, 0, 0, 0, 0, -0.28571428571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, 0, 0, 0, 0, 0, 0, 0, -0.28571428571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, + 0, 0, 0, 0, 0, 0, 0, 0, -0.33333333333, 0, -0.33333333333, 0, ], stackTops: [ 0, 1, 0.28571428571, 1.33333333333, 1.38095238095, 1, 1, 0.28571428571, 1.52380952381, @@ -1774,7 +1778,7 @@ export const FONT_METRICS: Readonly> = { 1.19047619048, 1.19047619048, 1, 1, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.19047619048, 1.33333333333, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.95238095238, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.66666666667, 0.66666666667, 1, - 1, 1, 1, 1.33333333333, 1, 1.33333333333, + 1, 1, 1, 1.33333333333, 1, 1.33333333333, 0.95238095238, ], afterStack: 0.28571428571, }, @@ -1791,7 +1795,7 @@ export const FONT_METRICS: Readonly> = { 0.7, 0.75, 1.1, 1.1, 1, 0.7, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 1.1, 0.7, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.6, 0.5, 0.85, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 1.2, 0.8, 0.8, 0.8, 0.8, 0.8, 0.9, 0.8125, 0.8, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.9, 0.6, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.6, 0.6, 0.7, 0.7, - 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6425, 0.7, + 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6425, 0.7, 0.9, ], tails: [ 0, -0.15, -0.15, -0.15, -0.1188976378, -0.15, -0.15089882962, -0.15, -0.15, -0.15039370079, @@ -1812,7 +1816,7 @@ export const FONT_METRICS: Readonly> = { -0.11893398282, -0.11375631329, -0.11375631329, -0.11375631329, -0.11375631329, -0.11375631329, -0.11375631329, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.09901354711, -0.11375631329, -0.15, -0.15, -0.15, -0.15, -0.15, -0.15, -0.125, - -0.15, -0.15, -0.15, -0.15, -0.15, -0.15107864376, -0.15, + -0.15, -0.15, -0.15, -0.15, -0.15, -0.15107864376, -0.15, -0.15, ], heads: [ 0, 0.15, 0.15, 0.15, 0.1188976378, 0.15, 0.0912007874, 0.15, 0.15039370079, 0.15, 0.15, 0.15, @@ -1830,7 +1834,7 @@ export const FONT_METRICS: Readonly> = { 0.15, 0.15, 0.15, 0.1, 0.15, 0.15, 0.15, 0.15, 0.15, 0.06213203436, 0.11893398282, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.11375631329, 0.11893398282, 0.11893398282, 0.11893398282, 0.11893398282, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.125, - 0.11375631329, 0.11375631329, 0.11375631329, 0.11375631329, 0.15, 0.09142135624, 0.15, + 0.11375631329, 0.11375631329, 0.11375631329, 0.11375631329, 0.15, 0.09142135624, 0.15, 0.15, ], lefts: [ 0, 0.15, 0.15, 0.15, 0.1188976378, 0.15, 0.0912007874, 0.15, 0.15039370079, 0.15, 0.15, 0.15, @@ -1848,7 +1852,7 @@ export const FONT_METRICS: Readonly> = { 0.15, 0.15, 0.15, 0.1, 0.15, 0.15, 0.15, 0.15, 0.15, 0.06213203436, 0.11893398282, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.11375631329, 0.11893398282, 0.11893398282, 0.11893398282, 0.11893398282, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.125, - 0.11375631329, 0.11375631329, 0.11375631329, 0.11375631329, 0.15, 0.09142135624, 0.15, + 0.11375631329, 0.11375631329, 0.11375631329, 0.11375631329, 0.15, 0.09142135624, 0.15, 0.15, ], rights: [ 0.4, 0.15, 0.45, 0.75, 0.5811023622, 0.95, 0.75, 0.2, 0.25, 0.24960629921, 0.55, 0.55, 0.2, @@ -1867,7 +1871,7 @@ export const FONT_METRICS: Readonly> = { 0.7, 0.65, 0.65, 0.65, 0.65, 0.75, 0.66213203436, 0.68106601718, 0.58624368671, 0.58624368671, 0.58624368671, 0.58624368671, 0.58624368671, 0.58624368671, 0.75, 0.45, 0.55, 0.55, 0.55, 0.55, 0.35, 0.35, 0.45, 0.45, 0.60098645289, 0.58624368671, 0.55, 0.55, 0.55, 0.55, 0.55, - 0.55, 0.575, 0.55, 0.55, 0.55, 0.55, 0.55, 0.49142135624, 0.55, + 0.55, 0.575, 0.55, 0.55, 0.55, 0.55, 0.55, 0.49142135624, 0.55, 0.75, ], tops: [ 1, 1, 1, 1, 1, 1, 1, 1, 1.05, 1.05, 1, 1, 1, 1, 1, 1, 1, 1, 1.00019685039, 1, 1, 1, 1, 1, 1, @@ -1879,7 +1883,7 @@ export const FONT_METRICS: Readonly> = { 1.25, 1.35, 1.35, 1.35, 1.25, 1.00695436483, 1.34960629921, 1.35, 1.35, 1.35, 1.34960629921, 1.25, 1, 1, 1.35, 1.35, 1.35, 1.25, 1.35, 1, 1, 1.05, 1.05, 1.05, 1.04960629921, 1, 1.05, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1.05, 1.05, 1, 1, 1.04960629921, 1.05, 1.05, 1.05, - 1.04960629921, 1, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1, 1, + 1.04960629921, 1, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1, 1, 1, ], bottoms: [ 0, 0, 0, 0, 0, 0, -0.0093503937, 0, -0.05, -0.05, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -1890,7 +1894,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0, -0.15, 0, 0, 0, -0.05, -0.05, -0.05, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, -0.00695436483, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, -0.25, 0, -0.25, + 0, -0.25, 0, -0.25, 0, ], stackTops: [ 0, 0.9, 0.2, 0.9, 0.9, 0.9, 0.96104624895, 0.2, 1.1, 1.1, 0.4, 0.4, 0.2, 0, 0.05, 0.9, @@ -1909,7 +1913,7 @@ export const FONT_METRICS: Readonly> = { 0.99960629921, 0.9, 1, 0.66213203436, 0.83624368671, 1.03106601718, 1.03106601718, 1.03106601718, 0.93106601718, 1, 1, 1, 0.9, 0.93377169664, 0.99960629921, 1, 1, 1, 0.99960629921, 0.9, 0.5, 0.6, 1.03624368671, 1.03624368671, 1.03624368671, 0.93624368671, 1.3, - 0.9, 1.2, + 0.9, 1.2, 0.9, ], afterStack: 0.14921259843, }, @@ -1926,7 +1930,7 @@ export const FONT_METRICS: Readonly> = { 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, - 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, + 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, ], tails: [ 0, -0.55, -0.4, -0.25, -0.3188976378, -0.15, -0.25089882962, -0.525, -0.5, -0.50039370079, @@ -1947,7 +1951,7 @@ export const FONT_METRICS: Readonly> = { -0.26893398282, -0.31375631329, -0.31375631329, -0.31375631329, -0.31375631329, -0.31375631329, -0.31375631329, -0.25, -0.4, -0.35, -0.35, -0.35, -0.35, -0.45, -0.45, -0.4, -0.4, -0.29901354711, -0.31375631329, -0.35, -0.35, -0.35, -0.35, -0.35, -0.35, -0.325, -0.35, - -0.35, -0.35, -0.35, -0.35, -0.38357864376, -0.35, + -0.35, -0.35, -0.35, -0.35, -0.38357864376, -0.35, -0.25, ], heads: [ 0, 0.55, 0.4, 0.25, 0.3188976378, 0.15, 0.1912007874, 0.525, 0.50039370079, 0.5, 0.35, 0.35, @@ -1965,7 +1969,7 @@ export const FONT_METRICS: Readonly> = { 0.3, 0.3, 0.25, 0.21213203436, 0.26893398282, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.25, 0.36375631329, 0.31893398282, 0.31893398282, 0.31893398282, 0.31893398282, 0.45, 0.45, 0.4, 0.4, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.325, 0.31375631329, 0.31375631329, - 0.31375631329, 0.31375631329, 0.35, 0.31642135624, 0.35, + 0.31375631329, 0.31375631329, 0.35, 0.31642135624, 0.35, 0.25, ], lefts: [ 0, 0.55, 0.4, 0.25, 0.3188976378, 0.15, 0.1912007874, 0.525, 0.50039370079, 0.5, 0.35, 0.35, @@ -1983,7 +1987,7 @@ export const FONT_METRICS: Readonly> = { 0.3, 0.3, 0.25, 0.21213203436, 0.26893398282, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.25, 0.36375631329, 0.31893398282, 0.31893398282, 0.31893398282, 0.31893398282, 0.45, 0.45, 0.4, 0.4, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.325, 0.31375631329, 0.31375631329, - 0.31375631329, 0.31375631329, 0.35, 0.31642135624, 0.35, + 0.31375631329, 0.31375631329, 0.35, 0.31642135624, 0.35, 0.25, ], rights: [ 1.1, 0.55, 0.7, 0.85, 0.7811023622, 0.95, 0.85, 0.575, 0.6, 0.59960629921, 0.75, 0.75, 0.575, @@ -2002,7 +2006,7 @@ export const FONT_METRICS: Readonly> = { 0.85, 0.81213203436, 0.83106601718, 0.78624368671, 0.78624368671, 0.78624368671, 0.78624368671, 0.78624368671, 0.78624368671, 0.85, 0.7, 0.75, 0.75, 0.75, 0.75, 0.65, 0.65, 0.7, 0.7, 0.80098645289, 0.78624368671, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.775, 0.75, 0.75, - 0.75, 0.75, 0.75, 0.71642135624, 0.75, + 0.75, 0.75, 0.75, 0.71642135624, 0.75, 0.85, ], tops: [ 1, 1, 1, 1, 1, 1, 1, 1, 1.05, 1.05, 1, 1, 1, 1, 1, 1, 1, 1, 1.00019685039, 1, 1, 1, 1, 1, 1, @@ -2014,7 +2018,7 @@ export const FONT_METRICS: Readonly> = { 1.25, 1.35, 1.35, 1.35, 1.25, 1.00695436483, 1.34960629921, 1.35, 1.35, 1.35, 1.34960629921, 1.25, 1, 1, 1.35, 1.35, 1.35, 1.25, 1.35, 1, 1, 1.05, 1.05, 1.05, 1.04960629921, 1, 1.05, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1.05, 1.05, 1, 1, 1.04960629921, 1.05, 1.05, 1.05, - 1.04960629921, 1, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1, 1, + 1.04960629921, 1, 1, 1, 1.05, 1.05, 1.05, 1, 1.05, 1, 1, 1, ], bottoms: [ 0, 0, 0, 0, 0, 0, -0.0093503937, 0, -0.05, -0.05, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2025,7 +2029,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0, -0.15, 0, 0, 0, -0.05, -0.05, -0.05, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, -0.00695436483, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, -0.25, 0, -0.25, + 0, -0.25, 0, -0.25, 0, ], stackTops: [ 0, 0.9, 0.2, 0.9, 0.9, 0.9, 0.96104624895, 0.225, 1.1, 1.1, 0.4, 0.4, 0.2, 0, 0.05, 0.9, @@ -2044,7 +2048,7 @@ export const FONT_METRICS: Readonly> = { 0.99960629921, 0.9, 1, 0.66213203436, 0.83624368671, 1.03106601718, 1.03106601718, 1.03106601718, 0.93106601718, 1, 1, 1, 0.9, 0.93377169664, 0.99960629921, 1, 1, 1, 0.99960629921, 0.9, 0.5, 0.6, 1.03624368671, 1.03624368671, 1.03624368671, 0.93624368671, 1.3, - 0.9, 1.2, + 0.9, 1.2, 0.9, ], afterStack: 0.34921259843, }, @@ -2082,7 +2086,7 @@ export const FONT_METRICS: Readonly> = { 0.77694406548, 0.77694406548, 0.77694406548, 0.38813096862, 0.38813096862, 0.38813096862, 0.38813096862, 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, 0.77694406548, 0.76671214188, 0.85334242838, 0.77694406548, 0.77694406548, - 0.77694406548, 0.77694406548, 0.69849931787, 0.77694406548, 0.69849931787, + 0.77694406548, 0.77694406548, 0.69849931787, 0.77694406548, 0.69849931787, 1.08663028649, ], tails: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2093,7 +2097,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0.00204638472, 0.00204638472, 0.00204638472, 0.00204638472, 0.00204638472, 0.00204638472, 0, 0, 0, 0, 0, 0, 0, 0, 0.02182810368, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03206002729, - 0.00068212824, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0.00068212824, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.03888130969, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2104,7 +2108,7 @@ export const FONT_METRICS: Readonly> = { -0.00204638472, -0.00204638472, -0.00204638472, -0.00204638472, -0.00204638472, 0, 0, 0, 0, 0, 0, 0, 0, -0.02182810368, 0, -0.00204638472, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01159618008, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, + 0, 0, 0, 0, ], lefts: [ 0, 0.12005457026, 0.06412005457, 0.01432469304, 0.04979536153, 0.08117326057, 0.06002728513, @@ -2136,7 +2140,7 @@ export const FONT_METRICS: Readonly> = { 0.05115961801, 0.0238744884, 0.12892223738, 0, 0.00613915416, 0.04979536153, 0.09208731242, 0.04638472033, 0.04638472033, 0.04638472033, 0.04638472033, 0.04638472033, 0.05320600273, 0.08799454297, 0.08935879945, 0.08935879945, 0.08935879945, 0.08935879945, 0.02251023192, - 0.09208731242, 0.02251023192, + 0.09208731242, 0.02251023192, 0.05661664393, ], rights: [ 0.38813096862, 0.2721691678, 0.43042291951, 0.75920873124, 0.71145975443, 1.15620736699, @@ -2170,7 +2174,7 @@ export const FONT_METRICS: Readonly> = { 0.71896316507, 0.71896316507, 0.71896316507, 0.28035470669, 0.38062755798, 0.42019099591, 0.38881309686, 0.7210095498, 0.68076398363, 0.72510231924, 0.72510231924, 0.72510231924, 0.72510231924, 0.72510231924, 0.71350613915, 0.76671214188, 0.67667121419, 0.67667121419, - 0.67667121419, 0.67667121419, 0.68622100955, 0.7210095498, 0.68622100955, + 0.67667121419, 0.67667121419, 0.68622100955, 0.7210095498, 0.68622100955, 1.03478854025, ], tops: [ 1, 1, 1, 1.017053206, 1.09208731241, 1.017053206, 1.017053206, 1, 1.017053206, 1.017053206, 1, @@ -2189,7 +2193,7 @@ export const FONT_METRICS: Readonly> = { 1.00545702592, 1, 1.00613915416, 1.03478854025, 1, 1, 1.00545702592, 1.00545702592, 1.00545702592, 1.00613915416, 1.00545702592, 1.00545702592, 1.00545702592, 1.00613915416, 1, 1, 1.00545702592, 1.00545702592, 1.00545702592, 1, 1.00613915416, 1, 1, 1.00545702592, - 1.00545702592, 1.00545702592, 1.00613915416, 1.00545702592, 1, 1.00613915416, + 1.00545702592, 1.00545702592, 1.00613915416, 1.00545702592, 1, 1.00613915416, 1.03683492497, ], bottoms: [ 0, 0, 0, -0.017053206, -0.14392905866, -0.03683492497, -0.02319236016, 0, -0.29399727149, @@ -2212,6 +2216,7 @@ export const FONT_METRICS: Readonly> = { -0.01637107776, 0, 0, 0, 0, -0.017053206, 0, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, 0, -0.05388813097, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.29399727149, -0.27762619372, -0.29399727149, + -0.04024556617, ], stackTops: [ 0, 1, 0.35402455662, 1.03410641201, 1.23601637108, 1.05388813097, 1.04024556617, @@ -2241,7 +2246,7 @@ export const FONT_METRICS: Readonly> = { 1.02251023192, 1.00545702592, 1.00545702592, 1.00545702592, 1.00613915416, 1.017053206, 0.98908594816, 1.02182810368, 1.02182810368, 1.02182810368, 1.00545702592, 1.02251023192, 0.55115961801, 0.82264665757, 1.02182810368, 1.02182810368, 1.02182810368, 1.02251023192, - 1.29945429741, 1.27762619372, 1.30013642565, + 1.29945429741, 1.27762619372, 1.30013642565, 1.07708049113, ], afterStack: 0.06684856753, bold: { @@ -2277,7 +2282,7 @@ export const FONT_METRICS: Readonly> = { 0.77694406548, 0.77694406548, 0.77694406548, 0.38813096862, 0.38813096862, 0.38813096862, 0.38813096862, 0.85334242838, 0.85334242838, 0.85334242838, 0.85334242838, 0.85334242838, 0.85334242838, 0.85334242838, 0.76671214188, 0.85334242838, 0.85334242838, 0.85334242838, - 0.85334242838, 0.85334242838, 0.77694406548, 0.85334242838, 0.77694406548, + 0.85334242838, 0.85334242838, 0.77694406548, 0.85334242838, 0.77694406548, 1.08663028649, ], lefts: [ 0, 0.12551159618, 0.07639836289, 0.01227830832, 0.04774897681, 0.06070941337, 0.06139154161, @@ -2308,7 +2313,7 @@ export const FONT_METRICS: Readonly> = { 0.04433833561, 0, 0.08594815825, 0, 0, 0.05661664393, 0.09890859482, 0.05593451569, 0.05593451569, 0.05593451569, 0.05593451569, 0.05593451569, 0.03342428377, 0.05934515689, 0.09618008186, 0.09618008186, 0.09618008186, 0.09618008186, 0.00954979536, 0.09481582538, - 0.00954979536, + 0.00954979536, 0.04297407913, ], rights: [ 0.38813096862, 0.33287858117, 0.59276944065, 0.76057298772, 0.71487039563, 1.17667121419, @@ -2342,7 +2347,7 @@ export const FONT_METRICS: Readonly> = { 0.72510231924, 0.72510231924, 0.72510231924, 0.29331514325, 0.39495225102, 0.42701227831, 0.42564802183, 0.80150068213, 0.75920873124, 0.80354706685, 0.80354706685, 0.80354706685, 0.80354706685, 0.80354706685, 0.73260572988, 0.80695770805, 0.7551159618, 0.7551159618, - 0.7551159618, 0.7551159618, 0.75443383356, 0.80150068213, 0.75443383356, + 0.7551159618, 0.7551159618, 0.75443383356, 0.80150068213, 0.75443383356, 1.04774897681, ], tops: [ 1, 1, 1, 1.017053206, 1.08049113233, 1.017053206, 1.017053206, 1, 1.017053206, 1.017053206, @@ -2362,7 +2367,7 @@ export const FONT_METRICS: Readonly> = { 1.04911323329, 1, 1, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1, 1, 1.017053206, 1.017053206, 1.017053206, 1, 1.017053206, 1, 1, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1.017053206, 1, - 1.017053206, + 1.017053206, 1.04774897681, ], bottoms: [ 0, 0, 0, -0.017053206, -0.13983628922, -0.04024556617, -0.02592087312, 0, -0.29399727149, @@ -2385,7 +2390,7 @@ export const FONT_METRICS: Readonly> = { -0.01637107776, -0.01637107776, -0.01637107776, 0, 0, 0, 0, -0.017053206, 0, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, 0, -0.04979536153, -0.01637107776, -0.01637107776, -0.01637107776, -0.01637107776, -0.29399727149, - -0.275579809, -0.29399727149, + -0.275579809, -0.29399727149, -0.05593451569, ], }, }, @@ -2423,7 +2428,7 @@ export const FONT_METRICS: Readonly> = { 0.78384615385, 0.78384615385, 0.36153846154, 0.36153846154, 0.36153846154, 0.36153846154, 0.82769230769, 0.82769230769, 0.83076923077, 0.83076923077, 0.83076923077, 0.83076923077, 0.83076923077, 0.78461538462, 0.83384615385, 0.82769230769, 0.82769230769, 0.82769230769, - 0.82769230769, 0.71307692308, 0.82769230769, 0.71307692308, + 0.82769230769, 0.71307692308, 0.82769230769, 0.71307692308, 1.04538461539, ], tails: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2433,7 +2438,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04153846154, 0.05538461538, 0.03615384615, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00846153846, 0.03307692308, 0.01, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.24692307692, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2443,7 +2448,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.04, 0, 0, 0, 0, 0, -0.04, 0, -0.05230769231, -0.03384615385, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01153846154, 0, -0.02846153846, -0.00769230769, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0.20461538462, 0.10692307692, 0.02769230769, 0.07384615385, 0.05538461538, 0.08307692308, @@ -2476,7 +2481,7 @@ export const FONT_METRICS: Readonly> = { 0.07153846154, 0, 0.11230769231, 0, 0, 0.07461538462, 0.11769230769, 0.06923076923, 0.06923076923, 0.06923076923, 0.06923076923, 0.06923076923, 0.03307692308, 0.06923076923, 0.11384615385, 0.11384615385, 0.11384615385, 0.11384615385, 0.02615384615, 0.11769230769, - 0.02615384615, + 0.02615384615, 0.07615384615, ], rights: [ 0.35615384615, 0.36615384615, 0.51230769231, 0.75615384615, 0.71692307692, 1.07076923077, @@ -2510,7 +2515,7 @@ export const FONT_METRICS: Readonly> = { 0.24615384615, 0.37, 0.39461538462, 0.37153846154, 0.72769230769, 0.71384615385, 0.76153846154, 0.76153846154, 0.76153846154, 0.76153846154, 0.76153846154, 0.73846153846, 0.76461538461, 0.71076923077, 0.71076923077, 0.71076923077, 0.71076923077, 0.68615384615, - 0.75461538462, 0.68615384615, + 0.75461538462, 0.68615384615, 0.96923076923, ], tops: [ 1, 1.05692307692, 1, 1, 1.17153846154, 1.02538461538, 1.04153846154, 1, 1.09153846154, @@ -2531,7 +2536,7 @@ export const FONT_METRICS: Readonly> = { 1.07846153846, 1.07846153846, 1.07846153846, 1.00769230769, 1.07846153846, 1.07846153846, 1.07846153846, 1.00769230769, 1.07, 1.04230769231, 1.07846153846, 1.07846153846, 1.07846153846, 1.04230769231, 1.00769230769, 1, 1, 1.07846153846, 1.07846153846, - 1.07846153846, 1.00769230769, 1.07846153846, 1.07153846154, 1.00769230769, + 1.07846153846, 1.00769230769, 1.07846153846, 1.07153846154, 1.00769230769, 1.17076923077, ], bottoms: [ 0, -0.00769230769, 0, -0.00461538462, -0.18846153846, -0.02769230769, -0.01384615385, 0, @@ -2562,7 +2567,7 @@ export const FONT_METRICS: Readonly> = { -0.00461538462, -0.00461538462, -0.00461538462, -0.01461538462, -0.00461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, 0, -0.12769230769, -0.01461538462, -0.01461538462, -0.01461538462, -0.01461538462, -0.28, -0.28, - -0.28, + -0.28, -0.17692307692, ], stackTops: [ 0, 1.06461538462, 0.40538461538, 1.00461538462, 1.36, 1.05307692308, 1.05538461538, @@ -2595,7 +2600,7 @@ export const FONT_METRICS: Readonly> = { 1.08307692308, 1.08307692308, 1.01230769231, 1.08461538462, 1.04692307692, 1.09307692308, 1.09307692308, 1.09307692308, 1.05692307692, 1.02230769231, 0.75461538462, 0.98461538462, 1.09307692308, 1.09307692308, 1.09307692308, 1.02230769231, 1.35846153846, 1.35153846154, - 1.28769230769, + 1.28769230769, 1.34769230769, ], afterStack: 0.05461538462, bold: { @@ -2631,7 +2636,7 @@ export const FONT_METRICS: Readonly> = { 0.79307692308, 0.38692307692, 0.38692307692, 0.38692307692, 0.38692307692, 0.84538461538, 0.84538461538, 0.84692307692, 0.84692307692, 0.84692307692, 0.84692307692, 0.84692307692, 0.78461538462, 0.85692307692, 0.84538461538, 0.84538461538, 0.84538461538, 0.84538461538, - 0.74615384615, 0.84538461538, 0.74615384615, + 0.74615384615, 0.84538461538, 0.74615384615, 1.07230769231, ], lefts: [ 0, 0.17692307692, 0.09307692308, 0.02153846154, 0.06307692308, 0.04384615385, 0.06307692308, @@ -2664,7 +2669,7 @@ export const FONT_METRICS: Readonly> = { 0.05692307692, 0.05692307692, 0, 0.09692307692, 0, 0, 0.05846153846, 0.09692307692, 0.05538461539, 0.05538461539, 0.05538461539, 0.05538461539, 0.05538461539, 0.02615384615, 0.05538461539, 0.09307692308, 0.09307692308, 0.09307692308, 0.09307692308, 0.01692307692, - 0.09692307692, 0.01692307692, + 0.09692307692, 0.01692307692, 0.06153846154, ], rights: [ 0.35615384615, 0.39384615385, 0.56153846154, 0.76230769231, 0.73153846154, 1.10461538462, @@ -2698,7 +2703,7 @@ export const FONT_METRICS: Readonly> = { 0.41538461538, 0.43461538461, 0.41769230769, 0.76, 0.75230769231, 0.79076923077, 0.79076923077, 0.79076923077, 0.79076923077, 0.79076923077, 0.75076923077, 0.80153846154, 0.74769230769, 0.74769230769, 0.74769230769, 0.74769230769, 0.72923076923, 0.78769230769, - 0.72923076923, + 0.72923076923, 1.01076923077, ], tops: [ 1, 1.06461538462, 1, 1, 1.17307692308, 1.02307692308, 1.04538461538, 1, 1.09538461538, @@ -2719,6 +2724,7 @@ export const FONT_METRICS: Readonly> = { 1.05846153846, 1.03692307692, 1.12076923077, 1, 1, 1.08, 1.08, 1.08, 1.03692307692, 1.08, 1.08, 1.08, 1.03692307692, 1.07230769231, 1.05846153846, 1.08, 1.08, 1.08, 1.05846153846, 1.03692307692, 1, 1, 1.08, 1.08, 1.08, 1.03692307692, 1.08, 1.07076923077, 1.03692307692, + 1.16153846154, ], bottoms: [ 0, -0.01153846154, 0, -0.00461538462, -0.18923076923, -0.02615384615, -0.01692307692, 0, @@ -2749,7 +2755,7 @@ export const FONT_METRICS: Readonly> = { -0.00461538462, -0.00461538462, -0.00461538462, -0.00461538462, -0.01769230769, -0.00461538462, -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, -0.01769230769, 0, -0.13461538462, -0.01769230769, -0.01769230769, -0.01769230769, - -0.01769230769, -0.27923076923, -0.27923076923, -0.27923076923, + -0.01769230769, -0.27923076923, -0.27923076923, -0.27923076923, -0.17153846154, ], }, }, @@ -2787,7 +2793,7 @@ export const FONT_METRICS: Readonly> = { 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, - 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, ], tails: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2796,7 +2802,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2805,7 +2811,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.03289977047, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0.32746748279, 0.1973986228, 0.03289977047, 0.08492731446, 0.01530221882, 0.04361132364, @@ -2838,7 +2844,7 @@ export const FONT_METRICS: Readonly> = { 0.08951798011, 0.08951798011, 0.13159908187, 0.13159908187, 0.13159908187, 0.13159908187, 0.07651109411, 0.12241775057, 0.07039020658, 0.07039020658, 0.07039020658, 0.07039020658, 0.07039020658, 0.06426931905, 0.07039020658, 0.12241775057, 0.12241775057, 0.12241775057, - 0.12241775057, 0.04514154552, 0.12241775057, 0.04514154552, + 0.12241775057, 0.04514154552, 0.12241775057, 0.04514154552, 0.04361132364, ], rights: [ 0.86151491966, 0.52945677123, 0.66411629686, 0.8286151492, 0.76817138485, 0.84621270084, @@ -2872,7 +2878,7 @@ export const FONT_METRICS: Readonly> = { 0.77123182862, 0.77123182862, 0.77123182862, 0.74751338944, 0.74751338944, 0.74751338944, 0.74751338944, 0.76970160673, 0.73986228003, 0.79112471308, 0.79112471308, 0.79112471308, 0.79112471308, 0.79112471308, 0.79724560061, 0.79112471308, 0.73986228003, 0.73986228003, - 0.73986228003, 0.73986228003, 0.80566182096, 0.77888293803, 0.80566182096, + 0.73986228003, 0.73986228003, 0.80566182096, 0.77888293803, 0.80566182096, 0.81790359602, ], tops: [ 1, 1.08110175976, 1, 1, 1.14384085692, 1.09181331293, 1.05891354246, 1, 1.13925019128, @@ -2894,7 +2900,7 @@ export const FONT_METRICS: Readonly> = { 1.08110175976, 1.08110175976, 1.08110175976, 1.07498087223, 1.08110175976, 1.08110175976, 1.08110175976, 1.07498087223, 1.08110175976, 1.08110175976, 1.08110175976, 1.08110175976, 1.08110175976, 1.08110175976, 1.07498087223, 1, 1, 1.08110175976, 1.08110175976, - 1.08110175976, 1.07498087223, 1.08110175976, 1.08110175976, 1.07498087223, + 1.08110175976, 1.07498087223, 1.08110175976, 1.08110175976, 1.07498087223, 1.16449885233, ], bottoms: [ 0, -0.01377199694, 0, 0, -0.1805661821, -0.01071155318, -0.01071155318, 0, -0.32134659526, @@ -2917,7 +2923,7 @@ export const FONT_METRICS: Readonly> = { -0.01377199694, -0.01377199694, -0.01377199694, 0, 0, 0, 0, -0.01377199694, 0, -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, 0, -0.16449885233, -0.01377199694, -0.01377199694, -0.01377199694, -0.01377199694, -0.31828615149, - -0.31369548585, -0.31828615149, + -0.31369548585, -0.31828615149, -0.16449885233, ], stackTops: [ 0, 1.09487375669, 0.35883703137, 1, 1.32440703902, 1.10252486611, 1.06962509564, @@ -2948,7 +2954,7 @@ export const FONT_METRICS: Readonly> = { 1.08110175976, 1.08110175976, 1.07498087223, 1.09487375669, 1.08110175976, 1.09487375669, 1.09487375669, 1.09487375669, 1.09487375669, 1.08875286917, 0.79877582249, 1.09716908952, 1.09487375669, 1.09487375669, 1.09487375669, 1.08875286917, 1.39938791125, 1.3947972456, - 1.39326702372, + 1.39326702372, 1.32899770467, ], afterStack: 0.06732976282, bold: { @@ -2984,7 +2990,7 @@ export const FONT_METRICS: Readonly> = { 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, - 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, + 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, 0.86151491966, ], lefts: [ 0, 0.31216526396, 0.17368018363, 0.03136954858, 0.0688599847, 0, 0.02371843917, @@ -3017,7 +3023,7 @@ export const FONT_METRICS: Readonly> = { 0.07804131599, 0.0856924254, 0.11094108646, 0.11094108646, 0.11094108646, 0.05814843152, 0.10635042081, 0.05508798776, 0.05508798776, 0.05508798776, 0.05508798776, 0.05508798776, 0.0596786534, 0.05508798776, 0.07039020658, 0.10482019893, 0.10482019893, 0.10482019893, - 0.01759755164, 0.10635042081, 0.01759755164, + 0.01759755164, 0.10635042081, 0.01759755164, 0.02830910482, ], rights: [ 0.86151491966, 0.55011476664, 0.68783473604, 0.8286151492, 0.7895944912, 0.86151491966, @@ -3051,7 +3057,7 @@ export const FONT_METRICS: Readonly> = { 0.7895944912, 0.78347360367, 0.78347360367, 0.7727620505, 0.80489671002, 0.7727620505, 0.7727620505, 0.78653404744, 0.75669472073, 0.8064269319, 0.8064269319, 0.8064269319, 0.8064269319, 0.8064269319, 0.8026013772, 0.80719204285, 0.75516449885, 0.7895944912, - 0.75516449885, 0.75516449885, 0.84621270084, 0.80566182096, 0.84621270084, + 0.75516449885, 0.75516449885, 0.84621270084, 0.80566182096, 0.84621270084, 0.83320581484, ], tops: [ 1, 1.08110175976, 1, 1, 1.1545524101, 1.09563886764, 1.07498087223, 1, 1.14078041316, @@ -3073,7 +3079,7 @@ export const FONT_METRICS: Readonly> = { 1.08110175976, 1.08110175976, 1.08110175976, 1.09410864575, 1.08110175976, 1.08110175976, 1.08110175976, 1.09410864575, 1.08110175976, 1.09640397858, 1.08110175976, 1.08110175976, 1.08110175976, 1.09640397858, 1.09410864575, 1, 1, 1.08110175976, 1.08110175976, - 1.08110175976, 1.09410864575, 1.08110175976, 1.08110175976, 1.09410864575, + 1.08110175976, 1.09410864575, 1.08110175976, 1.08110175976, 1.09410864575, 1.16449885233, ], bottoms: [ 0, -0.01759755164, 0, 0, -0.18974751339, -0.01377199694, -0.01759755164, 0, -0.32134659526, @@ -3096,7 +3102,7 @@ export const FONT_METRICS: Readonly> = { -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, 0, 0, 0, 0, -0.01759755164, 0, -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, 0, -0.16449885233, -0.01759755164, -0.01759755164, -0.01759755164, -0.01759755164, - -0.32134659526, -0.30374904361, -0.32134659526, + -0.32134659526, -0.30374904361, -0.32134659526, -0.16449885233, ], }, }, @@ -3134,7 +3140,7 @@ export const FONT_METRICS: Readonly> = { 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, - 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, + 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, 1.05042735043, ], tails: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -3143,7 +3149,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.02307692308, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01111111111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -3152,7 +3158,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.02307692308, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00256410256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0.41965811966, 0.22735042735, 0.15982905983, 0.19487179487, 0.15982905983, 0.21709401709, @@ -3185,7 +3191,7 @@ export const FONT_METRICS: Readonly> = { 0.1094017094, 0.15897435897, 0.15897435897, 0.15897435898, 0.15897435898, 0.11025641026, 0.09230769231, 0.12393162393, 0.12393162393, 0.12393162393, 0.12393162393, 0.12393162393, 0.12307692308, 0.09572649573, 0.07777777778, 0.07777777778, 0.07777777778, 0.07777777778, - 0.12735042735, 0.03846153846, 0.12735042735, + 0.12735042735, 0.03846153846, 0.12735042735, 0.06837606838, ], rights: [ 1.05042735043, 0.63076923077, 0.82136752137, 0.88974358974, 0.8547008547, 0.89230769231, @@ -3219,7 +3225,7 @@ export const FONT_METRICS: Readonly> = { 0.91538461538, 0.91538461538, 0.89487179487, 0.89487179487, 0.89487179487, 0.89487179487, 0.91452991453, 0.94957264957, 0.9264957265, 0.9264957265, 0.9264957265, 0.9264957265, 0.9264957265, 0.92735042735, 0.95897435897, 0.95128205128, 0.95128205128, 0.95128205128, - 0.95128205128, 1.00512820513, 0.94957264957, 1.00512820513, + 0.95128205128, 1.00512820513, 0.94957264957, 1.00512820513, 0.98205128205, ], tops: [ 1, 1.09829059829, 1, 1.15042735043, 1.16324786325, 1.08974358974, 1, 1, 1.07264957265, @@ -3242,7 +3248,7 @@ export const FONT_METRICS: Readonly> = { 1.04957264957, 1.12820512821, 1.13504273504, 1.11965811966, 1.04957264957, 1.06837606838, 1.03162393162, 1.1358974359, 1.1358974359, 1.11965811966, 1.03162393162, 1.04957264957, 1, 1, 1.1358974359, 1.1358974359, 1.11965811966, 1.04957264957, 1.1358974359, 1.07264957265, - 1.05042735043, + 1.05042735043, 1.07008547009, ], bottoms: [ 0, -0.02564102564, 0, -0.11111111111, -0.16324786325, -0.02051282051, -0.02820512821, 0, @@ -3266,6 +3272,7 @@ export const FONT_METRICS: Readonly> = { -0.02820512821, 0, 0, 0, 0, -0.0264957265, 0, -0.02820512821, -0.02820512821, -0.02820512821, -0.02820512821, -0.02820512821, 0, -0.0735042735, -0.02820512821, -0.02820512821, -0.02820512821, -0.02820512821, -0.32991452991, -0.32991452991, -0.32991452991, + -0.07179487179, ], stackTops: [ 0, 1.12393162393, 0.47435897436, 1.26153846154, 1.3264957265, 1.11025641026, 0.94957264957, @@ -3296,7 +3303,7 @@ export const FONT_METRICS: Readonly> = { 1.07777777778, 1.12820512821, 1.13504273504, 1.11965811966, 1.04957264957, 1.09487179487, 1.03162393162, 1.1641025641, 1.1641025641, 1.14786324786, 1.05982905983, 1.07777777778, 0.81025641026, 0.88290598291, 1.1641025641, 1.1641025641, 1.14786324786, 1.07777777778, - 1.46581196581, 1.40256410256, 1.38034188034, + 1.46581196581, 1.40256410256, 1.38034188034, 1.14188034188, ], afterStack: 0.19572649573, bold: { @@ -3332,7 +3339,7 @@ export const FONT_METRICS: Readonly> = { 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, - 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, + 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, 1.01319043693, ], lefts: [ 0, 0.3660346249, 0.2176422094, 0.10057708162, 0.13685078318, 0.13025556472, 0.18549051937, @@ -3362,7 +3369,7 @@ export const FONT_METRICS: Readonly> = { 0.05441055235, 0.05441055235, 0.05441055235, 0.05441055235, 0.10552349547, 0.10552349547, 0.10552349547, 0.10552349547, 0.07502061006, 0.04204451772, 0.07089859852, 0.07089859852, 0.07089859852, 0.07089859852, 0.07089859852, 0.06760098928, 0.03792250618, 0.02473206925, - 0.02473206925, 0.02473206925, 0.02473206925, 0.03544929926, 0, 0.03544929926, + 0.02473206925, 0.02473206925, 0.02473206925, 0.03544929926, 0, 0.03544929926, 0.01813685078, ], rights: [ 1.01319043693, 0.63643858203, 0.78730420445, 0.90849134378, 0.87551525144, 0.88623248145, @@ -3396,7 +3403,7 @@ export const FONT_METRICS: Readonly> = { 0.93157460841, 0.93157460841, 0.90601813685, 0.90601813685, 0.90601813685, 0.90601813685, 0.91178895301, 0.96949711459, 0.94558944765, 0.94558944765, 0.94558944765, 0.94558944765, 0.94558944765, 0.94558944765, 0.96867271228, 0.9703215169, 0.9703215169, 0.9703215169, - 0.9703215169, 0.98268755153, 0.96702390767, 0.98268755153, + 0.9703215169, 0.98268755153, 0.96702390767, 0.98268755153, 0.99835119538, ], tops: [ 1, 1.09480626546, 1, 1.1582852432, 1.17312448475, 1.0593569662, 1, 1, 1.08408903545, @@ -3419,7 +3426,7 @@ export const FONT_METRICS: Readonly> = { 1.0593569662, 1.12695795548, 1.12530915087, 1.10717230008, 1.0593569662, 1.06677658697, 1.0395713108, 1.12695795548, 1.12530915087, 1.10717230008, 1.0395713108, 1.0593569662, 1, 1, 1.12695795548, 1.12530915087, 1.10717230008, 1.0593569662, 1.12530915087, 1.0692497939, - 1.0593569662, + 1.0593569662, 1.08408903545, ], bottoms: [ 0, -0.02473206925, 0, -0.1582852432, -0.21104699093, -0.02473206925, -0.02473206925, 0, @@ -3443,7 +3450,7 @@ export const FONT_METRICS: Readonly> = { -0.02720527617, -0.02720527617, 0, 0, 0, 0, -0.02885408079, 0, -0.02720527617, -0.02720527617, -0.02720527617, -0.02720527617, -0.02720527617, 0, -0.12118713932, -0.02720527617, -0.02720527617, -0.02720527617, -0.02720527617, -0.35284418796, - -0.35284418796, -0.35284418796, + -0.35284418796, -0.35284418796, -0.12036273702, ], }, }, @@ -3481,7 +3488,7 @@ export const FONT_METRICS: Readonly> = { 0.68797776233, 0.68797776233, 0.68797776233, 0.4169562196, 0.4169562196, 0.4169562196, 0.4169562196, 0.75677553857, 0.84086170952, 0.76719944406, 0.76719944406, 0.76719944406, 0.76719944406, 0.76719944406, 0.91521890202, 0.76719944406, 0.81862404448, 0.81862404448, - 0.81862404448, 0.81862404448, 0.70048644892, 0.7956914524, 0.70048644892, + 0.81862404448, 0.81862404448, 0.70048644892, 0.7956914524, 0.70048644892, 1.05906879778, ], tails: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -3493,7 +3500,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0.03266157054, 0.03266157054, 0.03266157054, 0.03266157054, 0.03266157054, 0.03266157054, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03752605976, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0.02084781098, 0, 0.02084781098, + 0, 0, 0, 0, 0, 0, 0, 0.02084781098, 0, 0.02084781098, 0.36414176511, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -3506,7 +3513,7 @@ export const FONT_METRICS: Readonly> = { -0.02849200834, -0.06740792217, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.03057678944, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01389854065, -0.00972897846, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01320361362, -0.01320361362, - -0.01320361362, + -0.01320361362, 0, ], lefts: [ 0, 0.14384989576, 0.08200138985, 0.10701876303, 0.10771369006, 0.07574704656, 0.05211952745, @@ -3537,7 +3544,7 @@ export const FONT_METRICS: Readonly> = { 0.05003474635, 0.05003474635, 0.02918693537, 0.02988186241, 0, 0, 0.04864489229, 0.04239054899, 0.04864489229, 0.04864489229, 0.04864489229, 0.04864489229, 0.04864489229, 0.1000694927, 0.04864489229, 0.02362751911, 0.02362751911, 0.02362751911, 0.02362751911, 0, 0, - 0, + 0, 0.05559416261, ], rights: [ 0.34329395413, 0.33425990271, 0.50382209868, 0.80820013899, 0.76650451703, 1.08756080612, @@ -3571,7 +3578,7 @@ export const FONT_METRICS: Readonly> = { 0.65879082696, 0.65879082696, 0.65879082696, 0.38220986796, 0.38220986796, 0.38915913829, 0.39332870049, 0.70465601112, 0.80681028492, 0.71855455177, 0.71855455177, 0.71855455177, 0.71855455177, 0.71855455177, 0.81514940931, 0.71855455177, 0.78457261988, 0.78457261988, - 0.78457261988, 0.78457261988, 0.7213342599, 0.74496177901, 0.7213342599, + 0.78457261988, 0.78457261988, 0.7213342599, 0.74496177901, 0.7213342599, 1.00347463516, ], tops: [ 1, 1.01181375956, 1, 1, 1.05906879778, 1.00972897846, 1.00972897846, 1, 1.06462821404, @@ -3593,7 +3600,7 @@ export const FONT_METRICS: Readonly> = { 1.03335649757, 1.06879777623, 1.06879777623, 1.07157748436, 1.03335649757, 1.08130646282, 1.03544127867, 1.06879777623, 1.06879777623, 1.07157748436, 1.03544127867, 1.03335649757, 1, 1, 1.06879777623, 1.06879777623, 1.07157748436, 1.03335649757, 1.06879777623, 1.07574704656, - 1.03335649757, + 1.03335649757, 1.02501737318, ], bottoms: [ 0, -0.01389854065, 0, 0, -0.20778318277, -0.02223766505, -0.02432244614, 0, -0.22793606671, @@ -3617,7 +3624,7 @@ export const FONT_METRICS: Readonly> = { -0.01737317582, -0.01806810285, -0.3085476025, -0.01806810285, -0.01806810285, -0.01806810285, -0.01806810285, 0, 0, 0, 0, -0.02084781098, 0, -0.02084781098, -0.02084781098, -0.02084781098, -0.02084781098, -0.02084781098, 0, -0.05628908965, -0.01737317582, -0.01737317582, - -0.01737317582, -0.01737317582, -0.3085476025, -0.3085476025, -0.3085476025, + -0.01737317582, -0.01737317582, -0.3085476025, -0.3085476025, -0.3085476025, -0.05837387074, ], stackTops: [ 0, 1.02571230021, 0.39054899236, 0.85476025017, 1.26685198054, 1.0319666435, 1.0340514246, @@ -3651,7 +3658,7 @@ export const FONT_METRICS: Readonly> = { 1.06879777623, 1.07157748436, 1.03335649757, 1.1021542738, 1.03544127867, 1.08964558721, 1.08964558721, 1.09242529534, 1.05628908965, 1.05420430855, 0.74148714385, 0.7915218902, 1.08617095205, 1.08617095205, 1.08895066018, 1.05072967338, 1.37734537874, 1.38429464906, - 1.34190410007, + 1.34190410007, 1.08339124392, ], afterStack: 0.07157748436, bold: { @@ -3687,7 +3694,7 @@ export const FONT_METRICS: Readonly> = { 0.81375955525, 0.81375955525, 0.81375955525, 0.50312717165, 0.50312717165, 0.50312717165, 0.50312717165, 0.90757470466, 0.98193189715, 0.90479499653, 0.90479499653, 0.90479499653, 0.90479499653, 0.90479499653, 1.00069492703, 0.90479499653, 0.96316886727, 0.96316886727, - 0.96316886727, 0.96316886727, 0.79986101459, 0.91799861015, 0.79986101459, + 0.96316886727, 0.96316886727, 0.79986101459, 0.91799861015, 0.79986101459, 1.16678248784, ], lefts: [ 0, 0.13273106324, 0.08339124392, 0.10771369006, 0.07366226546, 0.06323835997, 0.04794996525, @@ -3718,6 +3725,7 @@ export const FONT_METRICS: Readonly> = { 0.04933981932, 0.02293259208, 0.02293259208, 0, 0, 0.04933981932, 0.03057678944, 0.04933981932, 0.04933981932, 0.04933981932, 0.04933981932, 0.04933981932, 0.11396803336, 0.02432244614, 0.01111883252, 0.01111883252, 0.01111883252, 0.01111883252, 0, 0, 0, + 0.04933981932, ], rights: [ 0.36136205698, 0.40305767894, 0.64211257818, 0.89298123697, 0.83877692842, 1.18832522585, @@ -3751,7 +3759,7 @@ export const FONT_METRICS: Readonly> = { 0.78735232801, 0.78735232801, 0.78735232801, 0.47949965254, 0.47949965254, 0.47949965254, 0.49965253648, 0.85545517721, 0.95760945101, 0.85545517721, 0.85545517721, 0.85545517721, 0.85545517721, 0.85545517721, 0.88603196664, 0.87491313412, 0.94649061849, 0.94649061849, - 0.94649061849, 0.94649061849, 0.8255733148, 0.86865879083, 0.8255733148, + 0.94649061849, 0.94649061849, 0.8255733148, 0.86865879083, 0.8255733148, 1.11744266852, ], tops: [ 1, 1.00555941626, 1, 1, 1.05906879778, 1.01459346769, 1.01320361362, 1, 1.06462821404, @@ -3773,7 +3781,7 @@ export const FONT_METRICS: Readonly> = { 1.07574704656, 1.05420430855, 1.07574704656, 1.07574704656, 1.07574704656, 1.05420430855, 1.07574704656, 1.04447533009, 1.07574704656, 1.07574704656, 1.07574704656, 1.04447533009, 1.05420430855, 1, 1, 1.07574704656, 1.07574704656, 1.07574704656, 1.05420430855, - 1.07574704656, 1.07574704656, 1.05420430855, + 1.07574704656, 1.07574704656, 1.05420430855, 1.04864489229, ], bottoms: [ 0, -0.02015288395, 0, 0, -0.20778318277, -0.02432244614, -0.02432244614, 0, -0.22793606671, @@ -3798,7 +3806,7 @@ export const FONT_METRICS: Readonly> = { -0.02223766505, -0.02223766505, -0.02223766505, -0.02223766505, 0, 0, 0, 0, -0.02223766505, 0, -0.02223766505, -0.02223766505, -0.02223766505, -0.02223766505, -0.02223766505, -0.00069492703, -0.08130646282, -0.02084781098, -0.02084781098, -0.02084781098, - -0.02084781098, -0.3085476025, -0.3085476025, -0.3085476025, + -0.02084781098, -0.3085476025, -0.3085476025, -0.3085476025, -0.0660180681, ], }, }, @@ -3836,7 +3844,7 @@ export const FONT_METRICS: Readonly> = { 0.74686192469, 0.74686192469, 0.74686192469, 0.34588563459, 0.34588563459, 0.34588563459, 0.34588563459, 0.79846582985, 0.80822873082, 0.83682008368, 0.83682008368, 0.83682008368, 0.83682008368, 0.83682008368, 0.9769874477, 0.83682008368, 0.80822873082, 0.80822873082, - 0.80822873082, 0.80822873082, 0.69107391911, 0.83960948396, 0.69107391911, + 0.80822873082, 0.80822873082, 0.69107391911, 0.83960948396, 0.69107391911, 1.07670850767, ], tails: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01046025105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -3846,7 +3854,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01046025105, 0.0160390516, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0160390516, 0.02231520223, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, -0.36262203626, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01952580195, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -3856,7 +3864,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00278940028, -0.01046025105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01394700139, 0, -0.03138075314, -0.03835425384, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0.12552301255, 0.11366806137, 0.0230125523, 0.1129707113, 0.05578800558, 0.0829846583, @@ -3889,6 +3897,7 @@ export const FONT_METRICS: Readonly> = { 0.0669456067, 0, 0.06136680614, 0, 0, 0.0669456067, 0.11576011158, 0.0669456067, 0.0669456067, 0.0669456067, 0.0669456067, 0.0669456067, 0.16178521618, 0.03417015342, 0.10041841004, 0.10041841004, 0.10041841004, 0.10041841004, 0.00976290098, 0.11576011158, 0.00976290098, + 0.06555090656, ], rights: [ 0.39121338912, 0.28033472803, 0.44630404463, 0.81311018131, 0.68131101813, 1.11576011158, @@ -3922,7 +3931,7 @@ export const FONT_METRICS: Readonly> = { 0.68967921897, 0.68967921897, 0.68967921897, 0.25732217573, 0.33263598326, 0.36192468619, 0.36820083682, 0.73082287308, 0.70850767085, 0.76987447699, 0.76987447699, 0.76987447699, 0.76987447699, 0.76987447699, 0.81729428173, 0.81868898187, 0.69316596932, 0.69316596932, - 0.69316596932, 0.69316596932, 0.68410041841, 0.77266387727, 0.68410041841, + 0.69316596932, 0.69316596932, 0.68410041841, 0.77266387727, 0.68410041841, 1.01115760112, ], tops: [ 1, 1, 1, 1, 1.12691771269, 1.01534170153, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -3942,7 +3951,7 @@ export const FONT_METRICS: Readonly> = { 1.01673640167, 1, 1.09065550907, 1, 1, 1.07810320781, 1.07810320781, 1.08089260809, 1, 1.07810320781, 1.07810320781, 1.08089260809, 1, 1.06276150628, 1.01673640167, 1.07810320781, 1.07810320781, 1.08089260809, 1.01673640167, 1, 1, 1, 1.07810320781, 1.07810320781, - 1.08089260809, 1, 1.07810320781, 1.05718270572, 1, + 1.08089260809, 1, 1.07810320781, 1.05718270572, 1, 1.03974895397, ], bottoms: [ 0, -0.01255230126, 0, 0, -0.14574616457, -0.01534170153, -0.0160390516, 0, -0.22733612273, @@ -3965,7 +3974,7 @@ export const FONT_METRICS: Readonly> = { -0.01673640167, -0.01673640167, -0.01673640167, 0, 0, 0, 0, -0.01534170153, 0, -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, 0, -0.05718270572, -0.01673640167, -0.01673640167, -0.01673640167, -0.01673640167, -0.33612273361, - -0.32845188285, -0.33612273361, + -0.32845188285, -0.33612273361, -0.03556485356, ], stackTops: [ 0, 1.01255230126, 0.31171548117, 0.91422594142, 1.27266387727, 1.03068340307, 1.03277545328, @@ -3996,6 +4005,7 @@ export const FONT_METRICS: Readonly> = { 1.08089260809, 0.98675034868, 1.07810320781, 1.01673640167, 1.09483960948, 1.09483960948, 1.09762900976, 1.03347280335, 1.00348675035, 0.67642956764, 0.84239888424, 1.09483960948, 1.09483960948, 1.09762900976, 1.00348675035, 1.41422594142, 1.38563458856, 1.32287308229, + 1.07531380753, ], afterStack: 0.05857740586, bold: { @@ -4031,7 +4041,7 @@ export const FONT_METRICS: Readonly> = { 0.77266387727, 0.77266387727, 0.77266387727, 0.40585774059, 0.40585774059, 0.40585774059, 0.40585774059, 0.84728033473, 0.8640167364, 0.87238493724, 0.87238493724, 0.87238493724, 0.87238493724, 0.87238493724, 1.00976290098, 0.87308228731, 0.8640167364, 0.8640167364, - 0.8640167364, 0.8640167364, 0.76847977685, 0.88563458856, 0.76847977685, + 0.8640167364, 0.8640167364, 0.76847977685, 0.88563458856, 0.76847977685, 1.0829846583, ], lefts: [ 0, 0.1059972106, 0.13319386332, 0.02580195258, 0.08577405858, 0.06276150628, 0.05230125523, @@ -4063,7 +4073,7 @@ export const FONT_METRICS: Readonly> = { 0.05020920502, 0.05020920502, 0, 0.04951185495, 0, 0, 0.05020920502, 0.09274755928, 0.05020920502, 0.05020920502, 0.05020920502, 0.05020920502, 0.05020920502, 0.1659693166, 0.02719665272, 0.08158995816, 0.08158995816, 0.08158995816, 0.08158995816, 0, 0.09274755928, - 0, + 0, 0.05160390516, ], rights: [ 0.3940027894, 0.36122733612, 0.57112970711, 0.82008368201, 0.75523012552, 1.17573221757, @@ -4097,7 +4107,7 @@ export const FONT_METRICS: Readonly> = { 0.73430962343, 0.73430962343, 0.73430962343, 0.35843793584, 0.42677824268, 0.45815899582, 0.47419804742, 0.79707112971, 0.78242677824, 0.82287308229, 0.82287308229, 0.82287308229, 0.82287308229, 0.82287308229, 0.84518828452, 0.8410041841, 0.77126917713, 0.77126917713, - 0.77126917713, 0.77126917713, 0.77266387727, 0.83542538354, 0.77266387727, + 0.77126917713, 0.77126917713, 0.77266387727, 0.83542538354, 0.77266387727, 1.03138075314, ], tops: [ 1, 1, 1, 1, 1.12970711297, 1.01394700139, 1.01673640167, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -4118,7 +4128,7 @@ export const FONT_METRICS: Readonly> = { 1.05369595537, 1.01813110181, 1.05230125523, 1.05230125523, 1.05369595537, 1.01813110181, 1.08228730823, 1.04393305439, 1.05230125523, 1.05230125523, 1.05369595537, 1.04393305439, 1.01813110181, 1, 1, 1.05230125523, 1.05230125523, 1.05369595537, 1.01813110181, - 1.05230125523, 1.05718270572, 1.01813110181, + 1.05230125523, 1.05718270572, 1.01813110181, 1.03835425384, ], bottoms: [ 0, -0.0160390516, 0, 0, -0.14574616457, -0.01394700139, -0.0160390516, 0, -0.22733612273, @@ -4141,7 +4151,7 @@ export const FONT_METRICS: Readonly> = { -0.01743375174, -0.01743375174, -0.01743375174, 0, 0, 0, 0, -0.01743375174, 0, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, 0, -0.05439330544, -0.01743375174, -0.01743375174, -0.01743375174, -0.01743375174, - -0.33542538354, -0.32845188285, -0.33542538354, + -0.33542538354, -0.32845188285, -0.33542538354, -0.04253835425, ], }, }, @@ -4179,7 +4189,7 @@ export const FONT_METRICS: Readonly> = { 0.7239758227, 0.7239758227, 0.7239758227, 0.31430490262, 0.31430490262, 0.31430490262, 0.31430490262, 0.75083948959, 0.76695768972, 0.74680993956, 0.74680993956, 0.74680993956, 0.74680993956, 0.74680993956, 1.00067159167, 0.74680993956, 0.76695768972, 0.76695768972, - 0.76695768972, 0.76695768972, 0.68502350571, 0.760241773, 0.68502350571, + 0.76695768972, 0.76695768972, 0.68502350571, 0.760241773, 0.68502350571, 0.97313633311, ], tails: [ 0, 0, 0, 0, 0, 0, 0.0436534587, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -4191,7 +4201,7 @@ export const FONT_METRICS: Readonly> = { 0.00671591672, 0.00671591672, 0.00671591672, 0.00671591672, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00873069174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.04969778375, 0.03559435863, 0.02552048355, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, + 0, -0.28542646071, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01611820013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -4202,7 +4212,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, -0.00671591672, -0.00671591672, -0.00671591672, -0.00671591672, -0.00671591672, -0.00671591672, -0.02619207522, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00738750839, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00067159167, - 0, -0.0362659503, -0.02552048355, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, -0.0362659503, -0.02552048355, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0.15312290128, 0.07656145064, 0.09536601746, 0.07118871726, 0.06850235057, 0.04499664204, @@ -4234,6 +4244,7 @@ export const FONT_METRICS: Readonly> = { 0.08059100067, 0, 0, 0.03828072532, 0.09133646743, 0.03828072532, 0.03828072532, 0.03828072532, 0.03828072532, 0.03828072532, 0.10543989255, 0.02753525856, 0.08596373405, 0.08596373405, 0.08596373405, 0.08596373405, 0.00402955003, 0.09133646743, 0.00402955003, + 0.04432505037, ], rights: [ 0.42981867025, 0.30355943586, 0.47548690396, 0.90530557421, 0.6877098724, 1.27400940228, @@ -4267,7 +4278,7 @@ export const FONT_METRICS: Readonly> = { 0.6877098724, 0.6877098724, 0.6877098724, 0.28274009402, 0.36400268637, 0.34989926125, 0.33982538617, 0.70718603089, 0.68099395567, 0.70852921424, 0.70852921424, 0.70852921424, 0.70852921424, 0.70852921424, 0.89523169913, 0.70920080591, 0.6756212223, 0.6756212223, - 0.6756212223, 0.6756212223, 0.68099395567, 0.72061786434, 0.68099395567, + 0.6756212223, 0.6756212223, 0.68099395567, 0.72061786434, 0.68099395567, 0.92881128274, ], tops: [ 1, 1, 1, 1, 1.05842847549, 1.01880456682, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, @@ -4289,7 +4300,7 @@ export const FONT_METRICS: Readonly> = { 1.12558764271, 1.00671591672, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, 1.05171255876, 1.09603760913, 1.12558764271, 1.12558764271, 1.12558764271, 1.09603760913, 1.00671591672, 1, 1, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, - 1.12558764271, 1.04499664204, 1.00671591672, + 1.12558764271, 1.04499664204, 1.00671591672, 1.06178643385, ], bottoms: [ 0, 0, 0, 0, -0.24244459369, -0.0194761585, -0.02081934184, 0, -0.27669576897, -0.27669576897, @@ -4311,7 +4322,7 @@ export const FONT_METRICS: Readonly> = { -0.01746138348, -0.01746138348, -0.01746138348, 0, 0, 0, 0, -0.02081934184, 0, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, -0.09872397582, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.27669576897, - -0.27669576897, -0.27669576897, + -0.27669576897, -0.27669576897, -0.07790463398, ], stackTops: [ 0, 1, 0.38885157824, 1, 1.30087306917, 1.03828072532, 1.04163868368, 0.38885157824, @@ -4341,7 +4352,7 @@ export const FONT_METRICS: Readonly> = { 1.0241773002, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, 1.0725319006, 1.09603760913, 1.14640698455, 1.14640698455, 1.14640698455, 1.11685695097, 1.02753525856, 0.85292142377, 0.93149764943, 1.14640698455, 1.14640698455, 1.14640698455, 1.02753525856, - 1.40228341169, 1.32169241101, 1.2834116857, + 1.40228341169, 1.32169241101, 1.2834116857, 1.13969106783, ], afterStack: 0.0557421088, bold: { @@ -4377,7 +4388,7 @@ export const FONT_METRICS: Readonly> = { 0.81665547347, 0.81665547347, 0.81665547347, 0.41504365346, 0.41504365346, 0.41504365346, 0.41504365346, 0.8522498321, 0.88045668234, 0.84889187374, 0.84889187374, 0.84889187374, 0.84889187374, 0.84889187374, 1.12558764271, 0.84889187374, 0.88045668234, 0.88045668234, - 0.88045668234, 0.88045668234, 0.7918065816, 0.86568166555, 0.7918065816, + 0.88045668234, 0.88045668234, 0.7918065816, 0.86568166555, 0.7918065816, 1.05910006716, ], lefts: [ 0, 0.10208193418, 0.08529214238, 0.08394895903, 0.06447280054, 0.07186030893, 0.05708529214, @@ -4408,7 +4419,7 @@ export const FONT_METRICS: Readonly> = { 0.03492276696, 0.03492276696, 0.03492276696, 0.00067159167, 0.06447280054, 0, 0, 0.03492276696, 0.08999328408, 0.03492276696, 0.03492276696, 0.03492276696, 0.03492276696, 0.03492276696, 0.13028878442, 0.03492276696, 0.08394895903, 0.08394895903, 0.08394895903, - 0.08394895903, 0, 0.08999328408, 0, + 0.08394895903, 0, 0.08999328408, 0, 0.04499664204, ], rights: [ 0.40295500336, 0.36937541974, 0.58697112156, 1.04163868368, 0.82337139019, 1.57555406313, @@ -4442,7 +4453,7 @@ export const FONT_METRICS: Readonly> = { 0.78576225655, 0.78576225655, 0.78576225655, 0.36198791135, 0.42578912022, 0.44257891202, 0.44190732035, 0.81396910678, 0.7965077233, 0.81396910678, 0.81396910678, 0.81396910678, 0.81396910678, 0.81396910678, 0.99529885829, 0.81396910678, 0.79046339825, 0.79046339825, - 0.79046339825, 0.79046339825, 0.79382135661, 0.82941571524, 0.79382135661, + 0.79046339825, 0.79046339825, 0.79382135661, 0.82941571524, 0.79382135661, 1.01410342512, ], tops: [ 1, 1, 1, 1, 1.05842847549, 1.0194761585, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, @@ -4464,7 +4475,7 @@ export const FONT_METRICS: Readonly> = { 1.12558764271, 1.12558764271, 1.12558764271, 1.04499664204, 1.12558764271, 1.12558764271, 1.12558764271, 1.04499664204, 1.0557421088, 1.08327736736, 1.12558764271, 1.12558764271, 1.12558764271, 1.08327736736, 1.04499664204, 1, 1, 1.12558764271, 1.12558764271, - 1.12558764271, 1.04499664204, 1.12558764271, 1.04499664204, 1.04499664204, + 1.12558764271, 1.04499664204, 1.12558764271, 1.04499664204, 1.04499664204, 1.06917394224, ], bottoms: [ 0, 0, 0, 0, -0.24244459369, -0.02081934184, -0.02081934184, 0, -0.27669576897, @@ -4487,7 +4498,7 @@ export const FONT_METRICS: Readonly> = { -0.02014775017, -0.02014775017, -0.02014775017, 0, 0, 0, 0, -0.02350570853, 0, -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, 0, -0.10879785091, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, - -0.27669576897, -0.27669576897, -0.27669576897, + -0.27669576897, -0.27669576897, -0.27669576897, -0.08462055071, ], }, }, @@ -4525,7 +4536,7 @@ export const FONT_METRICS: Readonly> = { 0.65537130497, 0.65537130497, 0.65537130497, 0.41023792358, 0.41023792358, 0.41023792358, 0.41023792358, 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, 0.81038211968, 0.73828406633, 0.73828406633, 0.73828406633, - 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, + 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, 0.73828406633, 1.06633020908, ], tails: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00360490267, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -4535,7 +4546,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0129776496, 0, 0, 0, 0, 0, 0, 0.0021629416, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0.00504686373, 0.00144196107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0.00504686373, 0.00144196107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.08219178082, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -4545,7 +4556,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, -0.0043258832, 0, 0, 0, 0, -0.01225666907, 0, 0, 0, 0, 0, 0, -0.01009372747, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.0173035328, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01946647441, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00504686373, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.00504686373, 0, 0, ], lefts: [ 0, 0.16438356164, 0.09589041096, 0.02667627974, 0.07786589762, 0.05191059841, 0.05407354001, @@ -4577,7 +4588,7 @@ export const FONT_METRICS: Readonly> = { 0.05479452055, 0.05479452055, 0.05479452055, 0.05479452055, 0.04325883201, 0.04325883201, 0.00937274694, 0.00144196107, 0.04902667628, 0.0086517664, 0.04974765681, 0.04974765681, 0.04974765681, 0.04974765681, 0.04974765681, 0.01658255227, 0.02811824081, 0.00144196107, - 0.00144196107, 0.00144196107, 0.00144196107, 0.0086517664, 0, 0.0086517664, + 0.00144196107, 0.00144196107, 0.00144196107, 0.0086517664, 0, 0.0086517664, 0.05263157895, ], rights: [ 0.36914203317, 0.32732516222, 0.50468637347, 0.71160778659, 0.66402307138, 1.17880317231, @@ -4611,7 +4622,7 @@ export const FONT_METRICS: Readonly> = { 0.61355443403, 0.61355443403, 0.61355443403, 0.3741888969, 0.3741888969, 0.41528478731, 0.41167988464, 0.68421052632, 0.73179524153, 0.68709444845, 0.68709444845, 0.68709444845, 0.68709444845, 0.68709444845, 0.79379956741, 0.71016582552, 0.73612112473, 0.73612112473, - 0.73612112473, 0.73612112473, 0.72963229993, 0.68781542898, 0.72963229993, + 0.73612112473, 0.73612112473, 0.72963229993, 0.68781542898, 0.72963229993, 1.01009372747, ], tops: [ 1, 1, 1, 1, 1.05984138428, 1, 1, 1, 1.02523431867, 1.02523431867, 1, 1, 1, 1, 1, @@ -4628,6 +4639,7 @@ export const FONT_METRICS: Readonly> = { 1.02523431867, 1.0021629416, 1.0021629416, 1, 1, 1, 1.02811824081, 1, 1, 1.0021629416, 1.0021629416, 1, 1, 1.0021629416, 1.0021629416, 1, 1, 1.02523431867, 1, 1.0021629416, 1.0021629416, 1, 1, 1, 1, 1, 1.0021629416, 1.0021629416, 1, 1, 1.0021629416, 1.02523431867, 1, + 1.00937274694, ], bottoms: [ 0, -0.02018745494, 0, -0.02018745494, -0.11247296323, -0.04037490988, -0.02235039654, 0, @@ -4652,7 +4664,7 @@ export const FONT_METRICS: Readonly> = { -0.28118240807, -0.02018745494, -0.02018745494, -0.02018745494, -0.02018745494, 0, 0, 0, 0, -0.02018745494, 0, -0.02018745494, -0.02018745494, -0.02018745494, -0.02018745494, -0.02018745494, 0, -0.04830569575, -0.02018745494, -0.02018745494, -0.02018745494, - -0.02018745494, -0.31867339582, -0.31506849315, -0.31867339582, + -0.02018745494, -0.31867339582, -0.31506849315, -0.31867339582, -0.03388608508, ], stackTops: [ 0, 1.02018745494, 0.42105263158, 1.02018745494, 1.17231434751, 1.04037490988, 1.02235039654, @@ -4685,7 +4697,7 @@ export const FONT_METRICS: Readonly> = { 1.02235039654, 1.01874549387, 0.98341744773, 1.0021629416, 1.0021629416, 0.99855803893, 0.96322999279, 1.04542177361, 0.97764960346, 1.02235039654, 1.02235039654, 1.01874549387, 0.9978370584, 0.98341744773, 0.57390050469, 0.75414563807, 1.02235039654, 1.02235039654, - 1.01874549387, 0.98341744773, 1.32083633742, 1.34030281182, 1.28262436914, + 1.01874549387, 0.98341744773, 1.32083633742, 1.34030281182, 1.28262436914, 1.04325883201, ], afterStack: 0.05263157895, bold: { @@ -4721,7 +4733,7 @@ export const FONT_METRICS: Readonly> = { 0.65679190752, 0.65679190752, 0.65679190752, 0.41112716763, 0.41112716763, 0.41112716763, 0.41112716763, 0.73988439306, 0.82297687861, 0.73988439306, 0.73988439306, 0.73988439306, 0.73988439306, 0.73988439306, 0.81213872832, 0.73988439306, 0.82297687861, 0.82297687861, - 0.82297687861, 0.82297687861, 0.73988439306, 0.82297687861, 0.73988439306, + 0.82297687861, 0.82297687861, 0.73988439306, 0.82297687861, 0.73988439306, 1.15101156069, ], lefts: [ 0, 0.12644508671, 0.12716763006, 0.0289017341, 0.05708092486, 0.10260115607, 0.05924855491, @@ -4754,7 +4766,7 @@ export const FONT_METRICS: Readonly> = { 0.05708092486, 0.05708092486, 0, 0.03034682081, 0, 0, 0.05346820809, 0.05057803468, 0.05346820809, 0.05346820809, 0.05346820809, 0.05346820809, 0.05346820809, 0.01156069364, 0.04913294798, 0.04552023121, 0.04552023121, 0.04552023121, 0.04552023121, 0.01228323699, - 0.02817919075, 0.01228323699, + 0.02817919075, 0.01228323699, 0.05852601156, ], rights: [ 0.36994219653, 0.36705202312, 0.68930635838, 0.71026011561, 0.69291907514, 1.37716763006, @@ -4788,7 +4800,7 @@ export const FONT_METRICS: Readonly> = { 0.62210982659, 0.62210982659, 0.62210982659, 0.39523121387, 0.42774566474, 0.43858381503, 0.44075144509, 0.68713872832, 0.77962427746, 0.68713872832, 0.68713872832, 0.68713872832, 0.68713872832, 0.68713872832, 0.80130057803, 0.69147398844, 0.77528901734, 0.77528901734, - 0.77528901734, 0.77528901734, 0.72615606936, 0.75867052023, 0.72615606936, + 0.77528901734, 0.77528901734, 0.72615606936, 0.75867052023, 0.72615606936, 1.0975433526, ], tops: [ 1, 1.00216763006, 1, 1, 1.00650289017, 1.00216763006, 1.00216763006, 1, 1.00216763006, @@ -4807,7 +4819,7 @@ export const FONT_METRICS: Readonly> = { 1, 1, 1.03829479769, 1, 1, 1.01300578035, 1.01300578035, 1.03106936416, 1, 1.01300578035, 1.01300578035, 1.03106936416, 1, 1.00216763006, 1, 1.01300578035, 1.01300578035, 1.03106936416, 1, 1, 1, 1, 1.01300578035, 1.01300578035, 1.03106936416, 1, 1.01300578035, - 1.00216763006, 1, + 1.00216763006, 1, 1.02601156069, ], bottoms: [ 0, -0.01950867052, 0, -0.02023121387, -0.09971098266, -0.0411849711, -0.02239884393, 0, @@ -4832,7 +4844,7 @@ export const FONT_METRICS: Readonly> = { -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, 0, 0, 0, 0, -0.02023121387, 0, -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, 0, -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, -0.02023121387, - -0.31936416185, -0.31936416185, -0.31936416185, + -0.31936416185, -0.31936416185, -0.31936416185, -0.05563583815, ], }, }, @@ -4870,7 +4882,7 @@ export const FONT_METRICS: Readonly> = { 0.75218855219, 0.75218855219, 0.75218855219, 0.39326599327, 0.39326599327, 0.39326599327, 0.39326599327, 0.75757575758, 0.75353535354, 0.74006734007, 0.74006734007, 0.74006734007, 0.74006734007, 0.74006734007, 0.72323232323, 0.75218855219, 0.75353535354, 0.75353535354, - 0.75353535354, 0.75353535354, 0.68013468013, 0.76296296296, 0.68013468013, + 0.75353535354, 0.75353535354, 0.68013468013, 0.76296296296, 0.68013468013, 0.90572390572, ], tails: [ 0, 0, 0, 0.00808080808, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -4880,7 +4892,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0.00202020202, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00471380471, 0.0404040404, 0.06531986532, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.03771043771, 0.03636363636, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.21616161616, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -4890,7 +4902,7 @@ export const FONT_METRICS: Readonly> = { -0.00538720539, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.05387205387, -0.02087542088, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.04713804714, -0.0404040404, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, ], lefts: [ 0, 0.15757575758, 0.04848484848, 0.02491582492, 0.09158249158, 0.04107744108, 0.09562289562, @@ -4923,7 +4935,7 @@ export const FONT_METRICS: Readonly> = { 0.04377104377, 0.04377104377, 0.04175084175, 0.05387205387, 0, 0, 0.04107744108, 0.09090909091, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, 0.08215488216, 0.04107744108, 0.08417508418, 0.08417508418, 0.08417508418, 0.08417508418, - 0.00808080808, 0.09090909091, 0.00808080808, + 0.00808080808, 0.09090909091, 0.00808080808, 0.04511784512, ], rights: [ 0.41548821549, 0.3595959596, 0.39461279461, 0.73131313131, 0.64713804714, 0.7797979798, @@ -4957,7 +4969,7 @@ export const FONT_METRICS: Readonly> = { 0.70841750842, 0.70841750842, 0.70841750842, 0.28821548822, 0.36363636364, 0.43097643098, 0.42962962963, 0.6936026936, 0.66262626263, 0.6962962963, 0.6962962963, 0.6962962963, 0.6962962963, 0.6962962963, 0.64646464646, 0.6936026936, 0.67003367003, 0.67003367003, - 0.67003367003, 0.67003367003, 0.67205387205, 0.71919191919, 0.67205387205, + 0.67003367003, 0.67003367003, 0.67205387205, 0.71919191919, 0.67205387205, 0.86666666667, ], tops: [ 1, 1.00404040404, 1, 1.00134680135, 1.10572390572, 1.00404040404, 1.00404040404, 1, 1, 1, 1, @@ -4978,7 +4990,7 @@ export const FONT_METRICS: Readonly> = { 1.08956228956, 1.08956228956, 1.09292929293, 1.01885521886, 1.01683501683, 1.00471380471, 1.08956228956, 1.08956228956, 1.09292929293, 1.00471380471, 1.01885521886, 1, 1, 1.08956228956, 1.08956228956, 1.09292929293, 1.01885521886, 1.08956228956, 1.01683501683, - 1.01885521886, + 1.01885521886, 1.00404040404, ], bottoms: [ 0, -0.01346801347, 0, -0.01346801347, -0.16565656566, -0.01346801347, -0.01346801347, 0, @@ -5003,6 +5015,7 @@ export const FONT_METRICS: Readonly> = { -0.01346801347, 0, 0, 0, 0, -0.01346801347, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.28282828283, -0.28282828283, -0.28282828283, + -0.01683501683, ], stackTops: [ 0, 1.01750841751, 0.25656565657, 1.01481481481, 1.27138047138, 1.01750841751, 1.01750841751, @@ -5035,7 +5048,7 @@ export const FONT_METRICS: Readonly> = { 1.1063973064, 1.03232323232, 1.08956228956, 1.08956228956, 1.09292929293, 1.01885521886, 1.0303030303, 1.00471380471, 1.10303030303, 1.10303030303, 1.1063973064, 1.01818181818, 1.03232323232, 0.70774410774, 0.74814814815, 1.10303030303, 1.10303030303, 1.1063973064, - 1.03232323232, 1.37239057239, 1.29966329966, 1.30168350168, + 1.03232323232, 1.37239057239, 1.29966329966, 1.30168350168, 1.02087542088, ], afterStack: 0.04107744108, bold: { @@ -5071,7 +5084,7 @@ export const FONT_METRICS: Readonly> = { 0.79259259259, 0.79259259259, 0.79259259259, 0.41144781145, 0.41144781145, 0.41144781145, 0.41144781145, 0.78047138047, 0.81414141414, 0.78047138047, 0.78047138047, 0.78047138047, 0.78047138047, 0.78047138047, 0.80808080808, 0.78047138047, 0.81481481481, 0.81481481481, - 0.81481481481, 0.81481481481, 0.73602693603, 0.80336700337, 0.73602693603, + 0.81481481481, 0.81481481481, 0.73602693603, 0.80336700337, 0.73602693603, 0.94276094276, ], lefts: [ 0, 0.1468013468, 0.04713804714, 0.04377104377, 0.10437710438, 0.02087542088, 0.07542087542, @@ -5104,7 +5117,7 @@ export const FONT_METRICS: Readonly> = { 0.04377104377, 0.04377104377, 0.04377104377, 0.04713804714, 0, 0, 0.04377104377, 0.09090909091, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, 0.04377104377, 0.11043771044, 0.04377104377, 0.09090909091, 0.09090909091, 0.09090909091, 0.09090909091, - 0.00336700337, 0.07744107744, 0.00336700337, + 0.00336700337, 0.07744107744, 0.00336700337, 0.0404040404, ], rights: [ 0.41548821549, 0.367003367, 0.47003367003, 0.79057239057, 0.70168350168, 0.90774410774, @@ -5138,7 +5151,7 @@ export const FONT_METRICS: Readonly> = { 0.74882154882, 0.74882154882, 0.74882154882, 0.33737373737, 0.37171717172, 0.49898989899, 0.50505050505, 0.7367003367, 0.72323232323, 0.7367003367, 0.7367003367, 0.7367003367, 0.7367003367, 0.7367003367, 0.71515151515, 0.7367003367, 0.72390572391, 0.72390572391, - 0.72390572391, 0.72390572391, 0.72592592593, 0.74612794613, 0.72592592593, + 0.72390572391, 0.72390572391, 0.72592592593, 0.74612794613, 0.72592592593, 0.90235690236, ], tops: [ 1, 1.00404040404, 1, 1.00134680135, 1.11515151515, 1.00404040404, 1.00404040404, 1, @@ -5159,7 +5172,7 @@ export const FONT_METRICS: Readonly> = { 1.0101010101, 1.10303030303, 1, 1, 1.01548821549, 1.01548821549, 1.0303030303, 1.0101010101, 1.01548821549, 1.01548821549, 1.0303030303, 1.0101010101, 1.02154882155, 1, 1.01548821549, 1.01548821549, 1.0303030303, 1, 1.0101010101, 1, 1, 1.01548821549, 1.01548821549, - 1.0303030303, 1.0101010101, 1.01548821549, 1.0303030303, 1.0101010101, + 1.0303030303, 1.0101010101, 1.01548821549, 1.0303030303, 1.0101010101, 1.00404040404, ], bottoms: [ 0, -0.01346801347, 0, -0.01346801347, -0.15824915825, -0.01346801347, -0.01346801347, 0, @@ -5184,7 +5197,7 @@ export const FONT_METRICS: Readonly> = { -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, 0, 0, 0, 0, -0.01346801347, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, 0, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, -0.01346801347, - -0.28282828283, -0.28282828283, -0.28282828283, + -0.28282828283, -0.28282828283, -0.28282828283, -0.01683501683, ], }, }, @@ -5222,7 +5235,7 @@ export const FONT_METRICS: Readonly> = { 0.81934184016, 0.81934184016, 0.81934184016, 0.37743451981, 0.37743451981, 0.37743451981, 0.37743451981, 0.84150436535, 0.87038280725, 0.83478844862, 0.83478844862, 0.83478844862, 0.83478844862, 0.83478844862, 1.12558764271, 0.83478844862, 0.87038280725, 0.87038280725, - 0.87038280725, 0.87038280725, 0.81396910678, 0.85695097381, 0.81396910678, + 0.87038280725, 0.87038280725, 0.81396910678, 0.85695097381, 0.81396910678, 1.08260577569, ], tails: [ 0, 0, 0, 0, 0, 0, 0.04499664204, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5232,7 +5245,7 @@ export const FONT_METRICS: Readonly> = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.00268636669, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01343183345, - 0.00671591672, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0.00671591672, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.29281396911, ], heads: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.02014775017, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5242,6 +5255,7 @@ export const FONT_METRICS: Readonly> = { -0.00268636669, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01410342512, 0, -0.00738750839, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, ], lefts: [ 0, 0.19543317663, 0.11282740094, 0.13096037609, 0.1040967092, 0.10006715917, 0.07723304231, @@ -5274,7 +5288,7 @@ export const FONT_METRICS: Readonly> = { 0.07118871726, 0.07118871726, 0, 0.10745466756, 0, 0.00335795836, 0.07118871726, 0.12424445937, 0.07118871726, 0.07118871726, 0.07118871726, 0.07118871726, 0.07118871726, 0.14103425117, 0.06245802552, 0.11887172599, 0.11887172599, 0.11887172599, 0.11887172599, - 0.04096709201, 0.12424445937, 0.04096709201, + 0.04096709201, 0.12424445937, 0.04096709201, 0.07723304231, ], rights: [ 0.48354600403, 0.34586971122, 0.51846877099, 0.99462726662, 0.77904633983, 1.3801208865, @@ -5308,7 +5322,7 @@ export const FONT_METRICS: Readonly> = { 0.75218267294, 0.75218267294, 0.26930826058, 0.39086635326, 0.38415043654, 0.37407656145, 0.76359973136, 0.75151108126, 0.76359973136, 0.76359973136, 0.76359973136, 0.76359973136, 0.76359973136, 0.98455339154, 0.76359973136, 0.74613834789, 0.74613834789, 0.74613834789, - 0.74613834788, 0.77300201478, 0.7844190732, 0.77300201478, + 0.74613834788, 0.77300201478, 0.7844190732, 0.77300201478, 1.00604432505, ], tops: [ 1, 1, 1, 1, 1.05842847549, 1.01880456682, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, @@ -5330,7 +5344,7 @@ export const FONT_METRICS: Readonly> = { 1.12558764271, 1.00671591672, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, 1.05171255876, 1.08730691739, 1.12558764271, 1.12558764271, 1.12558764271, 1.08730691739, 1.00671591672, 1, 1, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, - 1.12558764271, 1.04499664204, 1.00671591672, + 1.12558764271, 1.04499664204, 1.00671591672, 1.08193418402, ], bottoms: [ 0, 0, 0, 0, -0.24244459369, -0.0194761585, -0.02081934184, 0, -0.27669576897, -0.27669576897, @@ -5352,7 +5366,7 @@ export const FONT_METRICS: Readonly> = { -0.01746138348, -0.01746138348, -0.01746138348, 0, 0, 0, 0, -0.02081934184, 0, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, 0, -0.09939556749, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, -0.27669576897, - -0.27669576897, -0.27669576897, + -0.27669576897, -0.27669576897, -0.09805238415, ], stackTops: [ 0, 1, 0.38885157824, 1, 1.30087306917, 1.03828072532, 1.04163868368, 0.38885157824, @@ -5382,7 +5396,7 @@ export const FONT_METRICS: Readonly> = { 1.0241773002, 1.12558764271, 1.12558764271, 1.12558764271, 1.00671591672, 1.0725319006, 1.08730691739, 1.14640698455, 1.14640698455, 1.14640698455, 1.10812625923, 1.02753525856, 0.86635325722, 0.93284083277, 1.14640698455, 1.14640698455, 1.14640698455, 1.02753525856, - 1.40228341169, 1.32169241101, 1.2834116857, + 1.40228341169, 1.32169241101, 1.2834116857, 1.17998656817, ], afterStack: 0.09066487576, bold: { @@ -5418,7 +5432,7 @@ export const FONT_METRICS: Readonly> = { 0.91336467428, 0.91336467428, 0.91336467428, 0.47011417058, 0.47011417058, 0.47011417058, 0.47011417058, 0.93418401612, 0.97985224983, 0.9442578912, 0.9442578912, 0.9442578912, 0.9442578912, 0.9442578912, 1.19274680994, 0.9442578912, 0.97985224983, 0.97985224983, - 0.97985224983, 0.97985224983, 0.89523169913, 0.96171927468, 0.89523169913, + 0.97985224983, 0.97985224983, 0.89523169913, 0.96171927468, 0.89523169913, 1.16924110141, ], lefts: [ 0, 0.13633310947, 0.11215580927, 0.10006715917, 0.08999328408, 0.09603760913, 0.08126259234, @@ -5451,7 +5465,7 @@ export const FONT_METRICS: Readonly> = { 0.05910006716, 0.05910006716, 0.05910006716, 0.05910006716, 0, 0.07051712559, 0, 0, 0.05910006716, 0.11417058428, 0.05910006716, 0.05910006716, 0.05910006716, 0.05910006716, 0.05910006716, 0.14640698455, 0.05910006716, 0.10812625923, 0.10812625923, 0.10812625923, - 0.10812625923, 0.02014775017, 0.11417058428, 0.02014775017, + 0.10812625923, 0.02014775017, 0.11417058428, 0.02014775017, 0.06917394224, ], rights: [ 0.47011417058, 0.41705842848, 0.69576897246, 1.09066487576, 0.89993284083, 1.65345869711, @@ -5485,7 +5499,7 @@ export const FONT_METRICS: Readonly> = { 0.85695097381, 0.85695097381, 0.85695097381, 0.39825386165, 0.4721289456, 0.47884486232, 0.48287441236, 0.87105439893, 0.8717259906, 0.88515782404, 0.88515782404, 0.88515782404, 0.88515782404, 0.88515782404, 1.04633982539, 0.88515782404, 0.86568166555, 0.86568166555, - 0.86568166555, 0.86568166555, 0.87508394896, 0.90127602418, 0.87508394896, + 0.86568166555, 0.86568166555, 0.87508394896, 0.90127602418, 0.87508394896, 1.10006715917, ], tops: [ 1, 1, 1, 1, 1.05842847549, 1.0194761585, 1.02081934184, 1, 1.04499664204, 1.04499664204, 1, @@ -5507,7 +5521,7 @@ export const FONT_METRICS: Readonly> = { 1.12558764271, 1.12558764271, 1.12558764271, 1.04499664204, 1.12558764271, 1.12558764271, 1.12558764271, 1.04499664204, 1.05708529214, 1.08663532572, 1.12558764271, 1.12558764271, 1.12558764271, 1.08663532572, 1.04499664204, 1, 1, 1.12558764271, 1.12558764271, - 1.12558764271, 1.04499664204, 1.12558764271, 1.04499664204, 1.04499664204, + 1.12558764271, 1.04499664204, 1.12558764271, 1.04499664204, 1.04499664204, 1.06917394224, ], bottoms: [ 0, 0, 0, 0, -0.24244459369, -0.02081934184, -0.02081934184, 0, -0.27669576897, @@ -5530,7 +5544,7 @@ export const FONT_METRICS: Readonly> = { -0.02014775017, -0.02014775017, -0.02014775017, 0, 0, 0, 0, -0.02350570853, 0, -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, -0.02350570853, 0, -0.10879785091, -0.02081934184, -0.02081934184, -0.02081934184, -0.02081934184, - -0.27669576897, -0.27669576897, -0.27669576897, + -0.27669576897, -0.27669576897, -0.27669576897, -0.09536601746, ], }, }, diff --git a/src/index.ts b/src/index.ts index fe5d059..6b452c1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,7 @@ export { ARROWHEADS, DEFAULT_LEADER_ARROWHEAD, DIMENSION_FRACTIONS, + DIMENSION_RADIAL_TEXTS, DIMENSION_TEXT_FITS, DIMENSION_TEXT_PLACEMENTS, LEADER_ARROWHEADS, @@ -59,6 +60,8 @@ export { type Circle, type CloudOptions, type DimensionStyle, + type DiameterDimension, + type DiameterDimensionOptions, type DimensionStyleDefinition, type DonutOptions, type Drawing, @@ -69,6 +72,8 @@ export { type Image, type ImageOptions, type Insert, + type JoggedRadiusDimension, + type JoggedRadiusDimensionOptions, type InsertOptions, type Layer, type LayerOptions, @@ -96,11 +101,14 @@ export { type Point, type Polyline, type PolylineOptions, + type RadiusDimension, + type RadiusDimensionOptions, type RectOptions, type Sheet, type StandardAlignedDimensionOptions, type StandardLeaderOptions, type StandardLinearDimensionOptions, + type StandardRadiusDimensionOptions, type StandardViewportOptions, type Text, type TextAlign, @@ -324,6 +332,7 @@ export { type ReadCensusText, type ReadCircle, type ReadDimension, + type ReadRadialDimension, type ReadDimensionStyle, type ReadDrawingFile, type ReadEntity, diff --git a/src/inspect.ts b/src/inspect.ts index 1d305bd..c76e13e 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -12,7 +12,7 @@ import { type XrefDrawings, } from "./blocks.ts"; import { callOf, type CallSite } from "./callsite.ts"; -import { dimensionPicture, pictureTexts } from "./dimensions.ts"; +import { dimensionPicture, pictureTexts, isDimension } from "./dimensions.ts"; import { leaderPicture, leaderRepeats } from "./leaders.ts"; import type { Block, @@ -301,7 +301,7 @@ export function inspectWithin( for (const text of note.texts) keep(text, index, matrix, from, attribute); return; } - if (drawn.kind === "linear-dimension" || drawn.kind === "aligned-dimension") { + if (isDimension(drawn)) { // A dimension's text is a text where its picture puts it. const style = tablesOf(from).dimensionStyles.get(key(drawn.style)); if (style === undefined) return; @@ -404,8 +404,7 @@ export function inspectWithin( const wanted = (e: Exclude): boolean => e.kind === "text" || e.kind === "paragraph" ? !blank(e.value) - : e.kind === "linear-dimension" || - e.kind === "aligned-dimension" || + : isDimension(e) || e.kind === "leader" || (e.kind === "polyline" && e.closed && Array.isArray(e.points) && e.points.length > 2); const where = layout === undefined ? "model space" : `layout ${shown(layout)}`; @@ -617,6 +616,9 @@ function looked( return Boolean(e.closed) && Array.isArray(e.points) && e.points.length > 2; case "linear-dimension": case "aligned-dimension": + case "radius-dimension": + case "diameter-dimension": + case "jogged-radius-dimension": case "leader": return true; default: diff --git a/src/lint.ts b/src/lint.ts index f3c4461..5e585e1 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -26,6 +26,7 @@ import { validDimensionStyleHandle, type Dimension, type DimensionPlace, + isDimension, } from "./dimensions.ts"; import type { AttributeDefinition, @@ -506,6 +507,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) break; case "linear-dimension": case "aligned-dimension": + case "radius-dimension": + case "diameter-dimension": + case "jogged-radius-dimension": cost += long1(e.style) + long1(e.text) + long1(e.textBelow); break; case "leader": @@ -1697,7 +1701,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } lintImage(entity, add, problems.length === 0, named, here); } - if (entity.kind === "linear-dimension" || entity.kind === "aligned-dimension") { + if (isDimension(entity)) { lintDimension(entity, add, problems.length === 0, block !== undefined, here); // The block of its picture takes handles from its id, or else from its place. if (!r12 && !block && (id === undefined || named)) { @@ -2214,7 +2218,10 @@ function costsBoxes(e: Readonly>): boolean { kind === "insert" || kind === "leader" || kind === "linear-dimension" || - kind === "aligned-dimension" + kind === "aligned-dimension" || + kind === "radius-dimension" || + kind === "diameter-dimension" || + kind === "jogged-radius-dimension" ); } @@ -2297,6 +2304,13 @@ function geometryProblems(e: Entity): string[] { case "aligned-dimension": finite("its points and its offset", ...e.from, ...e.to, e.offset); break; + case "radius-dimension": + case "diameter-dimension": + finite("its points and its text's distance", ...e.center, ...e.point, e.textFromCenter ?? 0); + break; + case "jogged-radius-dimension": + finite("its points", ...e.center, ...e.point, ...e.start, ...e.jog); + break; case "leader": finite("its point", ...e.at); break; diff --git a/src/pdf.ts b/src/pdf.ts index 332085c..f83508d 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -497,6 +497,12 @@ const WIN_ANSI_HIGH: Readonly> = { const QUESTION = 0x3f; +/** + * The character a font that lacks one is plotted with instead, as the leading CAD app plots it: + * the diameter sign as Ø. + */ +const PLOTTED_AS: Readonly> = { "\u2205": "\u00d8" }; + /** A control character, which no face sets: U+0000 to U+001F and U+007F to U+009F. */ function control(code: number): boolean { return code < 0x20 || (code >= 0x7f && code <= 0x9f); @@ -505,7 +511,8 @@ function control(code: number): boolean { /** A character's code in Windows-1252, the encoding of the page's fonts, or `?` for one it lacks. */ function winAnsi(code: number): number { if ((code >= 0x20 && code <= 0x7e) || (code >= 0xa0 && code <= 0xff)) return code; - return WIN_ANSI_HIGH[code] ?? QUESTION; + const instead = PLOTTED_AS[String.fromCodePoint(code)]; + return WIN_ANSI_HIGH[code] ?? (instead === undefined ? QUESTION : instead.codePointAt(0)!); } /** @@ -584,8 +591,9 @@ class Embedded { /** * The code of a character, given one when it is first set. A character the font has no glyph - * for, and a control character, is added to `missing` and set as `?`, as `measureText` - * measures it, or as the font's empty glyph, code 0, when it has no `?` either. + * for is set as the character `PLOTTED_AS` gives it, if the font has that one. Otherwise it, + * and a control character, is added to `missing` and set as `?`, as `measureText` measures it, + * or as the font's empty glyph, code 0, when it has no `?` either. */ code(character: string, missing: Set): number { const known = this.codes.get(character); @@ -597,6 +605,10 @@ class Embedded { this.codes.set(character, this.glyphs.length); return this.glyphs.length; } + const instead = PLOTTED_AS[character]; + if (glyph === 0 && instead !== undefined && this.font.glyph(instead.codePointAt(0)!) !== 0) { + return this.code(instead, missing); + } missing.add(character); if (character === "?") return 0; return this.codes.get("?") ?? (this.font.glyph(QUESTION) === 0 ? 0 : this.code("?", missing)); diff --git a/src/read/check.ts b/src/read/check.ts index afcdfc9..c6755d4 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -169,6 +169,23 @@ const ENTITY: Readonly> = { "block?": "string", "blockHandle?": "string", }, + "radial-dimension": { + ...BASE, + kind: { oneOf: ["radial-dimension"] }, + type: { oneOf: ["radius", "diameter", "jogged-radius"] }, + center: "point", + point: "point", + "start?": "point", + "jog?": "point", + textAt: "point", + "placed?": "boolean", + "measurement?": "number", + "text?": "string", + "textBelow?": "string", + style: "string", + "block?": "string", + "blockHandle?": "string", + }, multileader: { ...BASE, kind: { oneOf: ["multileader"] }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index a0593d9..5dd5992 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -189,6 +189,7 @@ const BLOCK_READS = new Set([ "DIMENSION", "IMAGE", "INSERT", + "LARGE_RADIAL_DIMENSION", "LINE", "LWPOLYLINE", "MTEXT", @@ -206,6 +207,7 @@ const SPACE_READS = new Set([ "DIMENSION", "IMAGE", "INSERT", + "LARGE_RADIAL_DIMENSION", "MTEXT", "POLYLINE", "SEQEND", @@ -1073,7 +1075,8 @@ class DxfReader { } return; } - case "DIMENSION": { + case "DIMENSION": + case "LARGE_RADIAL_DIMENSION": { if (!space) return; const style = name(r, 3) ?? "Standard"; const dstyle = xdata(r, "ACAD"); @@ -1618,7 +1621,12 @@ class DxfReader { if (records.size === 0) return; const named = (entities: readonly ReadEntity[]): void => { for (const entity of entities) { - if (entity.kind !== "insert" && entity.kind !== "dimension") continue; + if ( + entity.kind !== "insert" && + entity.kind !== "dimension" && + entity.kind !== "radial-dimension" + ) + continue; const block = entity.block; if (block === undefined || block.length > LONGEST_NAME) continue; const handle = records.get(layerKey(block)); diff --git a/src/read/entities.ts b/src/read/entities.ts index 1a6db5d..a7640ad 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -6,6 +6,7 @@ import { wholeImageClip } from "../images.ts"; import type { ReadAttribute, ReadDimension, + ReadRadialDimension, ReadEntity, ReadEntityBase, ReadImage, @@ -209,6 +210,7 @@ export function readingOf( case "MTEXT": return mtext(r, base); case "DIMENSION": + case "LARGE_RADIAL_DIMENSION": return dimension(r, base, face, r12); case "MULTILEADER": return multileader(r, base, later); @@ -399,7 +401,9 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Reading { if (face !== 1) return { other: face === -1 ? "DIMENSION seen from below" : "DIMENSION in 3D" }; - const kind = (num(r, 70) ?? 0) & 7; + // The kind is group 70's low four bits, 9 for a jogged radius: 32, 64 and 128 are flags. + const kind = (num(r, 70) ?? 0) & 15; + if (kind === 3 || kind === 4 || kind === 9) return radialDimension(r, base, kind, r12); if (kind > 1) return { other: `DIMENSION ${DIMENSION_KINDS[kind] ?? "of another kind"}` }; const angle = kind === 0 ? (num(r, 50) ?? 0) : 0; // The leading CAD app leaves the measurement out when it is 1. An R12 file holds none. @@ -424,6 +428,38 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re return { entity }; } +/** + * A radius (group 70's kind 4), a diameter (3) or a jogged radius (9) dimension. A diameter holds + * the far end of its line in group 10 and its center halfway to group 15. + */ +function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolean): Reading { + const measurement = num(r, 42) ?? (r12 ? undefined : 1); + const text = first(r, 1); + const block = name(r, 2); + const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); + const onCircle = point(r, 15); + const definition = point(r, 10); + const center: Point = + kind === 3 + ? [(definition[0] + onCircle[0]) / 2, (definition[1] + onCircle[1]) / 2] + : definition; + const entity: ReadRadialDimension = { + ...base, + kind: "radial-dimension", + type: kind === 4 ? "radius" : kind === 3 ? "diameter" : "jogged-radius", + center, + point: onCircle, + ...(kind === 9 && { start: point(r, 13), jog: point(r, 14) }), + textAt: point(r, 11), + ...(((num(r, 70) ?? 0) & 128) !== 0 && { placed: true }), + ...(measurement !== undefined && { measurement }), + ...parts, + style: name(r, 3) ?? "Standard", + ...(block !== undefined && block !== "" && { block }), + }; + return { entity }; +} + /** * A `MULTILEADER` with one root, straight shafts and a note, as the writers write one, from the * context data that says how it is drawn. Any other is left out by what it holds. @@ -563,6 +599,8 @@ export function costOf(e: ReadEntity): number { return own + 1 + chars(e.value) + chars(e.style); case "dimension": return own + 4 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); + case "radial-dimension": + return own + 5 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "multileader": { let points = 3; for (const shaft of e.shafts) points += shaft.length; diff --git a/src/read/model.ts b/src/read/model.ts index 260589e..e86471a 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -398,6 +398,30 @@ export interface ReadDimension extends ReadEntityBase { readonly blockHandle?: string; } +/** A radius, a diameter or a jogged radius dimension. */ +export interface ReadRadialDimension extends ReadEntityBase { + readonly kind: "radial-dimension"; + readonly type: "radius" | "diameter" | "jogged-radius"; + /** The center of the circle or arc it measures. */ + readonly center: Point; + /** The point of the circle or arc its line meets. */ + readonly point: Point; + /** A jogged radius dimension's: where its line starts, and the middle of its jog. */ + readonly start?: Point; + readonly jog?: Point; + /** The middle of its text. */ + readonly textAt: Point; + /** True where the file holds its text where it was placed, not where the leading CAD app puts it. */ + readonly placed?: boolean; + /** What it measures, as the file states it, as `ReadDimension`'s. */ + readonly measurement?: number; + readonly text?: string; + readonly textBelow?: string; + readonly style: string; + readonly block?: string; + readonly blockHandle?: string; +} + /** A multileader with one note and straight shafts that meet at one landing. */ export interface ReadMultileader extends ReadEntityBase { readonly kind: "multileader"; @@ -482,6 +506,7 @@ export type ReadEntity = | ReadInsert | ReadMtext | ReadDimension + | ReadRadialDimension | ReadMultileader | ReadSolid | ReadImage; diff --git a/src/rules.ts b/src/rules.ts index 312643d..61626fb 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -13,6 +13,8 @@ import { DEFAULT_ARROWHEAD, DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, + DIMENSION_RADIAL_TEXTS, + JOG_ANGLE, DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, @@ -222,6 +224,8 @@ const FRACTION_SCALE_INLINE = 'fractionScale sizes a fraction that is "stacked" or "diagonal". A fraction on the line is as high as the text'; const TEXT_PLACEMENT_MESSAGE = 'textPlacement must be "above" or "centered"'; const TEXT_FIT_MESSAGE = 'textFit must be "inside" or "leader"'; +const RADIAL_TEXT_MESSAGE = 'radialText must be "aligned" or "horizontal"'; +const JOG_ANGLE_MESSAGE = "jogAngle must be a number of degrees from 5 to 90"; const ZEROS_OF_UNITS = 'suppressZeros is for a style in decimal units, and feetInchZeros for one in "architectural" units, which writes feet and inches'; const DIMENSION_FORMATTING = @@ -2811,6 +2815,22 @@ export function textFitProblem(value: unknown): string | undefined { return (DIMENSION_TEXT_FITS as readonly unknown[]).includes(value) ? undefined : TEXT_FIT_MESSAGE; } +/** Returns what is wrong with a dimension style's `radialText`, or undefined. */ +export function radialTextProblem(value: unknown): string | undefined { + return (DIMENSION_RADIAL_TEXTS as readonly unknown[]).includes(value) + ? undefined + : RADIAL_TEXT_MESSAGE; +} + +/** Returns what is wrong with a dimension style's `jogAngle`, or undefined. */ +export function jogAngleProblem(value: unknown): string | undefined { + return typeof value === "number" && + written(value) >= JOG_ANGLE.least && + written(value) <= JOG_ANGLE.most + ? undefined + : JOG_ANGLE_MESSAGE; +} + /** * Returns what is wrong with what a dimension style sets of how its dimensions look, or undefined: * its fraction and the fraction's height, where its text goes and its lineweights. @@ -2843,6 +2863,14 @@ export function dimensionStyleLookProblem(s: Record): string | (s.arrowhead ?? DEFAULT_ARROWHEAD) === "closed-filled" ) return LEADER_CENTERED_ARROWS; + if (s.radialText !== undefined) { + const problem = radialTextProblem(s.radialText); + if (problem) return problem; + } + if (s.jogAngle !== undefined) { + const problem = jogAngleProblem(s.jogAngle); + if (problem) return problem; + } for (const field of ["dimensionLineweight", "extensionLineweight"] as const) { const value = s[field]; if (value === undefined) continue; @@ -2923,6 +2951,22 @@ export const DIMENSION_CENTERED_WIDE = const LEADER_CENTERED_ARROWS = 'textFit "leader" with closed filled arrowheads and the text "centered" turns the arrowheads outward where tsdraft does not know the room they need, which is not laid out yet, so tsdraft refuses it. Use a tick, or the text "above"'; +/** What is wrong with a radius or a diameter dimension in a style with a prefix. */ +export const RADIAL_PREFIX = + "its style has a prefix, which the leading CAD app may put in place of the R or the diameter sign it writes before a radius or a diameter, and which is not laid out yet, so tsdraft refuses it. Use a style without a prefix, or put the words in text"; +/** What is wrong with a placed text in a style that levels a radial dimension's text. */ +export const RADIAL_PLACED_LEVEL = + 'its text is placed along its line in a style with radialText "horizontal", and where the leading CAD app levels a placed text is not laid out yet, so tsdraft refuses it. Leave textFromCenter out, or use a style with radialText "aligned"'; +/** What is wrong with a radial dimension whose text is centered where that is not laid out. */ +export const RADIAL_CENTERED = + 'its style centers its text in its line, and where the leading CAD app breaks the line of a jogged radius dimension, or of one whose text is placed, is not laid out yet, so tsdraft refuses it. Use a style with the text "above"'; +/** What is wrong with a jogged radius dimension whose last stretch is shorter than its text. */ +export const RADIAL_JOG_SHORT = + "its jog leaves the stretch from the jog to the arc shorter than its text and a gap each side, and where the leading CAD app then puts the text is not laid out yet, so tsdraft refuses it. Move the jog toward the center"; +/** What is wrong with a radius or a diameter dimension that measures nothing. */ +export const RADIAL_NO_RADIUS = + "its point is its center once they are written with the 6 decimals tsdraft writes, so it has no radius"; + /** What is wrong with a dimension in a block. */ export const DIMENSION_IN_BLOCK = "a dimension cannot be in a block. The leading CAD app draws nothing for a dimension inside a block when it opens the file, so an insert of the block would show nothing of it. Draw it in model space or on a layout"; diff --git a/src/shape.ts b/src/shape.ts index 48b545b..c0f47ab 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -18,6 +18,9 @@ import type { LeaderStyle, Line, LinearDimension, + RadiusDimension, + DiameterDimension, + JoggedRadiusDimension, Linetype, Paragraph, Polyline, @@ -494,6 +497,28 @@ function shapes(all: boolean, typed = all): Shapes { { kind, layer: string, style: ruled(string), from: point, to: point, offset: number }, { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, ), + "radius-dimension": fields( + { kind, layer: string, style: ruled(string), center: point, point }, + { + id: ruled(string), + text: ruled(string), + textBelow: ruled(string), + textFromCenter: number, + }, + ), + "diameter-dimension": fields( + { kind, layer: string, style: ruled(string), center: point, point }, + { + id: ruled(string), + text: ruled(string), + textBelow: ruled(string), + textFromCenter: number, + }, + ), + "jogged-radius-dimension": fields( + { kind, layer: string, style: ruled(string), center: point, point, start: point, jog: point }, + { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + ), // A rule of `lint` reports the note, the shafts and the leader's own fields, whatever their type. leader: fields( { @@ -623,6 +648,8 @@ function shapes(all: boolean, typed = all): Shapes { textFit: ruled(string), dimensionLineweight: ruled(numberOrName), extensionLineweight: ruled(numberOrName), + radialText: ruled(string), + jogAngle: ruled(number), }, ), ); diff --git a/src/standard/document.ts b/src/standard/document.ts index 28bec93..7e73b79 100644 --- a/src/standard/document.ts +++ b/src/standard/document.ts @@ -5,6 +5,7 @@ import type { Arrowhead, DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, + DIMENSION_RADIAL_TEXTS, DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, @@ -189,6 +190,8 @@ export interface DimensionStyleFieldsDocument extends Commented { readonly textFit?: string; readonly dimensionLineweight?: number; readonly extensionLineweight?: number; + readonly radialText?: string; + readonly jogAngle?: number; readonly writing?: { readonly [U in Units]?: WritingDocument }; readonly description?: string; } @@ -363,6 +366,8 @@ export interface StandardDimensionStyleFields { readonly textFit?: (typeof DIMENSION_TEXT_FITS)[number]; readonly dimensionLineweight?: number; readonly extensionLineweight?: number; + readonly radialText?: (typeof DIMENSION_RADIAL_TEXTS)[number]; + readonly jogAngle?: number; readonly writing?: { readonly [U in Units]?: StandardWriting }; readonly description?: string; } @@ -378,6 +383,8 @@ export interface StandardDimensionStyle { readonly textFit: (typeof DIMENSION_TEXT_FITS)[number]; readonly dimensionLineweight?: number; readonly extensionLineweight?: number; + readonly radialText: (typeof DIMENSION_RADIAL_TEXTS)[number]; + readonly jogAngle: number; readonly writing: { readonly [U in Units]?: StandardWriting }; /** Its name in the leading CAD app on a layout, when it is not its id in capitals. */ readonly layoutName?: string; diff --git a/src/standard/lint.ts b/src/standard/lint.ts index 7c25742..7a023e5 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -2,6 +2,8 @@ // refuses under a standard, for a drawing made by other code or read from JSON, under the same // rules, and what only the whole drawing shows, such as the height a text plots at in each // viewport that shows it. The leading CAD app opens a drawing that breaks them: they are the firm's. +import { JOG_ANGLE } from "../arrowheads.ts"; +import { isDimension } from "../dimensions.ts"; import { DEFAULT_ARROWHEAD, DEFAULT_LEADER_ARROWHEAD } from "../arrowheads.ts"; import { blocksByKey, @@ -361,6 +363,8 @@ export function lintStandard( ["fractionScale", style.fractionScale ?? 1, writing.fractionScale], ["textPlacement", style.textPlacement ?? "above", fields.textPlacement], ["textFit", style.textFit ?? "inside", fields.textFit], + ["radialText", style.radialText ?? "aligned", fields.radialText], + ["jogAngle", style.jogAngle ?? JOG_ANGLE.default, fields.jogAngle], ["dimensionLineweight", style.dimensionLineweight, fields.dimensionLineweight], ["extensionLineweight", style.extensionLineweight, fields.extensionLineweight], ]; @@ -1065,7 +1069,7 @@ export function lintStandard( }); }; try { - if (entity.kind === "linear-dimension" || entity.kind === "aligned-dimension") { + if (isDimension(entity)) { const style = styleRatio.get(walk.key(entity.style)); if (!style || hidden({ name: walk.layer(entity.layer) })) return; // Its box reads its style's name, its own text and what its style gives every label. diff --git a/src/standard/literal.ts b/src/standard/literal.ts index 2d9633a..228a1f1 100644 --- a/src/standard/literal.ts +++ b/src/standard/literal.ts @@ -3,6 +3,7 @@ import type { DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, + DIMENSION_RADIAL_TEXTS, DIMENSION_TEXT_PLACEMENTS, } from "../arrowheads.ts"; import type { @@ -335,11 +336,13 @@ type StyleFields = { ? Str> : F extends "textFit" ? Str> - : F extends "writing" - ? { readonly [U in keyof E[F]]: Writing } - : F extends "discipline" - ? Discipline - : unknown; + : F extends "radialText" + ? Str> + : F extends "writing" + ? { readonly [U in keyof E[F]]: Writing } + : F extends "discipline" + ? Discipline + : unknown; }; type DimensionStyle = { diff --git a/src/standard/shape.ts b/src/standard/shape.ts index 3437fd8..a40164e 100644 --- a/src/standard/shape.ts +++ b/src/standard/shape.ts @@ -9,6 +9,8 @@ import { DEFAULT_LEADER_ARROWHEAD, DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, + DIMENSION_RADIAL_TEXTS, + JOG_ANGLE, DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, @@ -26,6 +28,8 @@ import { fractionProblem, fractionScaleProblem, textFitProblem, + radialTextProblem, + jogAngleProblem, textPlacementProblem, blockNameProblem, dimensionPrefixProblem, @@ -518,6 +522,17 @@ const STYLE_FIELDS = { description: "The text above the dimension line, or centered in a break of it", default: "above", }, + radialText: { + node: string({ enum: DIMENSION_RADIAL_TEXTS }, radialTextProblem), + description: + "How a radius, a diameter or a jogged radius dimension's text reads: along its line, or level", + default: "aligned", + }, + jogAngle: { + node: number({ minimum: JOG_ANGLE.least, maximum: JOG_ANGLE.most }, jogAngleProblem), + description: "The angle of a jogged radius dimension's jog to its line, in degrees", + default: JOG_ANGLE.default, + }, textFit: { node: string({ enum: DIMENSION_TEXT_FITS }, textFitProblem), description: diff --git a/src/svg.ts b/src/svg.ts index b60909b..2490c40 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -8,7 +8,7 @@ import { type Referenced, type XrefDrawings, } from "./blocks.ts"; -import { dimensionPicture, pictureTexts, type Dimension } from "./dimensions.ts"; +import { dimensionPicture, pictureTexts, type Dimension, isDimension } from "./dimensions.ts"; import { sweep, type DimensionStyle, @@ -717,7 +717,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ? imageElement(e, mark, drawnPen, look, from, matrix, room) : ""; } - if (e.kind !== "linear-dimension" && e.kind !== "aligned-dimension") { + if (!isDimension(e)) { return entityToSvg(e, mark, drawnPen, look, styleOf(e, from), matrix, room, sides); } const tables = tablesOf(from); @@ -842,7 +842,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): drawingAt = where; if (e.kind !== "insert") { // A dimension's texts are joined before it is drawn, so their length is paid for first. - if (e.kind === "linear-dimension" || e.kind === "aligned-dimension") { + if (isDimension(e)) { if (!write((e.text?.length ?? 0) + (e.textBelow?.length ?? 0))) refuse(where()); } const element = drawn(e, marks(e, i), pen(look, styled(e), { name: e.layer }, where), look); @@ -929,8 +929,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): shown[1].kind === "text" || shown[1].kind === "paragraph" || shown[1].kind === "insert" || - shown[1].kind === "linear-dimension" || - shown[1].kind === "aligned-dimension" || + isDimension(shown[1]) || shown[1].kind === "leader"; const slack = lettered ? Math.max(box[2] - box[0], box[3] - box[1]) : 0; return [{ shown, box, slack }]; @@ -1292,9 +1291,7 @@ type Shape = Exclude; /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ function styled(e: Drawn): Pick { - return e.kind === "linear-dimension" || e.kind === "aligned-dimension" || e.kind === "leader" - ? {} - : e; + return isDimension(e) || e.kind === "leader" ? {} : e; } /** diff --git a/standard.json b/standard.json index 74b78cb..70f1935 100644 --- a/standard.json +++ b/standard.json @@ -263,6 +263,8 @@ "extensionBeyond": 0.125, "textGap": 0.0625, "textPlacement": "centered", + "radialText": "aligned", + "jogAngle": 45, "textFit": "inside", "writing": { "in": { @@ -299,6 +301,8 @@ "extensionBeyond": 0.125, "textGap": 0.0625, "textPlacement": "above", + "radialText": "aligned", + "jogAngle": 45, "textFit": "inside", "writing": { "in": { @@ -334,6 +338,8 @@ "extensionBeyond": 0.125, "textGap": 0.0625, "textPlacement": "above", + "radialText": "aligned", + "jogAngle": 45, "textFit": "inside", "writing": { "in": { diff --git a/standard.schema.json b/standard.schema.json index 0f611c2..02a62ce 100644 --- a/standard.schema.json +++ b/standard.schema.json @@ -308,6 +308,19 @@ "description": "The text above the dimension line, or centered in a break of it", "default": "above" }, + "radialText": { + "type": "string", + "enum": ["aligned", "horizontal"], + "description": "How a radius, a diameter or a jogged radius dimension's text reads: along its line, or level", + "default": "aligned" + }, + "jogAngle": { + "type": "number", + "minimum": 5, + "maximum": 90, + "description": "The angle of a jogged radius dimension's jog to its line, in degrees", + "default": 45 + }, "textFit": { "type": "string", "enum": ["inside", "leader"], @@ -416,6 +429,17 @@ "enum": ["above", "centered"], "description": "The text above the dimension line, or centered in a break of it" }, + "radialText": { + "type": "string", + "enum": ["aligned", "horizontal"], + "description": "How a radius, a diameter or a jogged radius dimension's text reads: along its line, or level" + }, + "jogAngle": { + "type": "number", + "minimum": 5, + "maximum": 90, + "description": "The angle of a jogged radius dimension's jog to its line, in degrees" + }, "textFit": { "type": "string", "enum": ["inside", "leader"], diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 8f2f39b..c145efd 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2063,7 +2063,25 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint line: [0, i + 1], textBelow: pick([long, "A\\P".repeat(5_000)]), })), + // Radial ones, with long words, a text placed far off or past the center, and a jog. + ...Array.from({ length: pick([1, 300]) }, (_, i): Data => { + const kind = pick(["radius-dimension", "diameter-dimension", "jogged-radius-dimension"]); + return { + kind, + layer: "0", + style: style.name, + center: [0, i], + point: [pick([0.01, 10, 1e9]), i], + text: pick(["<>", long]), + textBelow: pick([long, "A\\P".repeat(5_000)]), + ...(kind === "jogged-radius-dimension" + ? { start: [5, i - 5], jog: [pick([5, -1e9]), i] } + : { textFromCenter: pick([-1e9, 0, 5, 1e12]) }), + }; + }), ); + style.radialText = pick(["aligned", "horizontal"]); + style.jogAngle = pick([5, 45, 90]); } // A leader style whose arrowhead or text style every leader reads. if (random() < 0.2) { diff --git a/test/dimensions.test.ts b/test/dimensions.test.ts index 406d867..860221e 100644 --- a/test/dimensions.test.ts +++ b/test/dimensions.test.ts @@ -1046,3 +1046,62 @@ test("a stacked fraction, words below the line and a text moved out are drawn an assert.equal(read.dimensionStyles.find((s) => s.name === "S")?.textMove, 1); assert.equal(read.dimensionStyles.find((s) => s.name === "S")?.arrowheadBlock, "_Oblique"); }); + +test("a radius, a diameter and a jogged radius dimension are built, written and read back", async () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + d.dimensionStyle({ ...sizes, name: "JOG", jogAngle: 30 }); + d.radiusDimension([0, 0], [3, 4], { style: "S", id: "r" }); + d.diameterDimension([10, 0], [10, 2], { style: "S", text: "<> TYP.", textFromCenter: 1 }); + d.joggedRadiusDimension([0, 0], [30, 40], [20, 20], [24, 30], { style: "JOG" }); + const drawing = d.build(); + assert.deepEqual(lint(drawing), []); + assert.deepEqual(fromJSON(toJSON(drawing)), drawing); + const read = await readDXF(toDXF(drawing), { geometry: true }); + const radial = (read.model.entities ?? []).filter((e) => e.kind === "radial-dimension"); + assert.deepEqual( + radial.map((e) => [e.type, e.center, e.point, e.measurement]), + [ + ["radius", [0, 0], [3, 4], 5], + ["diameter", [10, 0], [10, 2], 4], + ["jogged-radius", [0, 0], [30, 40], 50], + ], + ); + assert.equal(radial[1]!.text, "<> TYP."); + assert.equal(radial[1]!.placed, true); + assert.deepEqual( + [radial[2]!.start, radial[2]!.jog], + [ + [20, 20], + [24, 30], + ], + ); + // The leading CAD app writes R and the diameter sign before the measurement itself. + const style = drawing.dimensionStyles![0]!; + assert.equal(dimensionPicture(drawing.entities[0] as never, style).label.value, "R5.00"); +}); + +test("a radial dimension is refused where the leading CAD app would draw what tsdraft does not", () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + d.dimensionStyle({ ...sizes, name: "PRE", prefix: "L=" }); + // A style's prefix may stand in place of the R the app writes. + assert.throws( + () => d.radiusDimension([0, 0], [3, 4], { style: "PRE" }), + /its style has a prefix/, + ); + assert.throws(() => d.radiusDimension([0, 0], [0, 0.0000001], { style: "S" }), /no radius/); + assert.throws( + () => d.dimensionStyle({ ...sizes, name: "STEEP", jogAngle: 95 }), + /jogAngle must be a number of degrees from 5 to 90/, + ); + assert.throws( + () => d.radiusDimension([0, 0], [3, 4], { style: "S", textFromCenter: Number.NaN }), + /textFromCenter/, + ); + // A jog so near the arc that its last stretch cannot hold the text. + assert.throws( + () => d.joggedRadiusDimension([0, 0], [120, 0], [118, 0.5], [119.7, 0.1], { style: "S" }), + /shorter than its text/, + ); +}); diff --git a/test/measure.test.ts b/test/measure.test.ts index f9fa412..83112e3 100644 --- a/test/measure.test.ts +++ b/test/measure.test.ts @@ -22,7 +22,7 @@ const same = (corners: readonly Point[], expected: readonly Point[]): void => { test("the width table holds every font, with a number for each character of its ranges", () => { assert.deepEqual(Object.keys(FONT_METRICS), Object.keys(FONTS)); const count = FONT_METRICS_RANGES.reduce((sum, [first, last]) => sum + last - first + 1, 0); - assert.equal(count, 191); + assert.equal(count, 192); for (const [font, metrics] of Object.entries(FONT_METRICS)) { const { bold } = metrics; for (const table of [ diff --git a/test/pdf.test.ts b/test/pdf.test.ts index 38a6289..7109e2d 100644 --- a/test/pdf.test.ts +++ b/test/pdf.test.ts @@ -89,7 +89,7 @@ test("a page sets the thinnest pen 0 wide, turns ARCH E as the plotter holds it, d.layer("HAIR", { lineweight: 0 }); d.layout("E", { paper: "ARCH E" }, () => { d.layer("HAIR", {}, () => d.line([1, 1], [2, 1])); - d.text([1, 2], "A ≥ B", { height: 0.25, style: "NOTE" }); + d.text([1, 2], "A ≥ B ∅", { height: 0.25, style: "NOTE" }); }); const missing: [string, string, number][] = []; const pdf = latin1(toPDF(d.build(), { missing: (...said) => missing.push(said), title: "E" })); @@ -97,7 +97,8 @@ test("a page sets the thinnest pen 0 wide, turns ARCH E as the plotter holds it, // The medium is upright, 36 by 48 inches, and the layout's point (1, 1) is at (1, 47) on it. assert.match(pdf, /\/MediaBox \[0 0 2592 3456\] \/Rotate 270/); assert.match(pdf, /^0 w\n72 3384 m\n72 3312 l\nS$/m); - assert.match(pdf, /<41203F2042> Tj/); + // The diameter sign, which the font lacks, is plotted as Ø, as the leading CAD app plots it. + assert.match(pdf, /<41203F204220D8> Tj/); assert.deepEqual(missing, [["E", "≥", 0]]); assert.match(pdf, /\/Title /); assert.match(pdf, /\/ID \[<[0-9A-F]{32}> <[0-9A-F]{32}>\]/); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index fa15273..e802084 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -5,7 +5,12 @@ // held to the doubles that app holds, within the rounding of 6 decimals for what it works out // again, and each text to what its DXF reader makes of the text it wrote. import { placeAttribute } from "../src/blocks.ts"; -import { dimensionAngle, dimensionMeasure, dimensionPicture } from "../src/dimensions.ts"; +import { + dimensionAngle, + dimensionMeasure, + dimensionPicture, + isDimension, +} from "../src/dimensions.ts"; import type { AttributeDefinition, Block, @@ -199,12 +204,7 @@ export function readProblems( } if (got.color !== undefined || got.trueColor !== undefined) say(`${label}: has a color of its own`); - if ( - want.kind !== "insert" && - want.kind !== "leader" && - want.kind !== "linear-dimension" && - want.kind !== "aligned-dimension" - ) { + if (want.kind !== "insert" && want.kind !== "leader" && !isDimension(want)) { const linetype = entityLinetype(want); if (linetype === undefined ? got.linetype !== undefined : !sameName(got.linetype, linetype)) { say(`${label}: linetype ${got.linetype}, expected ${linetype}`); @@ -399,6 +399,52 @@ export function readProblems( if (got.block !== undefined && !got.blockHandle) say(`${label}: names no block record`); return; } + case "radius-dimension": + case "diameter-dimension": + case "jogged-radius-dimension": { + if (!kind("radial-dimension") || got.kind !== "radial-dimension") return; + const type = + { "radius-dimension": "radius", "diameter-dimension": "diameter" }[ + want.kind as "radius-dimension" + ] ?? "jogged-radius"; + if (got.type !== type) say(`${label}: ${got.type}, expected ${type}`); + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if ( + !nearPoint(got.center, point(want.center)) || + !nearPoint(got.point, point(want.point)) + ) { + say(`${label}: center ${got.center}, point ${got.point}`); + } + if ( + want.kind === "jogged-radius-dimension" && + (!nearPoint(got.start ?? [NaN, NaN], point(want.start)) || + !nearPoint(got.jog ?? [NaN, NaN], point(want.jog))) + ) + say(`${label}: starts at ${got.start}, jogs at ${got.jog}`); + if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { + say(`${label}: text ${JSON.stringify(got.text)}`); + } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { + say(`${label}: text below ${JSON.stringify(got.textBelow)}`); + } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; + const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); + const picture = dimensionPicture(want, style, font); + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { + say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); + } + const measurement = + dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); + if ( + got.measurement === undefined || + Math.abs(got.measurement - measurement) > 1e-9 * Math.max(1, Math.abs(measurement)) + ) { + say(`${label}: measures ${got.measurement}, expected ${measurement}`); + } + return; + } case "leader": { if (!kind("multileader") || got.kind !== "multileader") return; const style = findLeaderStyle(drawing, want.style); diff --git a/test/shape.test.ts b/test/shape.test.ts index f4d8fda..9818b03 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -172,6 +172,40 @@ const kinds: { id: "m", ...styled, }, + "radius-dimension": { + kind: "radius-dimension", + layer: "0", + style: "ARCH", + center: [0, 0], + point: [3, 4], + text: "<> TYP", + textBelow: "MIN.", + textFromCenter: 2, + id: "h-r", + }, + "diameter-dimension": { + kind: "diameter-dimension", + layer: "0", + style: "ARCH", + center: [0, 0], + point: [-3, 4], + text: "<> BOLT", + textBelow: "EQ.", + textFromCenter: -1, + id: "h-d", + }, + "jogged-radius-dimension": { + kind: "jogged-radius-dimension", + layer: "0", + style: "ARCH", + center: [0, 0], + point: [30, 40], + start: [25, 20], + jog: [27, 30], + text: "<> CL", + textBelow: "CURB", + id: "h-j", + }, }; /** A polyline of one width, with every field the polyline of `kinds` leaves out. */ @@ -235,6 +269,8 @@ const full: Required & { textFit: "leader", dimensionLineweight: 0.5, extensionLineweight: 0.25, + radialText: "horizontal", + jogAngle: 30, }, { name: "ARCH", @@ -258,6 +294,8 @@ const full: Required & { textFit: "inside", dimensionLineweight: 0.35, extensionLineweight: 0.18, + radialText: "aligned", + jogAngle: 45, }, ], leaderStyles: [ @@ -537,7 +575,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #11: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #14: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ diff --git a/test/standard-lint.test.ts b/test/standard-lint.test.ts index cb14eef..f2779fa 100644 --- a/test/standard-lint.test.ts +++ b/test/standard-lint.test.ts @@ -175,8 +175,8 @@ test("a text plots at its role's height in each viewport that shows it, and at l assert.deepEqual( lint(half, { standard }).map((d) => d.message), [ - `text #51: This text of the role "note" plots 0.047 in tall in viewport "plan" at 1" = 10', and the role is 0.094 in: it was sized for another scale. Draw it in the view of the viewport that shows it`, - `text #51: This text plots 0.047 in tall in viewport "plan" at 1" = 10', below the standard's least height of 0.0625 in`, + `text #52: This text of the role "note" plots 0.047 in tall in viewport "plan" at 1" = 10', and the role is 0.094 in: it was sized for another scale. Draw it in the view of the viewport that shows it`, + `text #52: This text plots 0.047 in tall in viewport "plan" at 1" = 10', below the standard's least height of 0.0625 in`, ], ); // The model of the sheet at 1" = 10', shown at 1" = 20': every text and dimension is off. From 02ce9b3c127f1acc0e27079cfc12276fc303a147 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 19 Nov 2026 23:36:02 -0500 Subject: [PATCH 09/35] Paragraph text in columns that flow from one to the next Paragraph text flows through columns, as the leading CAD app lays them out. - A paragraph takes `columns`, each column as wide as its `width`, in drawing units: `{ count, height }` for that many columns, the last taking whatever the others leave; `{ height }` for as many as the text takes; or `{ heights }` for a column of each height in turn, then one for the rest. `gutter` is the room between two, five times the paragraph's height when not given. `\N` in the value starts the next column. - `layoutParagraph` lays them out where the leading CAD app plots them. A line starts the next column when its box reaches below the column's height: its ink with at-least spacing, a third of a height below its baseline with exact spacing. It starts the column as a first line does, without the room the paragraph before leaves after it. The attachment places each column as a box of its own, and static columns stand as wide as all of them. Each line gives its `column`, the layout each column's box in `columns`, and `measureParagraph` each line's column. The preview, `toPDF`, `inspectText` and the extents follow. - `lint` and the builder refuse columns that are not one of those, with no width, a count that is not a whole number from 1 to 1000, a height not above 0 as written, a gutter below 0, or numbers too large to write, and a literal value with both `height` and `heights` is a compile error. `lint` warns of a `\N` in a paragraph without columns, which breaks the line as `\P` does. - Both writers write columns as the leading CAD app saves them, and `readDXF` reads them back, its `width` then each column's. `paragraphColumnsHeld` gives what a file holds of them, and `paragraphGutter` the gutter. - A distributed line wider than its room is no longer squeezed: it stands whole, centered. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 13 ++ GUIDE.md | 12 +- README.md | 6 +- docs/paragraphs.md | 56 ++++++-- docs/reading.md | 4 +- docs/rules.md | 9 +- src/drawing.ts | 23 ++++ src/dxf-r2018.ts | 42 +++++- src/index.ts | 4 + src/lint.ts | 54 ++++++-- src/paragraph-codes.ts | 17 ++- src/paragraphs.ts | 295 +++++++++++++++++++++++++++++++++++++--- src/read/check.ts | 20 ++- src/read/entities.ts | 63 ++++++++- src/read/model.ts | 6 + src/read/mtext.ts | 1 + src/rules.ts | 105 +++++++++++++- src/shape.ts | 16 +++ test/bounded.test.ts | 16 +++ test/paragraphs.test.ts | 136 +++++++++++++++++- test/rules.test.ts | 14 +- test/shape.test.ts | 1 + 22 files changed, 842 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc7d38c..7986ff2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,19 @@ as `radial-dimension`. The font tables hold the diameter sign, with the advance a paragraph gives it in a font that lacks it; every other number is as it was. `toPDF` plots the diameter sign as Ø in a font that lacks it, as the leading CAD app plots it. +- Columns in paragraph text. `columns: { count, height }` flows a paragraph's lines through that + many columns, the last taking what the others leave; `{ height }` through as many as the text + takes; and `{ heights }` through a column of each height, then one for the rest. Each column is + the paragraph's `width` wide and `gutter` apart, five heights by default, and `\N` in the value + starts the next column. `layoutParagraph` lays them out where the leading CAD app plots them: a + line starts the next column when its box reaches below the height, and the attachment places + each column on its own. Its layout gives each line's `column` and each column's box in + `columns`, and `measureParagraph` each line's column. `lint` and the builder refuse columns that + are not one of those, and `lint` warns of a `\N` in a paragraph without columns. Both writers + write columns as the leading CAD app saves them, and `readDXF` reads them back with each + column's width. A distributed line wider than its room is no longer squeezed, and stands + centered. `ParagraphColumns`, `ParagraphColumnsHeld`, `paragraphColumnsHeld` and + `paragraphGutter` are new. - What a dimension style sets of how its dimensions look. In architectural units, `fraction` stacks the fraction of an inch over a bar, `"stacked"`, or beside a slash, `"diagonal"`, at `fractionScale` of the text's height, as `4'-1` and a stacked `7/16`. `textPlacement: diff --git a/GUIDE.md b/GUIDE.md index a3f5fc3..5a7c24c 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -247,11 +247,12 @@ layoutParagraph({ value: notes, height: 0.1, width: 4 }).lines.length; // how ma A line feed starts a new paragraph. `list` writes numbered or lettered notes in two levels, each hanging under its mark as CAD programs set a list, and `paragraphFormat` a paragraph's indents, -tab stops, justification and spacing. `measureParagraph` gives its lines and its box, from the +tab stops, justification and spacing. `columns: { count: 2, height: 6 }` flows the notes into +columns side by side, each `width` wide. `measureParagraph` gives its lines and its box, from the widths `measureText` uses, and `inspectText` checks each line as a text. `underline`, `bold`, `stack`, `superscript` and `subscript` write the codes for what they name, and `plain(text)` -escapes text from elsewhere. `lint` refuses a code tsdraft does not lay out, such as columns or -a change of height, and names it. +escapes text from elsewhere. `lint` refuses a code tsdraft does not lay out, such as a change of +height, and names it. [docs/paragraphs.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/paragraphs.md) has the codes. @@ -614,9 +615,8 @@ writeFileSync("plan.dxf", toDXF(drawing)); viewport is a locked rectangle that shows every layer at one scale. - A paper outside the list in the section on layouts, a paper in portrait, and a page setup for another plotter. -- Lists with hanging indents, tab stops and columns in a paragraph, and the codes that change - the height, width, slant, spacing or color of characters inside one. Number a list with a - text beside each note's paragraph, as the example sheet does. +- The codes that change the height, width, slant, spacing or color of characters inside a + paragraph. - Ellipses and splines. - A color on a single entity. Color comes from the layer. - DWG files. tsdraft writes DXF. diff --git a/README.md b/README.md index 14e63ed..c30c4e4 100644 --- a/README.md +++ b/README.md @@ -267,14 +267,14 @@ included, can break code written for the one before. [CHANGELOG.md](CHANGELOG.md starts each breaking change with `Breaking:`. It draws layers, lines, polylines with arcs and widths, rectangles, revision clouds, donuts, -circles, arcs, single-line text and paragraph text that wraps to a width, with lists and tab -stops, linetypes and lineweights, text styles and justification, blocks with attributes and inserts +circles, arcs, single-line text and paragraph text that wraps to a width, with lists, tab +stops and columns, linetypes and lineweights, text styles and justification, blocks with attributes and inserts of them, references to DWG files as xrefs, linear and aligned dimensions in decimal units or feet and inches with stacked fractions, words below the line and text on a leader, leaders, layouts with a page setup and viewports, which can freeze their own layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have columns or overlines in paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one +It does not yet have overlines in paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit diff --git a/docs/paragraphs.md b/docs/paragraphs.md index cbc779f..af2bf81 100644 --- a/docs/paragraphs.md +++ b/docs/paragraphs.md @@ -32,6 +32,30 @@ flush right. - `lineSpacing` is a factor of the spacing of the lines, from 0.25 to 4, 1 by default. `lineSpacingStyle` is `"at-least"`, the default, or `"exactly"`. +### Columns + +```ts +d.paragraph(notes, { at: [1, 20], width: 3, columns: { count: 2, height: 6 } }); +d.paragraph(notes, { at: [1, 12], width: 3, columns: { height: 6 } }); +d.paragraph(notes, { at: [1, 4], width: 3, columns: { heights: [6, 4] } }); +``` + +`columns` flows the lines through columns side by side, each `width` wide and `gutter` apart, in +drawing units. A column takes lines until the next one's box would reach below its height; that +line, or the first after a `\N` in the value, starts the next column at its top. In the column +that takes the rest, a `\N` only breaks the line. + +- `{ count, height }` gives that many columns, each `height` high, and the last takes whatever + the others leave, past its height. The box is as wide as all of them, filled or not. +- `{ height }` gives as many columns as the text takes, each `height` high. +- `{ heights }` gives a column of each height in turn, then one more that takes the rest. A file + holds the heights of the columns the text reaches, so heights past them are not read back. +- `gutter` is five times the paragraph's height when not given. + +`align` and `valign` place each column as a box of its own: with `valign: "bottom"`, every +column's last line ends on `at`. `layoutParagraph` gives each column's box in `columns`, and each +line its `column`. + A paragraph takes the options of every entity: an `id`, a `linetype`, a `lineweight` and, under a standard, a `pen`. Under a standard it names a `role`, which gives its height and text style as it gives a text's, and in model space the `view` it is read in. @@ -48,6 +72,7 @@ these: | Code | Draws | | -------------------- | --------------------------------------------------------------------------- | | `\P` | A paragraph break | +| `\N` | A paragraph break that starts the next column | | `\~` | A space the line does not break at | | `\\`, `\{`, `\}` | A backslash and a brace | | `{` and `}` | A group: what a code sets inside it ends at its `}`, 16 groups deep at most | @@ -151,7 +176,7 @@ message names the code. - In `\p`, an option it does not know, a tab stop that aligns text by its right, its center or a decimal point, `tr`, `tc` and `td`, and spacing at least a size, `sa`, which tsdraft does not lay out. -- The codes tsdraft does not lay out yet: `\N`, columns; `\H` the height, `\W` the width +- The codes tsdraft does not lay out yet: `\H` the height, `\W` the width factor, `\Q` the oblique angle, `\T` the spacing and `\A` the alignment of the characters after it; `\C` and `\c` color; `\O`, an overline, which sits at a TrueType font's ascent, which tsdraft's tables do not hold; `\X`, which only a dimension's text holds; and `\M+NXXXX`, a @@ -160,6 +185,11 @@ message names the code. stands depends on the top of its letters, which tsdraft's tables hold only for digits and capitals; and a stack in underlined or struck-through characters, which is laid out otherwise. +It refuses columns that are not one of the three kinds above: a count that is not a whole number +from 1 to 1000, a height or heights not above 0, from 1 to 1000 heights, a gutter below 0, and +columns on a paragraph without a width. It warns of a `\N` in a paragraph without columns, which +breaks the line as `\P` does. + It also refuses a height or a width that is not greater than 0 as written, a line spacing outside 0.25 to 4 as given, so none rounds into the range or out of it, an `align`, a `valign` or a `lineSpacingStyle` that is not one of its choices, and a text style the drawing does not have. @@ -220,7 +250,12 @@ from the widths and the ink of each character that `FONT_METRICS` holds: its last tab alike to end at the right indent, but a paragraph's last line, which stands by `align`. A distributed line grows each gap between two letters or stacks after its last tab alike, every line, and stands centered without a width. A grown line draws each word and space, - or each letter, as a run of its own. + or each letter, as a run of its own. A line wider than its room is not grown, and a distributed + one is centered. +- In columns, a line starts the next column when its box reaches below its column's height: its + ink with `"at-least"` spacing, `h/3` below its baseline with `"exactly"`, and the box of the + paragraph's own spacing. It stands at the column's top as a first line does, and the next column + is the width and the gutter further along. - With `"at-least"` spacing, each line takes `lineSpacing` times its ascent, a third of the height of what reaches highest, and `h/3`. Its ascent is how far its letters reach above the baseline, at least `h`, as an `Å` or a stack reaches further: a plain line takes `5h/3`. The first line's @@ -234,7 +269,8 @@ from the widths and the ink of each character that `FONT_METRICS` holds: its line's top and the next line `5v/3` below, and the box ends `2v/3` below the last baseline, less `4/3` of what `v` passes `h` by. - The room before a paragraph comes before its first line, the first paragraph's too, and is a - quarter of a height at least; the room after one comes before the next. Once a `\p` code has + quarter of a height at least; the room after one comes before the next, and not at the top of a + column. Once a `\p` code has `x`, the numbers of each code after it are in heights too. - The style's width factor scales everything along a line. In a TrueType font its oblique angle moves where a line starts by its first letter's bottom, and where it ends by its ascent, times @@ -276,15 +312,17 @@ Times-Bold or Courier-Bold otherwise. `FONTS` names each TrueType font's bold fi ## Reading `readDXF` reads an `MTEXT` with its point, height, width, attachment, rotation, text style, value, -line spacing factor and line spacing style. Its rotation comes from its direction, groups 11 and -21, or else from group 50 in degrees, as the leading CAD app reads it, though the DXF Reference -gives radians; tsdraft writes the direction. `layoutMtext(mtext, style)` and `measureMtext` lay +line spacing factor and line spacing style, and its columns from the embedded object the leading +CAD app saves after its own groups, its `width` then each column's. Its rotation comes from its +direction, groups 11 and 21, or else from group 50 in degrees, as the leading CAD app reads it, +though the DXF Reference gives radians; tsdraft writes the direction. `layoutMtext(mtext, style)` and `measureMtext` lay one out by the same rules, in the font of `FONTS` nearest its style's, and say it is approximate when the font is not the style's own or the value holds a code tsdraft does not lay out. [Reading drawing files](reading.md) has the rest. ## Not yet -Columns, the codes that change the height, width, slant, spacing, alignment or color of the -characters after them, an overline, stacked parts in lower case, tab stops that align text by its -right, its center or a decimal point, and attributes of more than one line. +The codes that change the height, width, slant, spacing, alignment or color of the characters +after them, an overline, stacked parts in lower case, tab stops that align text by its right, its +center or a decimal point, columns that flow from right to left, and attributes of more than one +line. diff --git a/docs/reading.md b/docs/reading.md index 66ad733..5ea18fd 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -112,7 +112,9 @@ A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers - `mtext`: a paragraph text with its point, height, width, attachment, rotation, from its direction or else from group 50 in degrees, style, value, its formatting codes kept, `lineSpacing`, its line spacing factor, 1 where the file - states none, and `lineSpacingStyle`, `"at-least"` or `"exactly"`. `layoutMtext` and + states none, `lineSpacingStyle`, `"at-least"` or `"exactly"`, and its `columns`, as a + paragraph's, with `width` then each column's. Heights one by one are those of the columns the + text reaches. `layoutMtext` and `measureMtext` lay it out as tsdraft lays out a paragraph: [Paragraphs](paragraphs.md#reading). - `dimension`: a linear or aligned dimension, with its two points, the point where its dimension line meets its second extension line, its direction, the middle of its text, what it measures, diff --git a/docs/rules.md b/docs/rules.md index 6f17e71..94a0a77 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -40,10 +40,11 @@ it would take `1e+100` for `1e+10` and report nothing. written, its line spacing is a factor from 0.25 to 4 as written, and its value holds only the codes tsdraft lays out: its braces close, each code is one tsdraft knows and ends with its `;` where it takes one, a font is one of `FONTS`, in bold only for a TrueType font and never in - italic, and braces nest at most 16 deep. The codes of lists, tab stops, columns, the height, - width, slant, spacing, alignment and color of characters, and an overline, are refused until - tsdraft lays them out, since a paragraph that held one would plot otherwise than tsdraft draws - it. So are a stacked part of other characters than digits and capitals with `.`, `,`, `+` or + italic, and braces nest at most 16 deep. The codes of the height, width, slant, spacing, + alignment and color of characters, and an overline, are refused until tsdraft lays them out, + since a paragraph that held one would plot otherwise than tsdraft draws it. Its columns are a + count and a height, a height, or heights, with a width to be as wide as, and a `\N` without + them is a warning. So are a stacked part of other characters than digits and capitals with `.`, `,`, `+` or `-`, or spaces, and a stack in underlined or struck-through characters. [Paragraphs](paragraphs.md#what-lint-refuses) has the rest. - An image is R2018 only. Its path is not empty, starts from the folder of the drawing's file and diff --git a/src/drawing.ts b/src/drawing.ts index 23ba4d0..f86f788 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -1,3 +1,4 @@ +import type { ParagraphColumns } from "./paragraphs.ts"; import { definitionHandle, insertAttributeHandle, @@ -112,6 +113,7 @@ import { textAlignProblem, textProblem, lineSpacingProblem, + paragraphColumnsProblem, paragraphChoiceProblem, paragraphProblemIn, textStyleNameProblem, @@ -487,6 +489,8 @@ export interface Paragraph extends EntityBase { readonly lineSpacing?: number; /** Defaults to `"at-least"`. */ readonly lineSpacingStyle?: LineSpacingStyle; + /** Columns its lines flow through, each `width` wide. Missing, one column. */ + readonly columns?: ParagraphColumns; } /** @@ -1461,6 +1465,11 @@ interface ParagraphPlacement; /** Defaults to `"at-least"`. */ readonly lineSpacingStyle?: LineSpacingStyle; + /** + * Columns its lines flow through, each `width` wide, in drawing units: `{ count, height }` for + * that many, `{ height }` for as many as it takes, or `{ heights }` for one of each height. + */ + readonly columns?: ParagraphColumns; } /** @@ -3022,6 +3031,20 @@ export class DrawingBuilder< if (spacingProblem) refuse("paragraph", spacingProblem); if (lineSpacing !== 1) paragraph.lineSpacing = lineSpacing as number; } + const columns: unknown = (o as { columns?: unknown }).columns; + if (columns !== undefined) { + const columnsProblem = paragraphColumnsProblem(columns, paragraph.width, paragraph.height); + if (columnsProblem) refuse("paragraph", columnsProblem); + const c = columns as ParagraphColumns; + const heights = c.heights; + paragraph.columns = { + ...(heights + ? { heights: Array.from({ length: heights.length }, (_, i) => heights[i]!) } + : { height: c.height! }), + ...(c.count !== undefined && { count: c.count }), + ...(c.gutter !== undefined && { gutter: c.gutter }), + } as ParagraphColumns; + } return paragraph as Paragraph; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 9b96d1e..a6df634 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -88,7 +88,14 @@ import { fontInfo, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { ID_HANDLE_SEED, validIdHandle } from "./handles.ts"; import { dxfOnce, dxfText, fifteenDigits, fmt, readable, written, writtenAngle } from "./format.ts"; import { layerKey, layerZeroFirst } from "./layers.ts"; -import { lineSpacingStyleCode, paragraphAttachment, paragraphDirection } from "./paragraphs.ts"; +import { + layoutParagraph, + lineSpacingStyleCode, + paragraphAttachment, + paragraphColumnsHeld, + paragraphDirection, + paragraphInStyle, +} from "./paragraphs.ts"; import { attachmentCode, LEADER_STYLE_DICTIONARY, @@ -1106,11 +1113,16 @@ function writeEntity( return; case "paragraph": { begin("MTEXT", "AcDbMText"); + // Columns: the width of them all and their height, then an embedded object after group 44, + // as the leading CAD app saves them. + const columns = + e.columns && paragraphColumnsHeld(e, layoutParagraph(paragraphInStyle(e, style))); point(g, 10, ...e.at); g(40, e.height); - g(41, e.width ?? 0); // the width its lines wrap at, or 0 for none - g(46, 0); // no height of its own - g(71, paragraphAttachment(e)); + g(41, columns ? columns.total : (e.width ?? 0)); // the width its lines wrap at, or 0 for none + g(46, columns ? columns.height : 0); // no height of its own + const attachment = paragraphAttachment(e); + g(71, attachment); g(72, 1); // left to right writeMtextValue(g, e.value); g(7, style?.name ?? STANDARD_TEXT_STYLE); @@ -1122,6 +1134,28 @@ function writeEntity( } g(73, lineSpacingStyleCode(e)); g(44, e.lineSpacing ?? 1); + if (columns) { + g(101, "Embedded Object"); + g(70, attachment); + if (cos === 1 && sin === 0) point(g, 10, 1, 0); + else { + g(10, fifteenDigits(cos)); + g(20, fifteenDigits(sin)); + g(30, 0); + } + point(g, 11, ...e.at); + g(40, columns.total); + g(41, columns.height); + g(42, columns.total); + g(43, readable(columns.tallest)); + g(71, columns.type); + g(72, columns.count); + g(44, columns.width); + g(45, columns.gutter); + g(73, columns.auto ? 1 : 0); + g(74, 0); // left to right + for (const tall of columns.heights) g(46, tall); + } return; } case "text": diff --git a/src/index.ts b/src/index.ts index 6b452c1..b86d8ed 100644 --- a/src/index.ts +++ b/src/index.ts @@ -219,8 +219,12 @@ export { lineSpacingStyleCode, measureParagraph, paragraphAttachment, + paragraphColumnsHeld, paragraphDirection, + paragraphGutter, paragraphInStyle, + type ParagraphColumns, + type ParagraphColumnsHeld, type ParagraphLayout, type ParagraphLine, type ParagraphMeasure, diff --git a/src/lint.ts b/src/lint.ts index 5e585e1..351ede3 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -145,6 +145,9 @@ import { textProblem, lineSpacingProblem, paragraphChoiceProblem, + paragraphColumnsShapeProblem, + paragraphColumnsSizeProblem, + PARAGRAPH_COLUMN_BREAK, paragraphProblemIn, paragraphValueProblem, textStyleNameProblem, @@ -451,16 +454,21 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) return found; }; /** What is wrong with a paragraph's value in its style's font, read once for a long one. */ - const paragraphChecks = new Strings>(); - const checkParagraph = (value: string, font: unknown): string | undefined => { - if (value.length < LONG) return paragraphValueProblem(value, font); - let found = paragraphChecks.get(value); + const paragraphChecks = new Strings< + Pick + >(); + /** What is wrong with a paragraph's value, and whether it holds a `\N`. */ + const checkParagraph = (value: string, font: unknown): [string | undefined, boolean] => { + let found = value.length < LONG ? undefined : paragraphChecks.get(value); if (!found) { - const { problem, ownDiameter } = parseParagraph(value); - paragraphChecks.set(value, (found = { problem, ownDiameter })); + const { problem, ownDiameter, columnBreak } = parseParagraph(value); + found = { problem, ownDiameter, columnBreak }; + if (value.length >= LONG) paragraphChecks.set(value, found); } - return paragraphProblemIn(found, font); + return [paragraphProblemIn(found, font), found.columnBreak]; }; + /** What is wrong with each columns object a paragraph gives, apart from its width. */ + const columnShapes = new WeakMap(); /** The strings of `LONG` characters or more the checks have read. */ const long = new Strings(); /** @@ -1536,12 +1544,20 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // there may be unreported, and toDXF refuses the drawing. if (stopped !== undefined) return; const here = () => `${entity.kind} #${index} of ${space}`; - // A long list of points, bulges or widths that many polylines share is read again for - // each, and paid for. - if (isObject(entity) && (entity.kind === "polyline" || entity.kind === "image")) { + // A long list of points, bulges, widths or column heights that many entities share is read + // again for each, and paid for. + if ( + isObject(entity) && + (entity.kind === "polyline" || entity.kind === "image" || entity.kind === "paragraph") + ) { let cost = 0; + const columns: unknown = entity.kind === "paragraph" ? entity.columns : undefined; const lists = - entity.kind === "image" ? [entity.clip] : [entity.points, entity.bulges, entity.widths]; + entity.kind === "image" + ? [entity.clip] + : entity.kind === "paragraph" + ? [isObject(columns) ? columns.heights : undefined] + : [entity.points, entity.bulges, entity.widths]; for (const list of lists) { if (Array.isArray(list) && list.length >= FREE && again(list)) cost += Math.floor(list.length / 8); @@ -1757,8 +1773,22 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ? (stylesByKey.get(layerKey(style))?.font ?? (isStandardTextStyle(style) ? STANDARD_FONT : undefined)) : undefined; - const problem = checkParagraph(entity.value, font); + const [problem, columnBreak] = + typeof entity.value === "string" + ? checkParagraph(entity.value, font) + : [paragraphValueProblem(entity.value, font), false]; if (problem) add("paragraph", "error", problem); + if (entity.columns !== undefined) { + // Columns many paragraphs share are checked once. + const given: unknown = entity.columns; + let shape: string | undefined; + if (typeof given === "object" && given !== null) { + if (columnShapes.has(given)) shape = columnShapes.get(given); + else columnShapes.set(given, (shape = paragraphColumnsShapeProblem(given))); + } else shape = paragraphColumnsShapeProblem(given); + const columns = shape ?? paragraphColumnsSizeProblem(given, entity.width, entity.height); + if (columns) add("paragraph", "error", columns); + } else if (columnBreak) add("paragraph", "warning", PARAGRAPH_COLUMN_BREAK); const { align, valign, lineSpacing, lineSpacingStyle } = entity; for (const [rule, field, value] of [ ["text-align", "align", align], diff --git a/src/paragraph-codes.ts b/src/paragraph-codes.ts index e7254cd..25f57fd 100644 --- a/src/paragraph-codes.ts +++ b/src/paragraph-codes.ts @@ -39,7 +39,6 @@ export const PARAGRAPH_NOT_LAID_OUT = { A: "sets where the characters after it sit up and down the line", C: "sets the color of the characters after it", c: "sets the true color of the characters after it", - N: "starts a new column", X: "starts the part of a dimension's text below its line", M: "holds a character of a code page", m: "holds a character of a code page", @@ -182,14 +181,15 @@ export type ParagraphPiece = readonly format: RunFormat; } /** A paragraph break, `\P`. */ - | { readonly kind: "break" }; + /** `\P`, or `\N`, which also starts the next column: `column` true. */ + | { readonly kind: "break"; readonly column?: boolean }; export interface ParsedParagraph { readonly pieces: readonly ParagraphPiece[]; /** * The first code or character of the value that tsdraft refuses to write, or undefined. The - * pieces are still read past it: a code it does not lay out draws nothing, and `\N` and `\X` - * break the line. + * pieces are still read past it: a code it does not lay out draws nothing, and `\X` breaks + * the line. */ readonly problem: string | undefined; /** @@ -197,6 +197,8 @@ export interface ParsedParagraph { * when that font is an SHX font. One in an SHX font a `\f` code set is a `problem`. */ readonly ownDiameter: boolean; + /** True when it holds a `\N`, which starts the next column. */ + readonly columnBreak: boolean; } const PLAIN: RunFormat = { @@ -288,6 +290,7 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap let run = ""; let diameter = false; let ownDiameter = false; + let columnBreak = false; const flush = (): void => { if (diameter) { if (format.font === undefined) ownDiameter = true; @@ -350,7 +353,7 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap } flush(); if (saved.length > 0 || deeper > 0) fail(PARAGRAPH_NEVER_CLOSED); - return { pieces, problem, ownDiameter }; + return { pieces, problem, ownDiameter, columnBreak }; /** Reads the code after a backslash at `at`, and gives where the value goes on after it. */ function code(at: number): number { @@ -373,6 +376,10 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap run += letter; return at + 1; case "N": + flush(); + columnBreak = true; + pieces.push({ kind: "break", column: true }); + return at + 1; case "X": fail(paragraphNotLaidOut(letter)); flush(); diff --git a/src/paragraphs.ts b/src/paragraphs.ts index 980b4f4..1707a3f 100644 --- a/src/paragraphs.ts +++ b/src/paragraphs.ts @@ -12,7 +12,7 @@ import { type ParsedParagraph, type RunFormat, } from "./paragraph-codes.ts"; -import { LINE_SPACING_RANGE } from "./rules.ts"; +import { LINE_SPACING_RANGE, PARAGRAPH_COLUMNS_MOST } from "./rules.ts"; import { fifteenDigits, written } from "./format.ts"; import { Strings } from "./shape.ts"; @@ -78,7 +78,8 @@ import { Strings } from "./shape.ts"; // Justified, each line but the paragraph's last grows each space after its last tab alike, to // end at the right indent; the last stands by the attachment. Distributed, every line grows // each gap after its last tab between two characters or stacks alike, and is centered without -// a width. A grown line draws each word and space, or each character, as a run of its own. +// a width. A grown line draws each word and space, or each character, as a run of its own. A +// line wider than its room is not grown, and a distributed one is then centered. // - `\pb` leaves room before each paragraph, the first among them, and no less than // `BEFORE_LEAST`, and `\pa` after each but the last. Once a code has `x`, the numbers of each // after it are heights too. `\psm` spaces each line `MULTIPLE` times its A and D, times its factor, and the box @@ -86,6 +87,14 @@ import { Strings } from "./shape.ts"; // size below its line's top and each next line 5/3 of it below, and the box ends 2/3 of it // below the last baseline, less 4/3 of what it passes the height by. // - A tab's underline runs from the pen to its stop. +// - Columns, each the width wide and the gutter apart: a line whose box reaches below its column's +// height, where at-least spacing ends it at its ink, starts the next, as does the first line +// after a `\N`. It starts the column as a first line does, with the room its paragraph leaves +// before it and none of what the one before leaves after. Static columns stop at their count, +// the last taking the rest, and stand as wide as all of them; one height each takes the heights +// in turn and then a column for the rest. In a column that takes the rest a `\N` only breaks the +// line. Each column is a box of its own, which the attachment places up and down. Without +// columns `\N` is `\P`. /** How far past the width a word may reach and stay: the tables' rounding, and no more. */ const SLACK = 1e-9; const UNDERLINE_SHX = 0.2; @@ -116,6 +125,10 @@ const TAB = 9; const NO_GAPS: readonly number[] = []; /** The least room a paragraph's `\pb` leaves before it, in heights. */ const BEFORE_LEAST = 1 / 4; +/** The gutter of columns given none, in heights, as the leading CAD app's. */ +const DEFAULT_GUTTER = 5; +/** How far, in heights, a line's baseline may pass its column's height and stay in it. */ +const COLUMN_SLACK = 1e-9; /** A paragraph to lay out. A `Paragraph` and its `TextStyle` spread into one object are one. */ export interface ParagraphToMeasure { @@ -143,6 +156,93 @@ export interface ParagraphToMeasure { readonly lineSpacing?: number; /** Defaults to `"at-least"`. */ readonly lineSpacingStyle?: LineSpacingStyle; + /** Columns its lines flow through, each `width` wide. Missing, one column. */ + readonly columns?: ParagraphColumns; +} + +/** + * Columns a paragraph's lines flow through, each as wide as its `width`, in drawing units. A line + * whose box reaches below its column's height starts the next column, as does the first after a + * `\N`. + * + * - `{ count, height }`: that many columns, each `height` high, and the last takes what the + * others leave, past its height. + * - `{ height }`: as many columns as the text takes, each `height` high. + * - `{ heights }`: a column of each height, in order, as many as the text takes. Past the last + * height, one more column takes the rest, as a height of 0 does. + * + * `gutter` is the room between two columns. It defaults to five times the paragraph's height. + */ +export type ParagraphColumns = + | { + readonly height: number; + readonly count?: number; + readonly heights?: never; + readonly gutter?: number; + } + | { + readonly heights: readonly number[]; + readonly height?: never; + readonly count?: never; + readonly gutter?: number; + }; + +/** A paragraph's columns as a file holds them, from the paragraph and its layout. */ +export interface ParagraphColumnsHeld { + /** 1 for static columns, a count given, and 2 for dynamic ones. */ + readonly type: 1 | 2; + /** How many: as given for static columns, and as many as the layout took for dynamic ones. */ + readonly count: number; + /** Each column's width, and the room between two. */ + readonly width: number; + readonly gutter: number; + /** Their height, or the first of `heights`. */ + readonly height: number; + /** True for dynamic columns all `height` high. */ + readonly auto: boolean; + /** + * For dynamic columns of a height each, the height of each of `count`: 0 for the one past the + * heights given, which takes the rest. Empty otherwise. + */ + readonly heights: readonly number[]; + /** The width of all of them and the gutters between them, and the height of the tallest. */ + readonly total: number; + readonly tallest: number; +} + +/** What a file holds of a paragraph's columns, or undefined for a paragraph without them. */ +export function paragraphColumnsHeld( + paragraph: ParagraphToMeasure, + layout: ParagraphLayout, +): ParagraphColumnsHeld | undefined { + // The numbers as the writers write them, and as the layout read them, so that what a file + // holds of them adds up. + const settings = settingsOf(paragraph); + const columns = settings.columns; + if (columns === undefined) return undefined; + const width = settings.width; + const gutter = columns.gutter; + const boxes = layout.columns; + const tallest = boxes.reduce((most, [, bottom, , top]) => Math.max(most, top - bottom), 0); + const fixed = columns.fixed === true; + const count = fixed ? columns.count : Math.max(boxes.length, 1); + const given = columns.heights; + return { + type: fixed ? 1 : 2, + count, + width, + gutter, + height: given[0] ?? 0, + auto: columns.repeat && !fixed, + heights: columns.repeat ? [] : Array.from({ length: count }, (_, k) => given[k] ?? 0), + total: written(count * width + (count - 1) * gutter), + tallest, + }; +} + +/** The gutter of a paragraph's columns: its own, or five times the paragraph's height. */ +export function paragraphGutter(columns: ParagraphColumns, height: number): number { + return columns.gutter ?? DEFAULT_GUTTER * height; } /** A run of characters a paragraph draws in one font and one format, as a text is drawn. */ @@ -192,6 +292,8 @@ export interface ParagraphLine { readonly end: number; /** How far above its baseline it reaches: its A, which sets where it sits under at-least spacing. */ readonly top: number; + /** The column it is in, from 0. */ + readonly column: number; } /** A paragraph before it is turned and moved to its point: X along its lines, Y up them, from `at`. */ @@ -204,6 +306,11 @@ export interface ParagraphLayout { * the width from the point `align` names, or as the widest line without one. */ readonly frame: readonly [number, number, number, number]; + /** + * Each column's box, `[left, bottom, right, top]`, which `align` and `valign` place on its own: + * one for a paragraph without columns, its frame, and as many as the text took for dynamic ones. + */ + readonly columns: readonly (readonly [number, number, number, number])[]; /** * The box of all it draws, its letters with what they reach below the baseline and their lean, * and its strokes: `[left, bottom, right, top]`. Undefined when it draws nothing. @@ -238,6 +345,8 @@ export interface ParagraphMeasure { readonly lines: readonly { readonly value: string; readonly corners: readonly [Point, Point, Point, Point]; + /** The column it is in, from 0. */ + readonly column: number; }[]; readonly approximate: boolean; } @@ -503,6 +612,8 @@ interface Line { readonly paragraph: number; /** True for the first line of its paragraph. */ readonly first: boolean; + /** True for the first line after a `\N`, which starts the next column. */ + readonly column: boolean; /** Where it starts, from the left of the box: its paragraph's indent, in drawing units. */ readonly origin: number; /** @@ -693,6 +804,8 @@ interface Settings { readonly font: string | undefined; readonly align: ParagraphAlign | undefined; readonly valign: ParagraphVerticalAlign | undefined; + /** Its columns, or undefined for one. */ + readonly columns: Columns | undefined; /** * True for the text of a dimension's picture, whose box ends below the last line's characters * and below where a stack sets its lowest part, and not at a stacked part's ink. @@ -700,8 +813,77 @@ interface Settings { readonly dimension?: boolean; } +/** A paragraph's columns, read: how many at most, the height of each, and the gutter. */ +interface Columns { + /** How many at most: the last takes what the others leave. */ + readonly count: number; + /** + * The height of the column of each index. Past them, the last again when `repeat`, or else one + * more column that takes the rest, as one of height 0 does. + */ + readonly heights: readonly number[]; + readonly repeat: boolean; + /** True for static columns, which stand as wide as all `count` of them, filled or not. */ + readonly fixed?: boolean; + readonly gutter: number; + /** What a layout's key holds of `heights`: them, or a name of a long list of them. */ + readonly key: string; +} + +/** A paragraph's columns as the layout reads them, or undefined for one column. */ +/** A paragraph's columns, or undefined where it has none, or none an object gives. */ +function columnsGiven(paragraph: ParagraphToMeasure): ParagraphColumns | undefined { + const c: unknown = paragraph.columns; + return typeof c === "object" && c !== null ? (c as ParagraphColumns) : undefined; +} + +/** Reads a list of heights as the layout takes them: by its items alone, up to the most. */ +function readHeights(given: readonly unknown[]): readonly number[] { + const n = Math.min(given.length, PARAGRAPH_COLUMNS_MOST); + const out: number[] = []; + for (let i = 0; i < n; i++) out.push(Math.max(written(finite(given[i], 0)), 0)); + return out; +} + +/** A short name for each long list of heights, by the list itself, for the keys of layouts. */ +const heightNames = new WeakMap(); +let heightsNamed = 0; + +function columnsOf( + paragraph: ParagraphToMeasure, + height: number, + read: (given: readonly unknown[]) => readonly number[] = readHeights, +): Columns | undefined { + const c = columnsGiven(paragraph); + if (c === undefined) return undefined; + const gutter = Math.max(written(finite(paragraphGutter(c, height), 0)), 0); + const given: unknown = c.heights; + if (Array.isArray(given)) { + const heights = read(given); + let key = heights.length <= 16 ? heights.join(",") : heightNames.get(given); + if (key === undefined) heightNames.set(given, (key = `#${heightsNamed++}`)); + return { count: PARAGRAPH_COLUMNS_MOST, heights, repeat: false, gutter, key }; + } + const count = Math.min( + Math.max(Math.floor(finite(c.count, PARAGRAPH_COLUMNS_MOST)), 1), + PARAGRAPH_COLUMNS_MOST, + ); + const tall = Math.max(written(finite(c.height, 0)), 0); + return { + count, + fixed: c.count !== undefined, + heights: [tall], + repeat: true, + gutter, + key: `${tall}`, + }; +} + /** A paragraph's settings, from its numbers as the writers write them, as a file holds them. */ -function settingsOf(paragraph: ParagraphToMeasure): Settings { +function settingsOf( + paragraph: ParagraphToMeasure, + read?: (given: readonly unknown[]) => readonly number[], +): Settings { const chosen = written(finite(paragraph.lineSpacing, 1)); const font = paragraph.font ?? STANDARD_FONT; const align = paragraph.align; @@ -716,6 +898,7 @@ function settingsOf(paragraph: ParagraphToMeasure): Settings { font: fontMetrics(font).known ? font : undefined, align: align === "center" || align === "right" ? align : undefined, valign: valign === "middle" || valign === "bottom" ? valign : undefined, + columns: columnsOf(paragraph, Math.max(written(finite(paragraph.height, 0)), 0), read), }; } @@ -776,6 +959,8 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let lines: Line[] = []; let paragraph = 0; + /** True after a `\N`, until the line it starts. */ + let nextColumn = false; /** A line of the paragraph `paragraph`. */ const newLine = (first: boolean): Line => { const p = properties[paragraph] ?? UNSET; @@ -784,9 +969,11 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { spaced: false, paragraph, first, + column: nextColumn, origin: originOf(p, first), at: undefined, }; + nextColumn = false; lines.push(made); return made; }; @@ -1088,6 +1275,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { if (piece.kind === "break") { endWord(); endLine(); + if (piece.column) nextColumn = true; paragraph++; limit = limitOf(properties[paragraph] ?? UNSET); restart(true); @@ -1231,6 +1419,13 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { // Down the box: each line's baseline from its top, by its paragraph's spacing, with the room // its paragraph leaves before it and the last one after it. const baselines: number[] = []; + /** + * Where each line's slot starts, before the room its paragraph leaves and after the room the one + * before leaves, and where its box ends. + */ + const tops: number[] = []; + const bottoms: number[] = []; + let columnCount = 1; let boxHeight: number; { let top = 0; @@ -1239,8 +1434,10 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const p = properties[m.built.paragraph] ?? UNSET; if (m.built.first) { const before = k > 0 ? (properties[m.built.paragraph - 1] ?? UNSET).after : 0; + // A column's first line leaves out the room the paragraph before it leaves after it. + tops.push(top - before); top -= (p.before > 0 ? Math.max(p.before, BEFORE_LEAST * height) : p.before) + before; - } + } else tops.push(top); const spacing = p.spacing; let baseline: number; let slot: number; @@ -1266,15 +1463,51 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { bottom = baseline + m.down; } baselines.push(baseline); + bottoms.push(bottom); top -= slot; }); boxHeight = -bottom; } + // Across the columns: a line whose box reaches below its column's height starts the next, as + // does the first after a `\N`, its top at the column's top. Each column is a box of its own, + // which the attachment places. + const columnOf: number[] = []; + const columnHeights: number[] = []; + const columns = settings.columns; + if (columns) { + let column = 0; + let shift = 0; + let first = 0; + const heightOf = (k: number): number => { + const tall = columns.heights[columns.repeat ? Math.min(k, columns.heights.length - 1) : k]; + return tall === undefined || tall <= 0 ? Infinity : tall; + }; + for (let k = 0; k < baselines.length; k++) { + // The last static column and the one past the heights given take the rest. + const more = column + 1 < columns.count && Number.isFinite(heightOf(column)); + const below = -(bottoms[k]! + shift) > heightOf(column) + COLUMN_SLACK * height; + if (k > first && more && (measured[k]!.built.column || below)) { + column++; + first = k; + shift = -tops[k]!; + } + baselines[k]! += shift; + columnHeights[column] = -(bottoms[k]! + shift); + columnOf.push(column); + } + boxHeight = Math.max(...columnHeights); + // Static columns stand as wide as all of them, filled or not. + columnCount = columns.fixed ? columns.count : column + 1; + } const { align, valign } = settings; - const boxTop = valign === "middle" ? boxHeight / 2 : valign === "bottom" ? boxHeight : 0; + const topOf = (tall: number): number => + valign === "middle" ? tall / 2 : valign === "bottom" ? tall : 0; + const boxTop = topOf(boxHeight); /** Where the left of the box stands from the point, and where its lines may reach. */ + /** The width of the box: of all its columns and the gutters between them. */ + const boxWidth = given + (columns ? (columnCount - 1) * (given + columns.gutter) : 0); const boxLeft = - given > 0 ? (align === "center" ? -given / 2 : align === "right" ? -given : 0) : 0; + given > 0 ? (align === "center" ? -boxWidth / 2 : align === "right" ? -boxWidth : 0) : 0; const ink: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]; const include = (x: number, y: number): void => { @@ -1368,7 +1601,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const m = measured[k]!; const built = m.built; const p = properties[built.paragraph] ?? UNSET; - baseline = boxTop + baselines[k]!; + baseline = (columns ? topOf(columnHeights[columnOf[k]!]!) : boxTop) + baselines[k]!; const lastOfParagraph = lines[k + 1]?.paragraph !== built.paragraph; const justification = p.justification === "justified" && lastOfParagraph ? undefined : p.justification; @@ -1388,14 +1621,15 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let after = -1; let across = 0; if (!m.empty && given > 0 && (style === "justified" || style === "distributed")) { - gaps = gapsOf(built, style === "distributed", along); + // A line wider than its room is not squeezed: it stands as one with no gaps would. + gaps = to < inkTo ? NO_GAPS : gapsOf(built, style === "distributed", along); after = lastTabOf(built); if (gaps.length > 0) stretch = (to - inkTo) / gaps.length; } if (style === "center" || (style === "distributed" && gaps.length === 0)) { across = (from + to) / 2 - (inkFrom + inkTo) / 2; } else if (style === "right") across = to - inkTo; - const offset = boxLeft + at + across; + const offset = boxLeft + at + across + (columns ? columnOf[k]! * (given + columns.gutter) : 0); runs = []; value = ""; values = undefined; @@ -1475,15 +1709,27 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { start: m.empty ? 0 : m.start + offset, end: m.empty ? 0 : m.end + offset + grown, top: m.top, + column: columns ? columnOf[k]! : 0, }); } - const frameWidth = given > 0 ? given : widest; + const frameWidth = given > 0 ? boxWidth : widest; const left = align === "center" ? -frameWidth / 2 : align === "right" ? -frameWidth : 0; + const frame = [left, boxTop - boxHeight, left + frameWidth, boxTop] as const; + const boxes: (readonly [number, number, number, number])[] = []; + if (columns) { + for (let k = 0; k < columnCount; k++) { + const tall = columnHeights[k] ?? 0; + const top = topOf(tall); + const x = left + k * (given + columns.gutter); + boxes.push([x, top - tall, x + given, top]); + } + } else boxes.push(frame); return { lines: laid, strokes, - frame: [left, boxTop - boxHeight, left + frameWidth, boxTop], + frame, + columns: boxes, ink: ink[0] === Infinity ? undefined : ink, lean, widthFactor, @@ -1542,7 +1788,7 @@ function corners( export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout): ParagraphMeasure { const place = placer(paragraph); const box = (b: readonly [number, number, number, number]) => corners(place, b); - const lines: { value: string; corners: [Point, Point, Point, Point] }[] = []; + const lines: { value: string; corners: [Point, Point, Point, Point]; column: number }[] = []; for (const line of layout.lines) { if (line.runs.length === 0) continue; const lean = layout.lean * line.top; @@ -1554,6 +1800,7 @@ export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout) place(line.end + lean, line.baseline + line.top), place(line.start + lean, line.baseline + line.top), ], + column: line.column, }); } return { @@ -1640,7 +1887,10 @@ export interface ParagraphMeasurer { /** A key of a paragraph's settings. */ function keyOf(settings: Settings): string { - return JSON.stringify(settings); + // A long list of heights is keyed by its name, so that no key grows with it. + return JSON.stringify(settings, (field, value: unknown) => + field === "heights" ? undefined : value, + ); } /** @@ -1656,6 +1906,14 @@ export function paragraphMeasurer(): ParagraphMeasurer { last: { readonly key: string; readonly layout: ParagraphLayout } | undefined; } const kept = new Strings(); + /** Each list of heights, read once however many paragraphs share it. */ + const heights = new WeakMap(); + const read = (given: readonly unknown[]): readonly number[] => { + let found = heights.get(given); + if (!found) heights.set(given, (found = readHeights(given))); + return found; + }; + const settingsIn = (paragraph: ParagraphToMeasure): Settings => settingsOf(paragraph, read); const long = (value: unknown): value is string => typeof value === "string" && value.length >= LONG; /** What laying a long value out again costs, unless `has` finds what it keeps. */ @@ -1664,7 +1922,7 @@ export function paragraphMeasurer(): ParagraphMeasurer { if (!long(value)) return 0; const found = kept.get(value); const again = - kept.clashes(value) || (found !== undefined && !has(found, keyOf(settingsOf(paragraph)))); + kept.clashes(value) || (found !== undefined && !has(found, keyOf(settingsIn(paragraph)))); return again ? value.length : 0; }; const entry = (value: string): Kept => { @@ -1674,8 +1932,8 @@ export function paragraphMeasurer(): ParagraphMeasurer { }; const layout = (paragraph: ParagraphToMeasure): ParagraphLayout => { const value = paragraph.value; - if (!long(value)) return layoutParagraph(paragraph); - const settings = settingsOf(paragraph); + const settings = settingsIn(paragraph); + if (!long(value)) return layOut(settings, parseParagraph(value)); const key = keyOf(settings); const found = entry(value); if (found.last?.key !== key) { @@ -1686,9 +1944,9 @@ export function paragraphMeasurer(): ParagraphMeasurer { const box = (paragraph: ParagraphToMeasure): ParagraphMeasure["corners"] => { const value = paragraph.value; let ink: Ink; - if (!long(value)) ink = layoutParagraph(paragraph).ink; + const settings = settingsIn(paragraph); + if (!long(value)) ink = layOut(settings, parseParagraph(value)).ink; else { - const settings = settingsOf(paragraph); const key = keyOf(settings); const found = entry(value); found.boxes ??= new Map(); @@ -1719,6 +1977,7 @@ const OWN = [ "valign", "lineSpacing", "lineSpacingStyle", + "columns", ] as const; /** diff --git a/src/read/check.ts b/src/read/check.ts index c6755d4..8215de6 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -15,7 +15,9 @@ type Type = | { readonly fields: Fields } | { readonly list: Type } | { readonly map: Type } - | { readonly oneOf: readonly string[] }; + | { readonly oneOf: readonly string[] } + /** The fields of one of these, named in a message as `named`. */ + | { readonly either: readonly Fields[]; readonly named: string }; /** Each field and its type. A field whose name ends in `?` may be left out. */ type Fields = Readonly>; @@ -152,6 +154,13 @@ const ENTITY: Readonly> = { value: "string", lineSpacing: "number", lineSpacingStyle: { oneOf: ["at-least", "exactly"] }, + "columns?": { + either: [ + { height: "number", "count?": "count", "gutter?": "number" }, + { heights: { list: "number" }, "gutter?": "number" }, + ], + named: "{ height, count?, gutter? } or { heights, gutter? }", + }, }, dimension: { ...BASE, @@ -525,6 +534,15 @@ export function checkDrawingRead(value: unknown): string[] { if (problems.length >= MAX_PROBLEMS) return; check(v[key], type.map, `${at}[${JSON.stringify(key).slice(0, 80)}]`); } + } else if ("either" in type) { + // The first of them it holds to, with what that one finds wrong taken back from the others. + const before = problems.length; + for (const fields of type.either) { + checkFields(v, fields, at); + if (problems.length === before) return; + problems.length = before; + } + say(at, `must be ${type.named}`); } else checkFields(v, type.fields, at); }; diff --git a/src/read/entities.ts b/src/read/entities.ts index a7640ad..2e1c084 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -1,5 +1,6 @@ // What a DXF record of an entity reads as: the kinds of `ReadEntity`, each in the world's // coordinates with the pen it sets for itself. +import type { ParagraphColumns } from "../paragraphs.ts"; import type { Point } from "../drawing.ts"; import { textOnce, textTwice } from "./groups.ts"; import { wholeImageClip } from "../images.ts"; @@ -396,7 +397,65 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { lineSpacing: num(r, 44) ?? 1, lineSpacingStyle: num(r, 73) === 2 ? "exactly" : "at-least", }; - return { entity }; + // The embedded object's direction wins over the MTEXT's own, as the leading CAD app reads it. + const embedded = embeddedDirection(record); + const turned = embedded === undefined ? entity : { ...entity, rotation: embedded }; + const held = columnsOf(record); + if (held) return { entity: { ...turned, width: held.width, columns: held.columns } }; + return { entity: turned }; +} + +/** The direction in an `MTEXT`'s embedded object, in degrees, or undefined where it has none. */ +function embeddedDirection(record: Rec): number | undefined { + const from = record.codes.indexOf(101); + if (from < 0) return undefined; + const after: Rec = { + type: record.type, + codes: record.codes.slice(from + 1), + values: record.values.slice(from + 1), + }; + const dx = num(after, 10); + const dy = num(after, 20); + if (dx === undefined || dy === undefined || (dx === 0 && dy === 0)) return undefined; + if (!Number.isFinite(dx) || !Number.isFinite(dy)) return undefined; + return degrees((Math.atan2(dy, dx) * 180) / Math.PI); +} + +/** + * An `MTEXT`'s columns, from its embedded object, with the width of each, or undefined when it + * has none: static ones, type 1, by their count; dynamic ones, type 2, by their height, or one + * by one by the heights after group 74 up to the first of 0, which takes the rest. + */ +function columnsOf(record: Rec): { width: number; columns: ParagraphColumns } | undefined { + const from = record.codes.indexOf(101); + if (from < 0) return undefined; + const after: Rec = { + type: record.type, + codes: record.codes.slice(from + 1), + values: record.values.slice(from + 1), + }; + const type = num(after, 71); + const width = num(after, 44); + const height = num(after, 41); + const gutter = num(after, 45) ?? 0; + const good = (n: number | undefined): n is number => n !== undefined && Number.isFinite(n); + if ((type !== 1 && type !== 2) || !good(width) || width <= 0 || !good(height) || gutter < 0) { + return undefined; + } + if (type === 1) { + const count = num(after, 72); + if (!good(count) || count < 1) return undefined; + return { width, columns: { count: Math.floor(count), height, gutter } }; + } + if (num(after, 73) !== 0) return { width, columns: { height, gutter } }; + const heights: number[] = []; + for (let i = 0; i < after.codes.length; i++) { + if (after.codes[i] !== 46) continue; + const tall = Number(after.values[i]); + if (!(tall > 0)) break; + heights.push(tall); + } + return heights.length > 0 ? { width, columns: { heights, gutter } } : undefined; } function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Reading { @@ -596,7 +655,7 @@ export function costOf(e: ReadEntity): number { case "text": return own + placementCost(e) + chars(e.value); case "mtext": - return own + 1 + chars(e.value) + chars(e.style); + return own + 1 + chars(e.value) + chars(e.style) + (e.columns?.heights?.length ?? 0); case "dimension": return own + 4 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "radial-dimension": diff --git a/src/read/model.ts b/src/read/model.ts index e86471a..b388011 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -2,6 +2,7 @@ // drawing file states about its tables, its blocks, its xrefs and its layouts, a census of what // each space draws and, for a read that asks for it, what each space draws, and is never // written back. +import type { ParagraphColumns } from "../paragraphs.ts"; import type { Point } from "../drawing.ts"; /** The format of a `DrawingRead`. A reader gives the format it was built for. */ @@ -351,6 +352,11 @@ export interface ReadMtext extends ReadEntityBase { readonly lineSpacing: number; /** How its line spacing is taken: as the least, or exactly. */ readonly lineSpacingStyle: "at-least" | "exactly"; + /** + * Its columns, each `width` wide, as a paragraph's: a count for static ones, none for dynamic + * ones, and heights for dynamic ones of a height each, up to the first of 0. + */ + readonly columns?: ParagraphColumns; } /** diff --git a/src/read/mtext.ts b/src/read/mtext.ts index cf4554c..aa608d8 100644 --- a/src/read/mtext.ts +++ b/src/read/mtext.ts @@ -35,6 +35,7 @@ export function mtextToMeasure( valign: place?.valign ?? "top", lineSpacing: mtext.lineSpacing, lineSpacingStyle: mtext.lineSpacingStyle, + ...(mtext.columns && { columns: mtext.columns }), }; return { paragraph, exact: font.exact && place !== undefined }; } diff --git a/src/rules.ts b/src/rules.ts index 61626fb..2b20aee 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -1015,7 +1015,7 @@ type ParagraphClose = S extends `${infer A}}${infer R}` type ParagraphPercent = S extends `${string}%${infer R}` ? ["%", R] : undefined; /** The codes of a paragraph that draw a character, and need nothing after them. */ -type ParagraphPlainCode = "P" | "~" | "\\" | "{" | "}" | "o"; +type ParagraphPlainCode = "P" | "N" | "~" | "\\" | "{" | "}" | "o"; /** The codes tsdraft does not lay out that end with a `;`. */ type ParagraphEndedCode = "H" | "W" | "Q" | "T" | "A" | "C" | "c"; @@ -1151,7 +1151,7 @@ type ParagraphCode< ? After extends `${string};${string}` ? ReturnType> : ReturnType> - : C extends "N" | "X" | "O" + : C extends "X" | "O" ? ReturnType> : C extends "U" | "u" ? After extends `+${infer H1}${infer H2}${infer H3}${infer H4}${infer Next}` @@ -1793,6 +1793,107 @@ export function lineSpacingProblem(value: unknown): string | undefined { : LINE_SPACING; } +/** The most columns a paragraph has, and the most heights it gives one by one. */ +export const PARAGRAPH_COLUMNS_MOST = 1000; + +/** The message for a paragraph's columns that are not as `ParagraphColumns` gives them. */ +export const PARAGRAPH_COLUMNS = + "A paragraph's columns are { height, count?, gutter? } or { heights, gutter? }, in drawing units: a height above 0 as written, a whole count from 1 to 1000, from 1 to 1000 heights above 0 as written, and a gutter of 0 or more"; + +/** The message for columns wider than a file holds. */ +export const PARAGRAPH_COLUMNS_WIDE = + "A paragraph's columns, their widths and gutters, are too wide to write: as many as the count gives, or 1000 of them without one"; + +/** The message for columns on a paragraph with no width. */ +export const PARAGRAPH_COLUMNS_WIDTH = + "A paragraph with columns needs a width, which each of its columns is as wide as"; + +/** The warning for a `\N` in a paragraph with no columns. */ +export const PARAGRAPH_COLUMN_BREAK = + "The paragraph code \\N starts the next column, and this paragraph has no columns: it breaks the line, as \\P does"; + +/** A number above 0 as the writers write it, and not too large to write. */ +const writtenPositive = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value) && written(value) > 0 && !isTooLarge(value); + +const COLUMN_FIELDS = new Set(["height", "heights", "count", "gutter"]); + +/** + * Returns what is wrong with a paragraph's columns apart from its width, or undefined. It reads a + * list of heights by its items alone, and stops at the first field it does not know. + */ +export function paragraphColumnsShapeProblem(columns: unknown): string | undefined { + if (typeof columns !== "object" || columns === null || Array.isArray(columns)) { + return PARAGRAPH_COLUMNS; + } + for (const key in columns) if (!COLUMN_FIELDS.has(key)) return PARAGRAPH_COLUMNS; + const { height, heights, count, gutter } = columns as Record; + if ( + gutter !== undefined && + !( + typeof gutter === "number" && + Number.isFinite(gutter) && + written(gutter) >= 0 && + !isTooLarge(gutter) + ) + ) { + return PARAGRAPH_COLUMNS; + } + if (heights !== undefined) { + if (height !== undefined || count !== undefined || !Array.isArray(heights)) { + return PARAGRAPH_COLUMNS; + } + const list = heights as readonly unknown[]; + if (list.length < 1 || list.length > PARAGRAPH_COLUMNS_MOST) return PARAGRAPH_COLUMNS; + for (let i = 0; i < list.length; i++) if (!writtenPositive(list[i])) return PARAGRAPH_COLUMNS; + return undefined; + } + if (!writtenPositive(height)) return PARAGRAPH_COLUMNS; + if ( + count !== undefined && + !( + Number.isInteger(count) && + (count as number) >= 1 && + (count as number) <= PARAGRAPH_COLUMNS_MOST + ) + ) { + return PARAGRAPH_COLUMNS; + } + return undefined; +} + +/** + * Returns what is wrong with a paragraph's columns beside its width, or undefined: their shape, + * no width, and columns too wide to write, as many as static ones give or as dynamic ones may + * take, at the gutter given or the one of `height`. + */ +export function paragraphColumnsProblem( + columns: unknown, + width: unknown, + height: unknown = 0, +): string | undefined { + return ( + paragraphColumnsShapeProblem(columns) ?? paragraphColumnsSizeProblem(columns, width, height) + ); +} + +/** What is wrong with columns of a sound shape beside the paragraph's width, or undefined. */ +export function paragraphColumnsSizeProblem( + columns: unknown, + width: unknown, + height: unknown, +): string | undefined { + if (!positiveNumber(width)) return PARAGRAPH_COLUMNS_WIDTH; + const c = columns as { readonly count?: number; readonly gutter?: number }; + const gutter = + c.gutter ?? 5 * (typeof height === "number" && Number.isFinite(height) ? height : 0); + const count = c.count ?? PARAGRAPH_COLUMNS_MOST; + return isTooLarge(count * ((width as number) + gutter)) ? PARAGRAPH_COLUMNS_WIDE : undefined; +} + +const positiveNumber = (value: unknown): boolean => + typeof value === "number" && Number.isFinite(value) && value > 0; + /** * Returns what is wrong with a paragraph's value in its style's font, or undefined: a code * tsdraft does not know or does not lay out, a brace that is never closed or never opened, a code diff --git a/src/shape.ts b/src/shape.ts index c0f47ab..fb60aaf 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -307,6 +307,14 @@ export interface Shapes { readonly entity: Check; } +/** A paragraph's columns, every field of each kind at once, as their shape is checked. */ +interface ColumnsShape { + readonly height?: number; + readonly heights?: readonly number[]; + readonly count?: number; + readonly gutter?: number; +} + /** * The checks of each object in a drawing, with one message for a problem whichever is asked. * @@ -483,6 +491,14 @@ function shapes(all: boolean, typed = all): Shapes { width: number, lineSpacing: number, lineSpacingStyle: ruled(string), + columns: ruled( + record( + fields( + {}, + { height: number, heights: list(number), count: number, gutter: number }, + ), + ), + ), }, ), insert: fields( diff --git a/test/bounded.test.ts b/test/bounded.test.ts index c145efd..8481ecb 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2367,6 +2367,22 @@ test("a paragraph of many lines, runs or braces, a long word and numbers past dr paragraph({ value: `\\pxi1,l2,r3;${"W ".repeat(200_000)}`, width: 6 }), paragraph({ value: "\\pl99999999999999999999,r-1e9;A".repeat(1_000), width: 1 }), paragraph({ value: "\\pxsm4,se0.0001,b1000,a-1000;A\\P".repeat(50_000), width: 1 }), + // Columns: a line each, a break each, heights past the most, and numbers past drawing. + paragraph({ value: "A\\P".repeat(100_000), width: 1, columns: { height: 1e-9 } }), + paragraph({ value: "A\\N".repeat(100_000), width: 1, columns: { count: 1e9, height: 1 } }), + paragraph({ + value: "WORD ".repeat(100_000), + width: 1, + columns: { heights: Array.from({ length: 5_000 }, () => 1e-3), gutter: 1e300 }, + }), + paragraph({ value: "A B ".repeat(50_000), width: 1e99, columns: { height: 1e99, gutter: -1 } }), + paragraph({ value: "A B ".repeat(50_000), width: 1, columns: null }), + // Heights many paragraphs share, under a value long enough to be kept. + paragraph({ + value: "X".repeat(256), + width: 2, + columns: { heights: Array.from({ length: 1_000 }, () => 1.2345678901234567e70) }, + }), ]; for (const [i, leaf] of hostile.entries()) { const d: Drawing = { diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index d031e7a..8aceda5 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -22,11 +22,15 @@ import { svgToPDF, toDXF, toSVG, + checkDrawingRead, + paragraphColumnsHeld, underline, type Drawing, type Entity, type Paragraph, + type ParagraphLayout, } from "../src/index.ts"; +import { paragraphMeasurer } from "../src/paragraphs.ts"; import { readProblems } from "./read-agreement.ts"; import { timeLimit } from "./time-limit.ts"; @@ -101,7 +105,6 @@ test("what tsdraft does not lay out is refused, and named", () => { ["\\ptr3;A", /aligns text by its right/], ["\\psa1.2;A", /at least a size apart/], ["\\pi-;A", /option "i-"/], - ["A\\NB", /code \\N, which starts a new column/], ["A\\XB", /code \\X/], ["\\OA", /code \\O, which draws a line over/], ["\\M+18140", /code \\M, which holds a character of a code page/], @@ -360,6 +363,81 @@ test("a list hangs its items under their marks, and its tabs and indents fall wh assert.ok(svgToPDF([picture]).length > 0); }); +test("columns take a paragraph's lines in turn, where the leading CAD app sets them", () => { + const arial = { font: "Arial", height: 0.2, width: 2 } as const; + const twelve = Array.from({ length: 12 }, (_, k) => `L${k + 1} HHHH`).join("\\P"); + const ten = Array.from({ length: 10 }, (_, k) => `L${k + 1} HHHH`).join("\\P"); + const lay = (value: string, more: object) => layoutParagraph({ value, ...arial, ...more }); + const columnsOf = (layout: ParagraphLayout) => + layout.lines.map((line) => `${line.column}:${line.value.split(" ")[0]}`).join(" "); + const first = (layout: ParagraphLayout, value: string) => + layout.lines.flatMap((line) => line.runs).find((run) => run.value === value)!; + const near = (got: number, want: number) => + assert.ok(Math.abs(got - want) < 2e-4, `${got} ${want}`); + // A line whose box reaches below the column's height starts the next, the gutter past it; the + // last static column takes what is left. + const two = lay(twelve, { columns: { count: 2, height: 1, gutter: 0.5 } }); + assert.match(columnsOf(two), /^0:L1 0:L2 0:L3 1:L4 .* 1:L12$/); + near(first(two, "L1 HHHH").x, -0.0205); + near(first(two, "L4 HHHH").x, 2.4795); + near(first(two, "L4 HHHH").baseline, -0.2); + assert.equal(two.columns.length, 2); + // Without a count, as many as it takes; with heights, one each, then one for the rest. + assert.equal(lay(twelve, { columns: { height: 1, gutter: 0.5 } }).columns.length, 4); + assert.equal( + columnsOf(lay(ten, { columns: { heights: [0.6, 1.2], gutter: 0.5 } })), + "0:L1 0:L2 1:L3 1:L4 1:L5 2:L6 2:L7 2:L8 2:L9 2:L10", + ); + // `\N` starts the next column; exact spacing ends a line's box a third of a height down. + assert.equal( + columnsOf(lay("L1 HHHH\\NL2 HHHH", { columns: { count: 2, height: 2 } })), + "0:L1 1:L2", + ); + assert.equal( + columnsOf(lay(ten, { lineSpacingStyle: "exactly", columns: { count: 2, height: 0.58 } })), + "0:L1 1:L2 1:L3 1:L4 1:L5 1:L6 1:L7 1:L8 1:L9 1:L10", + ); + // Each column is a box the attachment places on its own; static ones stand as wide as all. + const bottom = lay(twelve, { valign: "bottom", columns: { count: 2, height: 1.2, gutter: 0.5 } }); + near(first(bottom, "L3 HHHH").baseline, 0.0035); + near(first(bottom, "L12 HHHH").baseline, 0.0001); + const right = lay("L1 HHHH\\PL2 HHHH", { + align: "right", + columns: { count: 3, height: 1, gutter: 0.5 }, + }); + near(first(right, "L1 HHHH").x, -6.173); + assert.deepEqual([right.frame[0], right.frame[2]], [-7, 0]); + // Past the heights given one column takes the rest, a \\N there too. + assert.equal(columnsOf(lay("A\\NB\\NC", { columns: { heights: [1] } })), "0:A 1:B 1:C"); + // What a file holds adds up as written. + const held = { + value: "A", + height: 0.2, + width: 1.2345674, + columns: { count: 3, height: 1, gutter: 0.2345674 }, + }; + const kept = paragraphColumnsHeld(held, layoutParagraph(held))!; + assert.deepEqual([kept.width, kept.gutter, kept.total], [1.234567, 0.234567, 4.172835]); + // One measurer keeps a long value's layout for each height of its columns. + const notes = `${"VERIFY ALL DIMENSIONS IN FIELD\\P".repeat(10)}END`; + const measurer = paragraphMeasurer(); + const counts = [0.2, 10].map( + (height) => + measurer.layout({ value: notes, ...arial, height: 0.125, width: 8, columns: { height } }) + .columns.length, + ); + assert.deepEqual(counts, [11, 1]); + // Columns that are not an object, as data may hold them, are none. + assert.equal(lay(twelve, { columns: null }).columns.length, 1); + // A distributed line wider than its room is left whole, and centered. + const wide = lay("\\pxqd;CONSTRUCTION.", {}); + assert.deepEqual( + wide.lines[0]!.runs.map((run) => run.value), + ["CONSTRUCTION."], + ); + near(wide.lines[0]!.runs[0]!.x, -0.1589); +}); + test("what the tables cannot lay out exactly is approximate, or refused", () => { const approximate = (value: string, font: string, obliqueAngle = 0) => layoutParagraph({ value, height: 1, font, obliqueAngle }).approximate; @@ -421,6 +499,16 @@ test("lint refuses a paragraph built as data that the leading CAD app would not // code sets. [{ value: "%%c6" }, /^paragraph: .*%%c in an SHX font/], [{ value: "\\fArial;\\fromans.shx;%%c6" }, /^paragraph: .*%%c in an SHX font/], + [{ columns: { height: 1 } }, /^paragraph: .*needs a width/], + [{ width: 2, columns: { count: 0, height: 1 } }, /^paragraph: .*a whole count from 1 to 1000/], + [{ width: 2, columns: { height: 1, heights: [1] } }, /^paragraph: .*\{ heights, gutter\? \}/], + [{ width: 2, columns: { heights: [] } }, /^paragraph: .*from 1 to 1000 heights/], + [{ width: 2, columns: { height: 1, gutter: -1 } }, /^paragraph: .*a gutter of 0 or more/], + [{ width: 2, columns: { heights: [4e-7, 2] } }, /^paragraph: .*heights above 0 as written/], + [ + { width: 2, columns: { height: 1, count: 1000, gutter: 1e98 } }, + /^paragraph: .*too wide to write/, + ], ]; for (const [fields, problem] of refused) { const found = errors(holding(fields)); @@ -433,6 +521,20 @@ test("lint refuses a paragraph built as data that the leading CAD app would not const arial = { textStyles: [{ name: "NOTES", font: "Arial" }] }; assert.deepEqual(errors({ ...holding({ value: "%%c6", style: "NOTES" }), ...arial }), []); assert.deepEqual(errors(holding({ value: "\\fArial;%%c6" })), []); + // A \N without columns only breaks the line, which lint warns of. + const warnings = (drawing: Drawing) => + lint(drawing) + .filter((d) => d.severity === "warning") + .map((d) => d.message); + assert.deepEqual(warnings(holding({ value: "A\\NB" })), [ + "paragraph #0: The paragraph code \\N starts the next column, and this paragraph has no columns: it breaks the line, as \\P does", + ]); + assert.deepEqual(warnings(holding({ value: "A\\NB", width: 2, columns: { height: 1 } })), []); + // A list of heights is read by its items, whatever its methods. + const odd = Object.assign([1, 2], { [Symbol.iterator]: 0, slice: 0, map: 0 }); + const shadowed = holding({ value: "A\\NB", width: 2, columns: { heights: odd } }); + assert.deepEqual(errors(shadowed), []); + assert.doesNotThrow(() => toSVG(shadowed)); }); test("readDXF gives back each paragraph as toDXF wrote it, in model space, a block and a layout", async () => { @@ -461,14 +563,44 @@ test("readDXF gives back each paragraph as toDXF wrote it, in model space, a blo d.paragraph(long, { at: [1, 20], width: 6, height: 0.125 }), ); d.paragraph(list(["ONE\tTWO", "THREE"]), { at: [0, -6], width: 4 }); + // Columns of each kind, held in an embedded object after the MTEXT's own groups. + d.paragraph(long, { at: [10, 0], width: 2, columns: { count: 2, height: 1, gutter: 0.25 } }); + d.paragraph(long, { at: [20, 0], width: 2, rotation: 30, columns: { height: 1 } }); + d.paragraph(`${long}\\N${long}`, { at: [30, 0], width: 2, columns: { heights: [1, 2] } }); + // A file holds the heights of the columns the text reaches. + d.paragraph("A", { at: [40, 0], width: 2, columns: { heights: [1, 2, 3] } }); const drawing = d.build(); const dxf = toDXF(drawing); assert.ok(dxf.includes("1.^IONE^ITWO"), "a tab is written as ^I"); const read = await readDXF(dxf, { geometry: true }); assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); const mtexts = read.model.entities!.filter((e) => e.kind === "mtext"); - assert.equal(mtexts.length, 3); + assert.equal(mtexts.length, 7); assert.equal(mtexts[1]!.kind === "mtext" && mtexts[1]!.value, long); + // The embedded object's direction wins over group 50. + const turned = await readDXF( + dxf.replace(/\r\n11\r\n0\.866025403784439\r\n21\r\n0\.5\r\n31\r\n0\r\n/, "\r\n50\r\n90\r\n"), + { geometry: true }, + ); + const thirty = turned.model.entities!.filter((e) => e.kind === "mtext")[4]!; + assert.equal(thirty.kind === "mtext" && thirty.rotation, 30); + const both = structuredClone(read) as unknown as { + model: { entities: Record[] }; + }; + both.model.entities.find((e) => e.columns !== undefined)!.columns = { height: 1, heights: [2] }; + assert.match( + checkDrawingRead(both).join("; "), + /columns must be \{ height, count\?, gutter\? \}/, + ); + assert.deepEqual( + mtexts.slice(3).map((e) => e.kind === "mtext" && [e.width, e.columns]), + [ + [2, { count: 2, height: 1, gutter: 0.25 }], + [2, { height: 1, gutter: 0.625 }], + [2, { heights: [1, 2], gutter: 0.625 }], + [2, { heights: [1], gutter: 0.625 }], + ], + ); }); test("a paragraph is laid out from its numbers as written, as a read of the file lays it out", async () => { diff --git a/test/rules.test.ts b/test/rules.test.ts index bb33c40..c153c31 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -1287,8 +1287,18 @@ test("a paragraph's height, width, line spacing and codes are checked twice", () assert.throws(() => d.paragraph("\\psa1;NOTE", { at }), /at least a size apart/); // @ts-expect-error: an option \p does not know. assert.throws(() => d.paragraph("\\pz3;NOTE", { at }), /option "z3"/); - // @ts-expect-error: nor are columns. - assert.throws(() => d.paragraph("ONE\\NTWO", { at }), /code \\N, which starts a new column/); + d.paragraph("ONE\\NTWO", { at, width: 2, columns: { count: 2, height: 1 } }); + assert.throws( + // @ts-expect-error: a height and heights both. + () => d.paragraph("ONE", { at, width: 2, columns: { height: 1, heights: [1] } }), + /\{ heights, gutter\? \}/, + ); + assert.throws( + // @ts-expect-error: a count with heights. + () => d.paragraph("ONE", { at, width: 2, columns: { heights: [1], count: 2 } }), + /\{ heights, gutter\? \}/, + ); + assert.throws(() => d.paragraph("ONE", { at, columns: { height: 1 } }), /needs a width/); // @ts-expect-error: a code tsdraft does not know. assert.throws(() => d.paragraph("\\ZNOTE", { at }), /code \\Z is not one tsdraft knows/); // @ts-expect-error: a font with no ; to end it. diff --git a/test/shape.test.ts b/test/shape.test.ts index 9818b03..c048bb6 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -95,6 +95,7 @@ const kinds: { valign: "bottom", lineSpacing: 1.5, lineSpacingStyle: "exactly", + columns: { height: 4, count: 2, gutter: 0.5 }, id: "k", ...styled, }, From 58d6fb703c67a602ee62e05df39a5f799e6f62bb Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 00:44:57 -0500 Subject: [PATCH 10/35] Leaders whole: every attachment, notes that wrap, frames and masks, two roots, curved shafts and a block as the note Leaders now draw everything CAD programs' multileaders hold, laid out where CAD programs put it. - A note is laid out as paragraph text is, each line set by the ink of its letters, so its lines move where they plot by up to a quarter of their height from earlier versions. - `attachment` takes every place CAD programs attach a landing, `LEADER_ATTACHMENTS`: `"top-of-first"`, `"first-line"`, `"middle"`, `"last-line"`, `"bottom-of-last"`, `"underline-last"`, `"underline-first"`, `"bottom-of-first"` and `"underline-all"`. `"first-line"` and `"last-line"` notes sit a little higher than before, as CAD programs measure a line. - A leader style's `direction: "vertical"` puts the note above or below its point; `side` takes `"above"` and `"below"`, and `verticalAttachment` is `"center"` or `"line"`. - A leader's `width` wraps its note; `frame` on a style or a leader draws a frame one gap outside the note; and a leader's `mask` hides what is drawn before it behind its note, `true` for the drawing's background or `{ color, offsetFactor }`. - `toFarSide` gives the shafts of a second root on the note's far side, `shaft: "curved"` draws each shaft as the cubic CAD programs draw, and `d.leader({ block, attributes }, options)` holds a block, such as a keynote bubble, in place of the note. A style may name a `block`, with `blockConnection` and `blockScale`. `Leader.text` is optional, and `leaderPicture` takes a fourth argument that finds a block by name. - The built-in standard, version 3, has the leader style `notes`, its default leader style. A standard's leader style takes `direction`, `verticalAttachment`, `frame` and `shaft`. - `readDXF` reads every multileader whole (each root, the kind of shaft, each side's attachment, the note's width and where it is held, its frame, its mask, a block with its attributes) and the old `LEADER`. - Both writers write all of it, and `toSVG` and `toPDF` draw it. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 10 +- CHANGELOG.md | 35 ++ GUIDE.md | 13 +- docs/format.md | 15 +- docs/leaders.md | 125 ++++-- docs/reading.md | 30 +- docs/rules.md | 9 +- examples/site-plan.ts | 8 +- src/drawing.ts | 216 +++++++++- src/dxf-r2018.ts | 198 ++++++--- src/extents.ts | 37 +- src/index.ts | 16 +- src/inspect.ts | 40 +- src/leaders.ts | 895 ++++++++++++++++++++++++++++++++++----- src/lint.ts | 64 ++- src/read/check.ts | 35 ++ src/read/dxf.ts | 64 ++- src/read/entities.ts | 186 ++++++-- src/read/model.ts | 83 +++- src/rules.ts | 194 ++++++++- src/shape.ts | 18 +- src/standard/default.ts | 15 +- src/standard/define.ts | 2 +- src/standard/document.ts | 22 +- src/standard/lint.ts | 4 + src/standard/shape.ts | 30 +- src/svg.ts | 73 ++-- standard.json | 19 +- standard.schema.json | 70 ++- test/leaders.test.ts | 105 ++++- test/read-agreement.ts | 11 +- test/read-fuzz.ts | 213 +++++++++- test/read.test.ts | 7 +- test/shape.test.ts | 51 ++- test/standard.test.ts | 8 +- 35 files changed, 2481 insertions(+), 440 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ed206e4..807c350 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,8 +111,14 @@ refused inside a block, where that app draws nothing for it. - A leader holds its note, its point, its shafts and its own sizes, and the R2018 writer writes it as a multileader with no picture. `src/leaders.ts` is the one place that says what the leading CAD - app draws, `leaderPicture`, which the writers, `toSVG`, the extents and `inspectText` all read, - and `lineSpacing` in `src/measure.ts` the one rule for the pitch of a note's lines. A style's + app draws, `leaderPicture`, which the writers, `toSVG`, the extents and `inspectText` all read. + Its note is a `Paragraph`, laid out by `layoutParagraph` and held where the multileader holds it, + so the note's lines follow every rule of a paragraph's. A mask is drawn first in the leader's + group, so it hides what is drawn before the leader and none of the leader. A block in place of + the note is placed from its own outline, read once for each list of a block's entities and cut + at `OUTLINE_ITEMS`; `toSVG` draws it as an insert after the leader, so the insert walk draws it + and its attributes. A curved shaft is solved as three diagonals, in time in proportion to its + points. A style's sizes are paper sizes times its `scale`, and the file holds them multiplied out with a scale of 1. The writers add that app's own `Standard` and the dictionary `ACAD_MLEADERSTYLE` with the first style. The keys of the handles are `leader-style:NAME`, with A to Z in lower case, diff --git a/CHANGELOG.md b/CHANGELOG.md index 7986ff2..1e9bcf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,41 @@ ## Unreleased +- Leaders' notes, as CAD programs draw them. A note is laid out as paragraph text is, each line + set by the ink of its letters, so its lines move where they plot by up to a quarter of their + height from where earlier versions drew them. `attachment` takes every place CAD programs + attach a landing, `LEADER_ATTACHMENTS`: `"top-of-first"`, `"first-line"`, `"middle"`, + `"last-line"`, `"bottom-of-last"`, `"underline-last"`, `"underline-first"`, `"bottom-of-first"` + and `"underline-all"`, which underline the line they meet by running the landing on under it. + The middle of a line runs from its top as far down as its capitals and the last line's letters + below the baseline, as CAD programs measure it, so `"first-line"` and `"last-line"` notes sit a + little higher than before. A leader style's `direction: "vertical"` puts the note above or + below its point, `side` takes `"above"` and `"below"`, and `verticalAttachment` is `"center"` or + `"line"`, a line as wide as the note through the point. A leader's `width` wraps its note, each + item of its text a paragraph; `frame` on a style or a leader draws a frame one gap outside the + note; and a leader's `mask` hides what is drawn before it behind its note, `true` for the + drawing's background or `{ color, offsetFactor }`. Both writers write each of these as the + multileader CAD programs make, and `toSVG` and `toPDF` draw them where they plot. `lint` and + the builder refuse a width not greater than 0, a mask of another shape, and a value of + `attachment`, `side`, `direction` or `verticalAttachment` not in its list. +- Leaders with two roots, curved shafts and a block in place of the note. `toFarSide` gives the + shafts of a second root on the note's far side, whose point tsdraft works out from the note as + CAD programs do. `shaft: "curved"`, on a style or a leader, draws each shaft as the cubic CAD + programs draw through its tip, its bends and the end of its landing. `d.leader({ block, + attributes }, options)` holds a block of the drawing in place of the note, such as a keynote + bubble; a style may name the `block`, and `blockConnection` and `blockScale` say how it meets + the landing and how large it is. `Leader.text` is optional, since a leader whose content is a + block has none, and `leaderPicture` takes a fourth argument that finds a block by its name. + `lint` and the builder refuse a block the drawing lacks, a leader whose content is a block + that sets an option only a note has, and far shafts that are no shafts. +- The built-in standard, version 3, has the leader style `notes`, its `defaultLeaderStyle`: the + role `note`, a closed filled arrow 1/8 inch long, a landing of 1/8 and a gap of 1/16. A + standard's leader style takes a `direction`, a `verticalAttachment`, a `frame` and a `shaft`. +- `readDXF` and `readDWG` read a multileader whole: each of its roots, its kind of shaft, the + attachment of each side, its note's width and where it is held, its frame, its mask, and a + block in place of its note with its attributes; and the old `LEADER`, as the read model's + `leader`. + - Raster images, in R2018 drawings: `d.image(path, at, { pixels, width })` draws a PNG or a JPEG with its lower-left corner at `at`, `width` drawing units wide, and `height`, `rotation`, `clip`, `invertClip` and `transparent` where given; its height defaults to the file's diff --git a/GUIDE.md b/GUIDE.md index 5a7c24c..7ff475c 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -406,9 +406,14 @@ d.leader(["EXISTING TREE", "TO REMAIN"], { style: "NOTE", at: [62, 38], to: [52, - `at` is where the shafts meet. `to` is a point, or a list with a shaft for each item: a point, or a list of points from the tip through each bend. The note goes on the side away from the first shaft unless `side` says otherwise. -- A string is a one-line note, and an array its lines from the top. The note does not wrap. -- `arrowhead` is `"closed-filled"`, `"open"`, `"dot"` or `"none"`, and `attachment` has the - landing meet the `"first-line"` or the `"last-line"`. +- A string is a one-line note, and an array its paragraphs from the top. `width` wraps them. +- `arrowhead` is `"closed-filled"`, `"open"`, `"dot"` or `"none"`, and `attachment` is where the + landing meets the note, one of `LEADER_ATTACHMENTS`, such as `"first-line"` or + `"underline-last"`. A style with `direction: "vertical"` puts the note above or below its point. +- `frame: true` draws a frame around the note, and `mask: true` hides what is behind it. +- `shaft: "curved"` draws each shaft as a curve, `toFarSide` adds shafts from the note's other + side, and `d.leader({ block: "TAG", attributes: { NUM: "3" } }, options)` points a block, such + as a keynote bubble, at what it names. - Never draw a leader from lines and text. [docs/leaders.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/leaders.md) has the rest. @@ -605,8 +610,6 @@ writeFileSync("plan.dxf", toDXF(drawing)); ## What tsdraft cannot draw yet - Hatches, fills, and angular, arc length and ordinate dimensions. -- A leader with two roots, a curved shaft, a block in place of its note, or a note attached at - its top or bottom. - A block read from another file. A block is drawn in the drawing that inserts it. An xref references a whole DWG file, as an overlay, and the pictures draw it only from a drawing you give. diff --git a/docs/format.md b/docs/format.md index 1ce28b7..0a2f6ee 100644 --- a/docs/format.md +++ b/docs/format.md @@ -69,12 +69,15 @@ existed. [Dimensions](dimensions.md) describes them. A drawing lists its leader styles in `leaderStyles`, and leaves the field out when it has none. A style has a `name`, a `textHeight`, an `arrowSize`, a `landing` and a `gap`, and where they -are set a `textStyle`, an `arrowhead`, an `attachment` and a `scale`. A leader is an entity of -kind `"leader"`, in `drawing.entities` or in a layout's `entities`, with its `layer`, `style`, -`text`, the lines of its note from the top, `at`, where its shafts meet, and `shafts`, each a -list of points from its tip. Where it has them of its own it has a `side`, an `attachment`, a -`textStyle`, a `textHeight`, an `arrowSize`, a `landing` and a `gap`. It has no linetype or -lineweight. A drawing with no leader has the JSON it had before leaders existed. +are set a `textStyle`, an `arrowhead`, an `attachment`, a `direction`, a `verticalAttachment`, a +`frame`, a `shaft`, a `block`, a `blockConnection`, a `blockScale` and a `scale`. A leader is an entity of kind `"leader"`, in `drawing.entities` or in a +layout's `entities`, with its `layer`, `style`, `text`, the paragraphs of its note from the top, +`at`, where its shafts meet, and `shafts`, each a list of points from its tip. Where it has them +of its own it has a `side`, an `attachment`, a `verticalAttachment`, a `width`, a `frame`, a +`mask`, a `shaft`, `farShafts`, the shafts of a root on the note's far side, a `textStyle`, a +`textHeight`, an `arrowSize`, a `landing` and a `gap`. A leader whose content is a block has no +`text`, and a `block` and, where it sets them, `attributes`. It has no linetype +or lineweight. A drawing with no leader has the JSON it had before leaders existed. [Leaders](leaders.md) describes them. A paragraph is an entity of kind `"paragraph"`, in `drawing.entities`, a block's `entities` or a diff --git a/docs/leaders.md b/docs/leaders.md index ed02ead..26163bb 100644 --- a/docs/leaders.md +++ b/docs/leaders.md @@ -41,17 +41,31 @@ Every leader names a leader style, which says how it is drawn. `d.leaderStyle(de defines one. A style is defined once, under a name no other style has, and before the first leader that names it. -| Field | What it sets | -| ------------ | ------------------------------------------------------------------------------------------------------------------ | -| `name` | The style's name, held to the rules of a dimension style's name. | -| `textStyle` | The text style of the note. `"Standard"` unless given. | -| `textHeight` | The height of the note's capitals. Greater than 0. | -| `arrowhead` | `"closed-filled"`, the default, `"open"`, `"dot"` or `"none"`. `LEADER_ARROWHEADS` lists them. | -| `arrowSize` | The length of an arrowhead. 0 draws none. | -| `landing` | The length of the level line from where the shafts meet toward the note. 0 draws none. | -| `gap` | The gap between the end of the landing and the note. | -| `attachment` | `"first-line"`, the default, has the landing meet the middle of the note's first line, and `"last-line"` its last. | -| `scale` | What every size above is multiplied by. 1 unless given. | +| Field | What it sets | +| -------------------- | ------------------------------------------------------------------------------------------------- | +| `name` | The style's name, held to the rules of a dimension style's name. | +| `textStyle` | The text style of the note. `"Standard"` unless given. | +| `textHeight` | The height of the note's capitals. Greater than 0. | +| `arrowhead` | `"closed-filled"`, the default, `"open"`, `"dot"` or `"none"`. `LEADER_ARROWHEADS` lists them. | +| `arrowSize` | The length of an arrowhead. 0 draws none. | +| `landing` | The length of the level line from where the shafts meet toward the note. 0 draws none. | +| `gap` | The gap between the end of the landing and the note. | +| `attachment` | Where the landing meets the side of the note: one of `LEADER_ATTACHMENTS`, below. | +| `direction` | `"horizontal"`, the default, or `"vertical"`: the landing meets the note's top or bottom. | +| `verticalAttachment` | Where it meets a note above or below: `"center"`, the default, or `"line"`, with a line under it. | +| `frame` | `true` for a frame around each note, one gap outside it. `false` unless given. | +| `shaft` | `"straight"`, the default, or `"curved"`: each shaft a curve through its points. | +| `block` | A block of the drawing its leaders hold in place of a note. | +| `blockConnection` | How the block meets the landing: `"extents"`, the default, or `"insertion"`. | +| `blockScale` | What the block is scaled by, times `scale`. 1 unless given. | +| `scale` | What every size above is multiplied by. 1 unless given. | + +`LEADER_ATTACHMENTS` are, in order: `"top-of-first"`, the top of the note; `"first-line"`, the +default, the middle of its first line; `"middle"`, the middle of the note; `"last-line"`, the +middle of its last line; `"bottom-of-last"`, its bottom; `"underline-last"`, the bottom of its last +line, with the landing drawn on under that line; `"underline-first"`, the same under its first +line; `"bottom-of-first"`, the bottom of its first line; and `"underline-all"`, which underlines +every line. Give the sizes as they plot, and let `scale` carry the view, as for a [dimension style](dimensions.md#sizes-and-the-scale). A leader in model space that a viewport @@ -62,16 +76,35 @@ scale of 1, so CAD draws the sizes the style works out. ## A leader `d.leader(text, options)` draws one. `text` is the note: a string for one line, or an array of -its lines from the top. CAD draws the lines as they are given and does not wrap them. +its paragraphs from the top. Each is one line, unless `width` wraps it. In place of a note it may +be `{ block, attributes }`: a block of the drawing, such as a tag or a keynote bubble, and the +value of each of its attributes, by its tag, where it is not its definition's. + +```ts +d.leader( + { block: "KEYNOTE", attributes: { NUM: "7" } }, + { style: "KEYNOTES", at: [62, 38], to: [52, 26] }, +); +``` - `style` names the leader style. - `at` is where the shafts meet and the landing starts. - `to` is what the note names. A point is the tip of one straight shaft. A list has a shaft for each item: a point is a straight shaft from that tip, and a list of points is a shaft from its first point, the tip, through each point after it, where it bends, to `at`. -- `side` is the side of `at` the note is on, `"left"` or `"right"`. Unless given, it is the side - away from the first shaft: right when `at` is not to the left of the last point before it. -- `attachment` replaces the style's. +- `side` is the side of `at` the note is on: `"left"`, `"right"`, `"above"` or `"below"`. Unless + given, it is the side away from the first shaft: in a horizontal style right when `at` is not to + the left of the last point before it, and in a vertical one above when `at` is not below it. +- `attachment` and `verticalAttachment` replace the style's. +- `width` is the width the note wraps at, greater than 0, times the style's scale. +- `frame` and `shaft` replace the style's. +- `toFarSide` gives the shafts of a second root, on the note's far side, as `to` does. Its point + is worked out from the note: past its far end, as far out as `at` is on the near side, or above + or below a note that is below or above `at`. A drafter moves the note and both roots follow. +- `mask` hides what is drawn before the leader behind its note: `true` for the drawing's + background, or `{ color, offsetFactor }`, with a color index from 1 to 255, or 256 for the + layer's, and how far the mask reaches past the note, as a factor of its text height from 1 to + 5, 1.5 unless given. - `textStyle`, `textHeight`, `arrowSize`, `landing` and `gap` replace the style's, each times the style's scale. The file holds each as the leader's own, so CAD keeps it when the style changes. @@ -90,23 +123,38 @@ in a block. radius of half the arrow size. `"none"` draws no arrowhead. The shaft reaches the tip either way: with an arrowhead, the arrowhead draws the last arrow size of it. - The landing runs level from `at`, as long as `landing`, toward the note's side. -- The note starts `gap` past the end of the landing. On the right it is justified left, and on - the left justified right. The middle of the capitals of its first line, or of its last line, - is level with `at`. -- Its lines are `lineSpacing(textHeight)` apart, 5/3 of the height. `lineSpacing` is the one - rule for that, which the picture, the extents and `inspectText` use. +- The note is a paragraph, laid out as [paragraph text](paragraphs.md) is: each line set by the + ink of its letters, and wrapped at `width`. On the right it starts `gap` past the end of the + landing, justified left, and on the left it ends there, justified right. Its attachment puts it + as high as CAD does: for `"first-line"`, the middle of its first line, which runs from its top + as far down as its capitals and the last line's letters below the baseline, is level with `at`. +- The underline attachments run the landing on under the line they meet, as far as the note + reaches, but not into a frame. +- Above or below `at`, the note is a gap away from it and centered on it, and no landing is drawn. + With `"line"`, a line as wide as the note runs through `at`. +- A frame runs around the note's box one gap outside it, and a mask fills the note's box grown by + its factor of the text height less one, each side, before the rest of the leader is drawn. +- A curved shaft is the cubic CAD programs draw through the arrowhead's base, each bend and the end + of the landing, which it meets level, with no landing drawn apart. A curve whose first stretch + is shorter than the arrowhead draws none and runs to its tip. +- A block in place of the note is level with `at`. By its extents, the side of its box meets the + end of the landing; by its insertion point, it is slid along the line through `at` until its + outline meets the end of the landing. `leaderPicture(leader, style, textStyle)` gives what CAD draws for a leader: each shaft as drawn, -its arrowheads, its landing and each line of its note with where it is, and the numbers the file -holds for it. `leaderSizes(leader, style)` gives the sizes it is drawn with, and +its arrowheads, its landing, its note as a paragraph and where it is held, its underlines, its +frame and its mask, and the numbers the file holds for it. `leaderSizes(leader, style)` gives the sizes it is drawn with, and `findLeaderStyle(drawing, name)` the style a leader names. ## Under a standard A standard lists its leader styles in `leaderStyles`, by an id, each with a `role`, which gives the note its text style and height, and an `arrowSize`, a `landing` and a `gap` on paper, and -optionally an `arrowhead` and an `attachment`. `defaultLeaderStyle` names the one a leader with -no `style` is drawn in. +optionally an `arrowhead`, an `attachment`, a `direction`, a `verticalAttachment`, a `frame` and a +`shaft`. +`defaultLeaderStyle` names the one a leader with no `style` is drawn in. The built-in standard's +is `notes`: the role `note`, a closed filled arrowhead 1/8 inch long, a landing of 1/8 inch, a gap +of 1/16 and the landing at the middle of the first line. ```ts const standard = defineStandard({ @@ -133,8 +181,10 @@ style and height of another role, and a size of its own is a length on paper. `toSVG` draws each leader as CAD does, in model space, through a viewport and on a sheet, in its layer's color and lineweight. A leader is a `` with `data-layer`, `data-entity`, `data-id` and `data-leader`, its note with a line break between its lines. Its children have a -`data-part`: `shaft`, `landing`, `arrowhead` or `text`. A drawing's extents take its leaders -in, notes included. +`data-part`: `mask`, `shaft`, `landing`, `arrowhead`, `underline`, `frame` or `text`. A mask in +the drawing's background is filled white and marked `data-mask="background"`, for a viewer whose +background is another color. A drawing's extents take its leaders in, notes, frames and masks +included. `inspectText` takes each line of a leader's note for a text where the picture puts it, so it warns of a note that plots over another text. @@ -152,10 +202,15 @@ Each of these is an error, at the builder's call and in `lint`. The rule is `lea handle, which would lead to no style. - A text height is greater than 0. The arrow size, the landing and the gap are 0 or more, and the scale is greater than 0. -- An arrowhead is one of `LEADER_ARROWHEADS`, an attachment `"first-line"` or `"last-line"`, - and a side `"left"` or `"right"`. -- Every line of a note is a single line of text with none of `\`, `{` and `}`, which the leading CAD - app reads as the formatting of the note. One line is not empty or all spaces. +- A leader whose content is a block names a block of the drawing, and sets none of `text`, + `attachment`, `verticalAttachment`, `width`, `frame`, `mask`, `textStyle` and `textHeight`. + Its attributes are strings. +- An arrowhead is one of `LEADER_ARROWHEADS`, an attachment one of `LEADER_ATTACHMENTS`, a side + one of `LEADER_SIDES`, a direction one of `LEADER_DIRECTIONS`, a vertical attachment one of + `LEADER_VERTICAL_ATTACHMENTS`, a frame `true` or `false`, a width greater than 0 and a mask as + above. +- Every paragraph of a note is text with none of `\`, `{` and `}`, which the leading CAD app reads + as the formatting of the note. One is not empty or all spaces. - A leader has a shaft, and each shaft starts with its tip. Its tip and the point after it, or `at` for a straight shaft, are not one point once they are written with 6 decimals: CAD would have no direction to point the arrowhead in. @@ -196,10 +251,12 @@ tsdraft. For a drawing with a leader style, tsdraft writes the leading CAD app's own leader style `Standard` and each style of the drawing, in the dictionary `ACAD_MLEADERSTYLE`, the blocks `_Open`, `_Dot` and `_None` that its styles draw arrowheads with, and each leader as a multileader: one leader root -where its shafts meet, a leader line for each shaft, and its note as a multiline text. The file -holds no picture of a leader. CAD draws it from what the multileader holds. +where its shafts meet and a second on the note's far side, a leader line for each shaft, and its +note as a multiline text with its width, its mask and where it is held, or its block with where +it is placed and its attributes as the multileader's labels. The file holds no picture of a leader. CAD draws it from +what the multileader holds. ## What is not drawn yet -A leader with two roots, a curved shaft, a block in place of the note, a note attached at its -top or bottom, a frame around the note, and a note that wraps at a width. +A block in place of the note draws its attributes centered by their ink, where CAD programs center +a label of a multileader's block by its advances: 0.0055 inch apart for a `1` 0.1 inch high. diff --git a/docs/reading.md b/docs/reading.md index 5ea18fd..0a2a927 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -34,8 +34,8 @@ does not read again what it made: - The value of a `TEXT`, an attribute and an attribute definition, with its tag and its prompt, goes through two passes: `\U+XXXX` in the first, and `\U+XXXX` and `\M+NXXXX` in the second. So `\U+005CU+00B0` is held as `°`, and `\U+005CU+005CU+00B0` as `\U+00B0`. -- The value of an `MTEXT`, a dimension's text and a multileader's note goes through one pass of - both. +- The value of an `MTEXT`, a dimension's text, and a multileader's note and its block's labels go + through one pass of both. - A name, such as a layer's, and an xref's path go through one pass of `\U+XXXX`. tsdraft's own DXF escapes what the leading CAD app would decode, so a read of it gives every text as @@ -98,7 +98,8 @@ The texts of a block's definition are kept, since a title block's labels belong ### Entities -A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers write: +A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers write, and the old +leader: - `line`, `circle` and `arc`, and `polyline` for a lightweight polyline or a 2D one, open or closed, with `bulges`, one for each side, when a side is an arc, and `width`, one width for @@ -125,9 +126,26 @@ A space and a block hold one type, `ReadEntity`, of the kinds tsdraft's writers middle of its text, `placed` where the file holds the text where it was placed, what it measures, its text, its style and the block of its picture. A file holds a diameter's far point, and the center is halfway to the point. -- `multileader`: one with straight shafts, one root and a note, with its style, each shaft from - its tip, the point where the shafts meet, the landing's direction and length, its note, where - the note is held, and the note's height and style. Any other is counted under `other`. +- `multileader`: a note or a block, with its `style`, `textHeight` and `arrowSize`. `roots` holds + each root in the file's order, one with no shafts among them: the point `at` where its shafts + meet, its landing's `direction` and length, and its `shafts`, each from its tip. `shafts`, `at`, + `direction` and `landing` repeat the first root's, and one with no root has no shafts, its + note's point and no landing. `shaft` says how its shafts are drawn: `straight`, `curved` through + their points, or `none`. Its note is `text`, with `\P` between lines, held at `textAt` by the + point `textAttachment` names, as an `MTEXT`'s attachment, wrapping at `width`, or 0 where it + does not, in `textStyle`. `attachments` says where a landing meets each side of the note, + `vertical` that its landings meet the note's top or bottom, `frame` that a frame goes around the + note, and `mask` that a mask is behind it: the drawing's background, or the color index `color`, + over the note's box grown by `offsetFactor` times its height less one. A block as its content + has `text` `""`, `textAt` at the block, and `block`: its `name`, `at`, `scale`, `rotation` in + degrees, and `attributes`, the value each of its labels gives, by the tag of the attribute + definition it fills. A label whose definition the read does not hold is left out, and at most + 1,000 are read. One whose note or block leaves the plane is counted under `other`. +- `leader`: the old leader, with its dimension `style`, its `points` from its tip as the file + holds them, `shaft`, `straight` or `curved`, whether it draws an `arrowhead`, and `note`, the + handle of the entity that is its note, where it has one. The leading CAD app leaves group 71 out + where it draws an arrowhead, and group 73 where it has no note. One in another plane is counted + under `other`. - `solid`: three or four corners, filled, as a dimension draws an arrowhead. - `image`: a raster image, with its definition's `path` and the handle of the `definition`, the `pixels` it states, its lower-left corner `at`, and `u` and `v`, the vectors of one of its pixels diff --git a/docs/rules.md b/docs/rules.md index 94a0a77..f5f0504 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -213,9 +213,12 @@ it would take `1e+100` for `1e+10` and report nothing. - A leader names a leader style the drawing defines, and not `Standard`, which is the leading CAD app's own. A leader style's name follows the rules of a dimension style's name. Its text style, and a leader's own, is one the drawing defines. Its text height is greater than 0, its arrow - size, landing and gap are 0 or more, its scale is greater than 0, and its arrowhead is one of - `LEADER_ARROWHEADS`. [Leaders](leaders.md#what-lint-reports) says why. -- A leader's note is lines of text with none of `\`, `{` and `}`, and one line that is not + size, landing and gap are 0 or more, its scale is greater than 0, its arrowhead is one of + `LEADER_ARROWHEADS` and its attachment one of `LEADER_ATTACHMENTS`. A leader's width is greater + than 0, and its mask `true`, `false` or a color index and a factor from 1 to 5. A leader whose + content is a block names a block of the drawing and sets nothing only a note has. + [Leaders](leaders.md#what-lint-reports) says why. +- A leader's note is paragraphs of text with none of `\`, `{` and `}`, and one that is not empty or all spaces. A leader has a shaft, and the first segment of each has a length once it is written with 6 decimals. Every number a leader draws is under 1e100. - A leader is not in a block, and an R12 drawing has no leaders. diff --git a/examples/site-plan.ts b/examples/site-plan.ts index c4a21de..b0d0ae4 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -97,9 +97,9 @@ import { /** * The standard the sheet is drawn to: the built-in one, with layers for the trees and the - * revision and a leader style for the notes. Its layers give the plan its colors, linetypes and pens, its linetype - * scale sizes the dashes, and its leader style gives every leader its arrowhead, its landing and - * the role of its note. + * revision. Its layers give the plan its colors, linetypes and pens, its linetype scale sizes the + * dashes, and its leader style `notes` gives every leader its arrowhead, its landing and the role + * of its note. */ export const standard = defineStandard({ id: "site-plan-example", @@ -110,8 +110,6 @@ export const standard = defineStandard({ "C-ANNO-REVS": { color: 1, pen: "medium", discipline: "C" }, "C-ANNO-IMAG": { color: 8, pen: "fine", discipline: "C" }, }, - leaderStyles: { notes: { role: "note", arrowSize: 1 / 8, landing: 1 / 8, gap: 1 / 16 } }, - defaultLeaderStyle: "notes", }); /** diff --git a/src/drawing.ts b/src/drawing.ts index f86f788..bb87720 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -120,6 +120,7 @@ import { textStyleProblem, undefinedAttributeProblem, undefinedBlockProblem, + leaderBlockContentProblem, undefinedDimensionStyleProblem, undefinedDimensionTextStyleProblem, undefinedLeaderStyleProblem, @@ -204,7 +205,11 @@ import { type PARAGRAPH_ALIGNS, type PARAGRAPH_VERTICAL_ALIGNS, type LEADER_ATTACHMENTS, + type LEADER_DIRECTIONS, + type LEADER_BLOCK_CONNECTIONS, + type LEADER_SHAFT_KINDS, type LEADER_SIDES, + type LEADER_VERTICAL_ATTACHMENTS, } from "./rules.ts"; import type { Standard, @@ -620,11 +625,27 @@ export interface JoggedRadiusDimension extends RadialDimensionBase { /** Which side of the point where its shafts meet a leader's note is on. */ export type LeaderSide = (typeof LEADER_SIDES)[number]; +/** Where a leader's landing meets the side of its note: one of `LEADER_ATTACHMENTS`. */ +export type LeaderAttachment = (typeof LEADER_ATTACHMENTS)[number]; + +/** Whether a leader style's landings meet the side of its notes or their top or bottom. */ +export type LeaderDirection = (typeof LEADER_DIRECTIONS)[number]; + +/** How a leader's shafts run through their points: straight, or as a curve. */ +export type LeaderShaftKind = (typeof LEADER_SHAFT_KINDS)[number]; + +/** How a block in place of a leader's note meets its landing. */ +export type LeaderBlockConnection = (typeof LEADER_BLOCK_CONNECTIONS)[number]; + +/** Where a landing meets a note above or below it: at its middle, or with a line as wide as it. */ +export type LeaderVerticalAttachment = (typeof LEADER_VERTICAL_ATTACHMENTS)[number]; + /** - * Which line of a leader's note its landing meets, at the middle of that line's capitals: the - * first, which is the leading CAD app's own choice, or the last. + * A mask behind a leader's note, which hides what is drawn before the leader there: `true` for + * the drawing's background, or a color index of its own, over the note's box grown by + * `offsetFactor` times its text height less one, 1.5 unless given. */ -export type LeaderAttachment = (typeof LEADER_ATTACHMENTS)[number]; +export type LeaderMask = boolean | { readonly color?: number; readonly offsetFactor?: number }; /** * A leader: a note joined to what it names by one or more shafts. The leading CAD app holds it as @@ -637,8 +658,15 @@ export interface Leader extends Placed { readonly kind: "leader"; /** A leader style of the drawing. */ readonly style: string; - /** The lines of the note, from the top. */ - readonly text: readonly string[]; + /** + * The paragraphs of the note, from the top. Each is one line unless `width` wraps it. A leader + * whose content is a block has none. + */ + readonly text?: readonly string[]; + /** A block of the drawing in place of the note. Defaults to its style's. */ + readonly block?: string; + /** The value of each attribute of the block, by its tag, where it is not its definition's. */ + readonly attributes?: Readonly>; /** Where the shafts meet and the landing starts. */ readonly at: Point; /** @@ -647,12 +675,29 @@ export interface Leader extends Placed { */ readonly shafts: readonly (readonly Point[])[]; /** - * Which side of `at` the note is on. Defaults to the side away from the first shaft: right - * when `at` is not to the left of the shaft's last point before it, its last bend or its tip. + * Which side of `at` the note is on. Defaults to the side away from the first shaft: in a style + * whose `direction` is horizontal, right when `at` is not to the left of the shaft's last point + * before it, its last bend or its tip, and in a vertical one above when `at` is not below it. + * Above or below, the landing meets the note at its bottom or top. */ readonly side?: LeaderSide; - /** Which line of the note the landing meets. Defaults to its style's. */ + /** Where the landing meets the side of the note. Defaults to its style's. */ readonly attachment?: LeaderAttachment; + /** Where the landing meets a note above or below it. Defaults to its style's. */ + readonly verticalAttachment?: LeaderVerticalAttachment; + /** The width the note wraps at, in the same units as its sizes: times its style's scale. */ + readonly width?: number; + /** True for a frame around the note. Defaults to its style's. */ + readonly frame?: boolean; + /** A mask behind the note. */ + readonly mask?: LeaderMask; + /** How its shafts run through their points. Defaults to its style's. */ + readonly shaft?: LeaderShaftKind; + /** + * The shafts of a second root, on the note's far side: each its tip, then each point it bends + * at on its way to that root, whose point is worked out from the note. + */ + readonly farShafts?: readonly (readonly Point[])[]; /** The leader's own text style, in place of its style's. */ readonly textStyle?: string; /** The leader's own sizes, in place of its style's, in the same units: each times its scale. */ @@ -723,7 +768,7 @@ export type Entity = * another scale. * * tsdraft draws every leader the same way where a style has no choice: straight shafts, a level - * landing, and a note of lines that do not wrap, set `lineSpacing` apart. + * landing, and a note laid out as paragraph text, its lines spaced at least as far as they need. */ export interface LeaderStyle { readonly name: string; @@ -739,8 +784,28 @@ export interface LeaderStyle { readonly landing: number; /** The gap between the end of the landing and the note. */ readonly gap: number; - /** Which line of the note the landing meets. Defaults to `"first-line"`. */ + /** Where the landing meets the side of the note. Defaults to `"first-line"`. */ readonly attachment?: LeaderAttachment; + /** + * Whether the landing meets the side of the note, `"horizontal"`, the default, or its top or + * bottom, `"vertical"`, which also sets the side a leader's note takes by default. + */ + readonly direction?: LeaderDirection; + /** Where the landing meets a note above or below it. Defaults to `"center"`. */ + readonly verticalAttachment?: LeaderVerticalAttachment; + /** True for a frame around each note, one gap outside it. Defaults to false. */ + readonly frame?: boolean; + /** How its leaders' shafts run through their points: `"straight"`, the default, or `"curved"`. */ + readonly shaft?: LeaderShaftKind; + /** A block of the drawing its leaders hold in place of a note. */ + readonly block?: string; + /** + * How a block meets the landing: by its extents, `"extents"`, the default, or by its outline on + * the line through its insertion point, `"insertion"`. + */ + readonly blockConnection?: LeaderBlockConnection; + /** What the block is scaled by, times `scale`. Defaults to 1. */ + readonly blockScale?: number; /** * What every size of the style is multiplied by: how many units of the leader's space one * unit of the sizes is. Defaults to 1. @@ -1828,8 +1893,22 @@ export interface LeaderStyleDefinition< readonly landing: LeaderSize; /** The gap between the end of the landing and the note. */ readonly gap: LeaderSize; - /** Which line of the note the landing meets. Defaults to `"first-line"`. */ + /** Where the landing meets the side of the note. Defaults to `"first-line"`. */ readonly attachment?: LeaderAttachment; + /** `"horizontal"`, the default, or `"vertical"`: the landing meets the note's top or bottom. */ + readonly direction?: LeaderDirection; + /** Where the landing meets a note above or below it. Defaults to `"center"`. */ + readonly verticalAttachment?: LeaderVerticalAttachment; + /** True for a frame around each note, one gap outside it. Defaults to false. */ + readonly frame?: boolean; + /** `"straight"`, the default, or `"curved"`: a curve through the tip, each bend and the landing. */ + readonly shaft?: LeaderShaftKind; + /** A block of the drawing its leaders hold in place of a note, as `{ block }` gives one. */ + readonly block?: string; + /** `"extents"`, the default, or `"insertion"`: how a block meets the landing. */ + readonly blockConnection?: LeaderBlockConnection; + /** What the block is scaled by, times `scale`, greater than 0. Defaults to 1. */ + readonly blockScale?: number; /** What every size is multiplied by, greater than 0. Defaults to 1. */ readonly scale?: LeaderScale; } @@ -1840,6 +1919,15 @@ export interface LeaderStyleDefinition< */ export type LeaderTargets = Point | readonly (Point | readonly Point[])[]; +/** + * A block of the drawing in place of a leader's note, and the value of each of its attributes + * that is not its definition's, by its tag. The note's own options, such as `width`, do not apply. + */ +export interface LeaderBlockContent { + readonly block: string; + readonly attributes?: Readonly>; +} + /** What every leader is drawn with: where its shafts meet, what they point to and how. */ interface LeaderPlacement { /** Where the shafts meet and the landing starts. */ @@ -1848,11 +1936,25 @@ interface LeaderPlacement { readonly to: LeaderTargetsOf; /** * Which side of `at` the note is on. Defaults to the side away from the first shaft: right when - * `at` is not to the left of the shaft's last point before it. + * `at` is not to the left of the shaft's last point before it, or in a vertical style above + * when `at` is not below it. */ readonly side?: LeaderSide; - /** Which line of the note the landing meets. Defaults to its style's. */ + /** Where the landing meets the side of the note. Defaults to its style's. */ readonly attachment?: LeaderAttachment; + /** Where the landing meets a note above or below it. Defaults to its style's. */ + readonly verticalAttachment?: LeaderVerticalAttachment; + /** True for a frame around the note. Defaults to its style's. */ + readonly frame?: boolean; + /** A mask behind the note: `true` for the drawing's background, or `{ color, offsetFactor }`. */ + readonly mask?: LeaderMask; + /** How its shafts run through their points. Defaults to its style's. */ + readonly shaft?: LeaderShaftKind; + /** + * The shafts of a second root on the note's far side, as `to` gives shafts: its point is worked + * out from the note, on its other side, or above or below it. + */ + readonly toFarSide?: LeaderTargets; } /** The options of `leader()`. Each size of its own replaces its style's, and is multiplied by the style's scale. */ @@ -1865,9 +1967,12 @@ export interface LeaderOptions< L extends number = number, G extends number = number, TO extends LeaderTargets = LeaderTargets, + W extends number = number, > extends LeaderPlacement { /** A leader style of the drawing. */ readonly style: LeaderStyleName; + /** The width the note wraps at, greater than 0, in place of none: times the style's scale. */ + readonly width?: Positive; /** A text style of the drawing for the note, in place of its style's. */ readonly textStyle?: TextStyleName; /** The height of the note's capitals, in place of its style's. */ @@ -1901,9 +2006,12 @@ export interface StandardLeaderOptions< L extends number = number, G extends number = number, TO extends LeaderTargets = LeaderTargets, + W extends number = number, > extends LeaderPlacement { /** A leader style of the standard, by its id. Defaults to its `defaultLeaderStyle`. */ readonly style?: LeaderStyleOfStandard; + /** The width the note wraps at on paper, greater than 0. */ + readonly width?: Positive; /** In model space, the view the leader is read in, which `view()` returns. */ readonly view?: View; /** A text role of the standard for the note, in place of its style's. */ @@ -3926,6 +4034,23 @@ export class DrawingBuilder< landing: definition.landing, gap: definition.gap, ...(attachment === "first-line" ? {} : { attachment }), + ...(definition.direction === undefined || definition.direction === "horizontal" + ? {} + : { direction: definition.direction }), + ...(definition.verticalAttachment === undefined || definition.verticalAttachment === "center" + ? {} + : { verticalAttachment: definition.verticalAttachment }), + ...(definition.frame === true ? { frame: true } : {}), + ...(definition.shaft === undefined || definition.shaft === "straight" + ? {} + : { shaft: definition.shaft }), + ...(definition.block === undefined ? {} : { block: definition.block }), + ...(definition.blockConnection === undefined || definition.blockConnection === "extents" + ? {} + : { blockConnection: definition.blockConnection }), + ...(definition.blockScale === undefined || definition.blockScale === 1 + ? {} + : { blockScale: definition.blockScale }), ...(scale === 1 ? {} : { scale }), }); this.#leaderStylesAudited.set(layerAuditKey(named), named); @@ -3953,13 +4078,14 @@ export class DrawingBuilder< G extends number = number, R extends string = string, TO extends LeaderTargets = LeaderTargets, + W extends number = number, >( - text: LeaderText, + text: LeaderText | LeaderBlockContent, options: Z extends Standard - ? StandardLeaderOptions + ? StandardLeaderOptions : V extends "R12" ? R12Leaders - : LeaderOptions, + : LeaderOptions, ): this { return this.#add(DrawingBuilder.prototype.leader, idOf(options), () => this.#leader(text as unknown, options as unknown), @@ -3971,9 +4097,34 @@ export class DrawingBuilder< if (this.dxf === "R12") refuse("leader", R12_ONLY.leaders); if (this.#open) refuse("leader", LEADER_IN_BLOCK); const o = (typeof given === "object" && given !== null ? given : {}) as Record; + // A block in place of the note: `{ block, attributes }`. + const content = + typeof text === "object" && text !== null && !Array.isArray(text) + ? (text as { readonly block?: unknown; readonly attributes?: unknown }) + : undefined; const lines: unknown = typeof text === "string" ? [text] : text; - const textProblem = leaderTextProblem(lines); - if (textProblem) refuse("leader", textProblem); + if (content === undefined) { + const textProblem = leaderTextProblem(lines); + if (textProblem) refuse("leader", textProblem); + } else { + if (typeof content.block !== "string") + refuse("undefined-block", "a block is named by a string"); + const placed = this.#blocks.get(layerKey(content.block as string)); + if (placed === undefined) { + refuse( + "undefined-block", + `${undefinedBlockProblem(content.block as string)}. Define it with block() first`, + ); + } + const problem = leaderBlockContentProblem({ ...o, attributes: content.attributes }); + if (problem) refuse("leader", problem); + // Each value names an attribute of the block, as an insert's does. + const tags = new Set((placed!.attributes ?? []).map((d) => d.tag)); + for (const tag of Object.keys((content.attributes as object | undefined) ?? {})) { + if (!tags.has(tag)) + refuse("undefined-attribute", undefinedAttributeProblem(tag, placed!.name)); + } + } // Its point and its shafts first: under a standard, finding its style defines the style. const at = o.at; if ( @@ -3987,6 +4138,8 @@ export class DrawingBuilder< const shafts = shaftsOf(o.to); const shaftProblem = leaderShaftsProblem(shafts, point); if (shaftProblem) refuse("leader", shaftProblem); + // The far root's point is the note's, so its shafts are checked as a leader's once it is made. + const far = o.toFarSide === undefined ? undefined : shaftsOf(o.toFarSide); let style: LeaderStyle; let own: Partial> = {}; if (this.#standard) { @@ -4025,22 +4178,41 @@ export class DrawingBuilder< kind: "leader", layer: this.#current, style: style.name, - text: [...(lines as readonly string[])], + ...(content === undefined + ? { text: [...(lines as readonly string[])] } + : { + block: this.#blocks.get(layerKey(content.block as string))!.name, + ...(content.attributes === undefined + ? {} + : { attributes: { ...(content.attributes as Record) } }), + }), at: point, shafts: (shafts as readonly (readonly Point[])[]).map((shaft) => shaft.map(pt)), ...(o.side === undefined ? {} : { side: o.side as LeaderSide }), ...(o.attachment === undefined ? {} : { attachment: o.attachment as LeaderAttachment }), + ...(o.verticalAttachment === undefined + ? {} + : { verticalAttachment: o.verticalAttachment as LeaderVerticalAttachment }), ...own, ...(o.arrowSize === undefined ? {} : { arrowSize: o.arrowSize as number }), ...(o.landing === undefined ? {} : { landing: o.landing as number }), ...(o.gap === undefined ? {} : { gap: o.gap as number }), + ...(o.width === undefined ? {} : { width: o.width as number }), + ...(o.frame === undefined ? {} : { frame: o.frame as boolean }), + ...(o.mask === undefined ? {} : { mask: o.mask as LeaderMask }), + ...(o.shaft === undefined ? {} : { shaft: o.shaft as LeaderShaftKind }), + ...(far === undefined + ? {} + : { farShafts: (far as readonly (readonly Point[])[]).map((shaft) => shaft.map(pt)) }), }; const ownProblem = leaderOwnProblem(made, written(style.scale ?? 1)); if (ownProblem) refuse("leader", ownProblem); const styleName = made.textStyle ?? style.textStyle; const textStyle = styleName === undefined ? undefined : this.#textStyles.get(layerKey(styleName)); - const drawn = leaderDrawnProblem(made, style, textStyle); + const drawn = leaderDrawnProblem(made, style, textStyle, (name) => + this.#blocks.get(layerKey(name)), + ); if (drawn) refuse("leader", drawn); return made; } @@ -4090,6 +4262,10 @@ export class DrawingBuilder< landing: fields.landing, gap: fields.gap, attachment: fields.attachment, + direction: fields.direction, + verticalAttachment: fields.verticalAttachment, + frame: fields.frame, + shaft: fields.shaft, scale, }); return this.#leaderStyles.get(layerKey(name))!; diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index a6df634..20c6122 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -107,6 +107,9 @@ import { leaderPicture, leaderSizes, leaderStyleDictionaryHandle, + leaderVerticalAttachment, + noteAttachmentPoint, + verticalAttachmentCode, STANDARD_LEADER_STYLE_SIZES, validLeaderStyleHandle, } from "./leaders.ts"; @@ -511,6 +514,7 @@ export function toDXFR2018( handle: own, owner, paper, + findBlock: (name) => blocksByName.get(layerKey(name)), textStyle: styleOf(named), textStyleHandle: textStyleHandles.get(layerKey(named ?? STANDARD_TEXT_STYLE)) ?? standardStyle, @@ -740,7 +744,9 @@ export function toDXFR2018( g(350, validLeaderStyleHandle(style.name)); } for (const [style, textStyle] of styles) { - writeLeaderStyle(g, style, leaderDictionary, textStyle, linetypeByBlock); + const content = + style.block === undefined ? undefined : blocksByName.get(layerKey(style.block))?.name; + writeLeaderStyle(g, style, leaderDictionary, textStyle, linetypeByBlock, content); } } if (images.length > 0) { @@ -1964,11 +1970,12 @@ const LINEWEIGHT_BY_BLOCK = -2; /** * A leader style, with its sizes times its scale and a scale of 1. Its shafts, its text and its * block are ByBlock, so a leader draws in its own color, linetype and lineweight, which are its - * layer's. The note's lines are set at least `lineSpacing` apart and do not wrap, and the text + * layer's. The note's lines are spaced at least as the paragraph layout sets them, and the text * is level. * * @param textStyle - The handle of the style's text style. * @param linetype - The handle of the linetype ByBlock. + * @param content - The block the style holds in place of a note, as the drawing names it. */ function writeLeaderStyle( g: Group, @@ -1976,22 +1983,24 @@ function writeLeaderStyle( dictionary: string, textStyle: string, linetype: string, + content: string | undefined, ): void { const sizes = leaderSizes({}, style); const scale = written(style.scale ?? 1); const attachment = attachmentCode(leaderAttachment({}, style)); + const vertical = verticalAttachmentCode(leaderVerticalAttachment({}, style)); const block = leaderArrowheadInfo(style.arrowhead ?? DEFAULT_LEADER_ARROWHEAD)?.block; g(0, "MLEADERSTYLE"); ownedBy(g, validLeaderStyleHandle(style.name), dictionary); g(100, "AcDbMLeaderStyle"); g(179, 2); // version - g(170, 2); // content: a text + g(170, content === undefined ? 2 : 1); // content: a text, or a block g(171, 1); // the leader is drawn first g(172, 0); // and from its arrowhead g(90, 2); // the points MLEADER asks for g(40, 0); // angles MLEADER keeps the segments to: none g(41, 0); - g(173, 1); // straight shafts + g(173, style.shaft === "curved" ? 2 : 1); // straight shafts, or curves g(91, COLOR_BY_BLOCK); g(340, linetype); g(92, LINEWEIGHT_BY_BLOCK); @@ -2011,24 +2020,27 @@ function writeLeaderStyle( g(176, 0); // text aligned as its attachment puts it g(93, COLOR_BY_BLOCK); g(45, sizes.textHeight); - g(292, 0); // no frame + g(292, style.frame === true ? 1 : 0); g(297, 0); // a note on the left is justified right g(46, 0.18 * scale); // the spacing MLEADERALIGN offers, as the leading CAD app's Standard style has it + // The block as the drawing names it, whose record's handle comes from that name. + if (content !== undefined) g(343, blockHandles(content).record); g(94, COLOR_BY_BLOCK); - g(47, 1); // the block's scale - g(49, 1); - g(140, 1); + const blockScale = written(style.blockScale ?? 1); + g(47, blockScale); // the block's scale + g(49, blockScale); + g(140, blockScale); g(293, 1); g(141, 0); // the block's rotation g(294, 1); - g(177, 0); // a block connects by its extents + g(177, style.blockConnection === "insertion" ? 1 : 0); // by its extents, or its insertion point g(142, 1); // scale g(295, 0); g(296, 0); // not annotative g(143, 0.125 * scale); // the size of a break DIMBREAK makes, as the leading CAD app's Standard style has it - g(271, 0); // the landing meets the note at its side - g(272, 9); - g(273, 9); + g(271, style.direction === "vertical" ? 1 : 0); + g(272, vertical); + g(273, vertical); g(298, 0); } @@ -2046,6 +2058,8 @@ function writeLeader( readonly handle: string; readonly owner: string; readonly paper: boolean; + /** The block of the drawing of a name, for a block in place of the note. */ + readonly findBlock: (name: string) => Block | undefined; /** The text style of its note, unless it is `Standard`, and its handle. */ readonly textStyle: TextStyle | undefined; readonly textStyleHandle: string; @@ -2053,11 +2067,18 @@ function writeLeader( readonly linetype: string; }, ): void { - const picture = leaderPicture(e, style, where.textStyle); + const picture = leaderPicture(e, style, where.textStyle, where.findBlock); const { sizes } = picture; + const content = picture.block; + const byInsertion = style.blockConnection === "insertion" ? 1 : 0; const attachment = attachmentCode(picture.attachment); + const vertical = verticalAttachmentCode(picture.verticalAttachment); const left = picture.side === "left"; + // A block in place of the note keeps a note's default alignment. + const align = content !== undefined ? 0 : picture.noteAttachment === 2 ? 1 : left ? 2 : 0; const block = leaderArrowheadInfo(style.arrowhead ?? DEFAULT_LEADER_ARROWHEAD)?.block; + const mask = picture.mask; + const maskColor = mask?.color; g(0, "MULTILEADER"); g(5, where.handle); g(330, where.owner); @@ -2074,34 +2095,69 @@ function writeLeader( g(145, sizes.gap); g(174, attachment); g(175, attachment); - g(176, left ? 2 : 0); // justified right, or left - g(177, 0); - g(290, 1); // the content is a text - g(304, dxfOnce(e.text.join("\\P"))); - point3(g, 11, 0, 0, 1); // the text's normal - g(340, where.textStyleHandle); - point3(g, 12, ...picture.location, 0); - point3(g, 13, 1, 0, 0); // along the text - g(42, 0); // rotation - g(43, 0); // no width to wrap at - g(44, 0); - g(45, 1); // line spacing - g(170, 1); // at least as set - g(90, COLOR_BY_LAYER); - g(171, left ? 3 : 1); // held by its top right, or top left - g(172, 5); // flow - g(91, COLOR_BY_LAYER); // no background - g(141, 0); - g(92, 0); - g(291, 0); - g(292, 0); - g(173, 0); // no columns - g(293, 0); - g(142, 0); - g(143, 0); - g(294, 0); - g(295, 0); - g(296, 0); // no block + g(176, align); // justified left, centered or right + g(177, content === undefined ? 0 : byInsertion); + if (content !== undefined) { + // A block in place of the note, where it is placed, and the matrix that places it. + const scale = content.scale?.[0] ?? 1; + g(290, 0); + g(296, 1); + g(341, blockHandles(content.block).record); + point3(g, 14, 0, 0, 1); + point3(g, 15, ...content.at, 0); + point3(g, 16, scale, scale, scale); + g(46, 0); + g(93, COLOR_BY_LAYER); + for (const value of [ + scale, + 0, + 0, + content.at[0], + 0, + scale, + 0, + content.at[1], + 0, + 0, + scale, + 0, + 0, + 0, + 0, + 1, + ]) { + g(47, value); + } + } + if (content === undefined) { + g(290, 1); // the content is a text + g(304, dxfOnce(picture.note.value)); + point3(g, 11, 0, 0, 1); // the text's normal + g(340, where.textStyleHandle); + point3(g, 12, ...picture.location, 0); + point3(g, 13, 1, 0, 0); // along the text + g(42, 0); // rotation + g(43, picture.note.width ?? 0); // the width it wraps at + g(44, 0); + g(45, 1); // line spacing + g(170, 1); // at least as set + g(90, COLOR_BY_LAYER); + g(171, picture.noteAttachment); // held by its top left, top center or top right + g(172, 5); // flow + // A mask in the drawing's background, or in a color of its own. + g(91, maskColor === undefined || maskColor === 256 ? COLOR_BY_LAYER : aciColor(maskColor)); + g(141, mask?.factor ?? 0); + g(92, 0); + g(291, mask !== undefined && maskColor === undefined ? 1 : 0); + g(292, mask === undefined ? 0 : 1); + g(173, 0); // no columns + g(293, 0); + g(142, 0); + g(143, 0); + g(294, 0); + g(295, 0); + g(296, 0); // no block + } // The plane the leader is drawn in, from the first tip, as the leading CAD app's MLEADER sets it. const tip = e.shafts[0]![0]!; point3(g, 110, tip[0], tip[1], 0); @@ -2121,14 +2177,32 @@ function writeLeader( g(91, i); g(305, "}"); }); - g(271, 0); // the landing meets the note at its side + g(271, picture.vertical ? 1 : 0); // the landing meets the note at its side, or its top or bottom g(303, "}"); - g(272, 9); - g(273, 9); + // A second root on the note's far side, its lines numbered on from the first root's. + if (picture.farConnection !== undefined) { + g(302, "LEADER{"); + g(290, 1); + g(291, 1); + point3(g, 10, ...picture.farConnection, 0); + point3(g, 11, picture.farDirection ?? -picture.direction, 0, 0); + g(90, 1); // the root's index + g(40, sizes.landing); + (e.farShafts ?? []).forEach((shaft, j) => { + g(304, "LEADER_LINE{"); + for (const [x, y] of shaft) point3(g, 10, x, y, 0); + g(91, e.shafts.length + j); + g(305, "}"); + }); + g(271, picture.vertical ? 1 : 0); + g(303, "}"); + } + g(272, vertical); + g(273, vertical); g(301, "}"); g(340, validLeaderStyleHandle(style.name)); - g(90, leaderOwnFlags(e)); - g(170, 1); // straight shafts + g(90, leaderOwnFlags(e, style)); + g(170, picture.curved ? 2 : 1); // straight shafts, or curves g(91, COLOR_BY_BLOCK); g(341, where.linetype); g(171, LINEWEIGHT_BY_BLOCK); @@ -2137,29 +2211,45 @@ function writeLeader( g(41, sizes.landing); if (block !== undefined) g(342, blockHandles(block).record); g(42, sizes.arrowSize); - g(172, 2); // content: a text + g(172, content === undefined ? 2 : 1); // content: a text, or a block g(343, where.textStyleHandle); g(173, attachment); g(95, attachment); g(174, 1); // level text - g(175, left ? 2 : 0); + g(175, content === undefined && left ? 2 : 0); g(92, COLOR_BY_BLOCK); - g(292, 0); + g(292, picture.frame === undefined ? 0 : 1); + if (content !== undefined) g(344, blockHandles(content.block).record); g(93, COLOR_BY_BLOCK); point3(g, 10, 1, 1, 1); // the block's scale g(43, 0); - g(176, 0); + g(176, content === undefined ? 0 : byInsertion); g(293, 0); // not annotative + // Each attribute of a block in place of the note, by its definition, and its value. + if (content !== undefined) { + const block = where.findBlock(content.block); + (block?.attributes ?? []).forEach((definition, i) => { + g(330, definitionHandle(block!.name, definition.tag)); + g(177, i + 1); + g(44, 0); + g(302, dxfText(content.attributes?.[definition.tag] ?? definition.value)); + }); + } g(294, 0); g(178, 0); - g(179, left ? 3 : 1); // justified right, or left + g(179, content === undefined ? noteAttachmentPoint(picture.side, e.width !== undefined) : 1); g(45, 1); // scale - g(271, 0); - g(272, 9); - g(273, 9); + g(271, picture.vertical ? 1 : 0); + g(272, vertical); + g(273, vertical); g(295, 0); } +/** A color index as a multileader holds it: the index in the low byte of a color by index. */ +function aciColor(index: number): number { + return 0xc3000000 | index | 0; +} + /** One entity of the block of a leader's arrowhead, on layer `0` and ByBlock. */ function writeArrowheadStroke( g: Group, diff --git a/src/extents.ts b/src/extents.ts index 3345cd7..9b3797a 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -212,17 +212,21 @@ export function boxer( readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; readonly leaderStyles: ReadonlyMap; + /** The blocks a leader's content names. */ + readonly blocks: ReadonlyMap; } const namesOf = ( text: readonly TextStyle[] | undefined, dimensions: readonly DimensionStyle[] | undefined, leaders: readonly LeaderStyle[] | undefined, + blocks: readonly Block[] | undefined, ): Names => ({ textStyles: new Map(filled(text).map((t) => [layerKey(t.name), t])), dimensionStyles: new Map(filled(dimensions).map((style) => [layerKey(style.name), style])), leaderStyles: new Map(filled(leaders).map((style) => [layerKey(style.name), style])), + blocks: new Map(filled(blocks).map((block) => [layerKey(block.name), block])), }); - const own = namesOf(textStyles, dimensionStyles, leaderStyles); + const own = namesOf(textStyles, dimensionStyles, leaderStyles, blocks); // The names of each referenced drawing, worked out when one of its entities is first met. const referenced = new Map(); const byDrawing = new Map(); @@ -232,8 +236,8 @@ export function boxer( if (!found) { found = byDrawing.get(from.drawing); if (!found) { - const { textStyles, dimensionStyles, leaderStyles } = from.drawing; - found = namesOf(textStyles, dimensionStyles, leaderStyles); + const { textStyles, dimensionStyles, leaderStyles, blocks } = from.drawing; + found = namesOf(textStyles, dimensionStyles, leaderStyles, blocks); byDrawing.set(from.drawing, found); } referenced.set(from, found); @@ -439,7 +443,7 @@ export function boxer( if (style === undefined) return box; const named = e.textStyle ?? style.textStyle; const textStyle = named === undefined ? undefined : from.textStyles.get(key(named)); - const picture = leaderPicture(e, style, textStyle); + const picture = leaderPicture(e, style, textStyle, (name) => from.blocks.get(key(name))); for (const shaft of picture.shafts) for (const p of shaft) add(...p); for (const arrowhead of picture.arrowheads) { for (const p of arrowhead.filled) add(...p); @@ -452,20 +456,19 @@ export function boxer( add(center[0] + radius, center[1] + radius); } } - for (const p of picture.landing ?? []) add(...p); - for (const line of picture.lines) { - const text: Text = { - kind: "text", - layer: e.layer, - at: line.at, - height: line.height, - value: line.value, - rotation: 0, - ...(line.align === "right" ? { align: "right" as const } : {}), - ...(named === undefined ? {} : { style: named }), - }; - shape(text, from, add); + for (const p of [...(picture.landing ?? []), ...(picture.farLanding ?? [])]) add(...p); + for (const [a, b] of picture.underlines) { + add(...a); + add(...b); + } + for (const p of picture.frame ?? []) add(...p); + for (const p of picture.mask?.corners ?? []) add(...p); + // A block in place of the note: the box of its outline, as the picture places it. + if (picture.block !== undefined) { + add(picture.box[0], picture.box[1]); + add(picture.box[2], picture.box[3]); } + shape(picture.note, from, add); return box; }; diff --git a/src/index.ts b/src/index.ts index b86d8ed..0021def 100644 --- a/src/index.ts +++ b/src/index.ts @@ -81,6 +81,9 @@ export { type LayoutOptions, type Leader, type LeaderAttachment, + type LeaderDirection, + type LeaderMask, + type LeaderVerticalAttachment, type LeaderOptions, type LeaderSide, type LeaderStyle, @@ -182,7 +185,10 @@ export { leaderSizes, leaderStyleDictionaryHandle, leaderStyleHandle, + leaderVerticalAttachment, + noteAttachmentPoint, STANDARD_LEADER_STYLE_SIZES, + verticalAttachmentCode, type LeaderArrowheadDrawn, type LeaderLine, type LeaderPicture, @@ -289,7 +295,15 @@ export type { WidthFactor, XrefPath, } from "./rules.ts"; -export { LINE_SPACING_RANGE, XREF_DEPTH } from "./rules.ts"; +export { + LEADER_ATTACHMENTS, + LEADER_DIRECTIONS, + LEADER_SHAFT_KINDS, + LEADER_SIDES, + LEADER_VERTICAL_ATTACHMENTS, + LINE_SPACING_RANGE, + XREF_DEPTH, +} from "./rules.ts"; export { BUILT_IN_STANDARD, defineStandard, type BuiltInStandard } from "./standard/define.ts"; export type { Box, diff --git a/src/inspect.ts b/src/inspect.ts index c76e13e..3a8f6f5 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -21,8 +21,8 @@ import type { Insert, Leader, LeaderStyle, + Paragraph, Point, - Text, TextStyle, } from "./drawing.ts"; import { written } from "./format.ts"; @@ -241,38 +241,20 @@ export function inspectWithin( const repeats = leaderRepeats(); const notes = new WeakMap< Leader, - { style: LeaderStyle; textStyle: TextStyle | undefined; texts: Text[]; cost: number } + { style: LeaderStyle; textStyle: TextStyle | undefined; texts: Paragraph[]; cost: number } >(); - const noteOf = ( - leader: Leader, - style: LeaderStyle, - named: string | undefined, - textStyle: TextStyle | undefined, - ) => { + /** A leader's note, as the paragraph it is laid out as, where its picture holds it. */ + const noteOf = (leader: Leader, style: LeaderStyle, textStyle: TextStyle | undefined) => { const known = notes.get(leader); if (known?.style === style && known.textStyle === textStyle) return known; - const texts: Text[] = []; // A leader that shares its shafts or its note with another is read again, and paid for. const again = repeats(leader); - if (again > 0 && !walk(again)) return { style, textStyle, texts, cost: 0 }; - let characters = 0; - for (const line of leaderPicture(leader, style, textStyle).lines) { - if (line.value.trim() === "") continue; - characters += line.value.length; - texts.push({ - kind: "text", - layer: leader.layer, - at: line.at, - height: line.height, - value: line.value, - rotation: 0, - ...(line.align === "right" ? { align: "right" as const } : {}), - ...(named === undefined ? {} : { style: named }), - }); - } - const note = { style, textStyle, texts, cost: Math.floor((texts.length + characters) / 32) }; - notes.set(leader, note); - return note; + if (again > 0 && !walk(again)) return { style, textStyle, texts: [], cost: 0 }; + const note = leaderPicture(leader, style, textStyle).note; + const texts = note.value.trim() === "" ? [] : [note]; + const result = { style, textStyle, texts, cost: Math.floor(note.value.length / 32) }; + notes.set(leader, result); + return result; }; const space = (entities: readonly Entity[], layout?: string, paper?: Box): void => { @@ -295,7 +277,7 @@ export function inspectWithin( if (style === undefined) return; const named = drawn.textStyle ?? style.textStyle; const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); - const note = noteOf(drawn, style, named, textStyle); + const note = noteOf(drawn, style, textStyle); // The note is read again for each place it is drawn. if (!walk(note.cost)) return; for (const text of note.texts) keep(text, index, matrix, from, attribute); diff --git a/src/leaders.ts b/src/leaders.ts index 263624a..325181c 100644 --- a/src/leaders.ts +++ b/src/leaders.ts @@ -13,19 +13,29 @@ import { import { blockHandles } from "./blocks.ts"; import { arrowheadEntityHandle } from "./dimensions.ts"; import type { + Block, Drawing, + Entity, + Insert, Leader, LeaderAttachment, LeaderSide, LeaderStyle, + LeaderVerticalAttachment, + Paragraph, Point, TextStyle, } from "./drawing.ts"; import { written } from "./format.ts"; import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; -import { lineSpacing, measureText } from "./measure.ts"; -import { leaderStyleNameProblem, pictureNumberProblem } from "./rules.ts"; +import { layoutParagraph, paragraphInStyle, placer } from "./paragraphs.ts"; +import { + LEADER_ATTACHMENTS, + LEADER_SHAFT_LENGTH, + leaderStyleNameProblem, + pictureNumberProblem, +} from "./rules.ts"; import { filled, Strings } from "./shape.ts"; /** The shortest line of a note that `leaderRepeats` tells apart by its value. */ @@ -33,9 +43,9 @@ const LONG = 256; /** * For the leaders of one call, what reading a leader again costs when it shares its list of - * shafts, a shaft, its note or a line of `LONG` characters or more with a leader read before, as - * a drawing made in code may: a unit for each shaft, each point and each line, and one for each - * 32 characters a line holds. 0 for a leader that shares none, whose lists the drawing holds. + * shafts, a shaft, its note, its block's values or a line of `LONG` characters or more with a + * leader read before, as a drawing made in code may: a unit for each shaft, each point, each line, + * tag and value, and one for each 32 characters a line, tag or value holds. 0 for a leader that shares none, whose lists the drawing holds. */ export function leaderRepeats(): (leader: Leader) => number { const lists = new WeakMap(); @@ -70,10 +80,32 @@ export function leaderRepeats(): (leader: Leader) => number { if (long) lines.set(value, true); return [1 + Math.floor(value.length / 32), again]; }; + // The values of a block in place of the note, by their tags, read once for each object: each + // tag and value costs as a line does. + const sets = new WeakMap(); + const valuesOf = (set: unknown): [number, boolean] => { + if (typeof set !== "object" || set === null) return [0, false]; + const known = sets.get(set); + if (known) return [known.cost, true]; + let cost = 0; + let shares = false; + for (const [tag, value] of Object.entries(set)) { + const [ofTag, sharedTag] = line(tag); + const [ofValue, sharedValue] = line(value); + cost += ofTag + ofValue; + shares ||= sharedTag || sharedValue; + } + sets.set(set, { cost, shares }); + return [cost, shares]; + }; return (leader) => { const [ofShafts, sharedShafts] = read(leader.shafts, shaft); + const [ofFar, sharedFar] = read(leader.farShafts, shaft); const [ofText, sharedText] = read(leader.text, line); - return sharedShafts || sharedText ? ofShafts + ofText : 0; + const [ofValues, sharedValues] = valuesOf(leader.attributes); + return sharedShafts || sharedFar || sharedText || sharedValues + ? ofShafts + ofFar + ofText + ofValues + : 0; }; } @@ -229,19 +261,7 @@ export function leaderSizes( }; } -/** - * The side of `at` a leader's note is on: its own, or else the side away from the first shaft's - * last point before `at`, right when `at` is not to the left of it, as written. A list is read up - * to its first empty slot. - */ -export function leaderSide(leader: Pick): LeaderSide { - if (leader.side !== undefined) return leader.side; - const shaft = filled(filled(leader.shafts)[0]); - const before = shaft[shaft.length - 1]; - return before === undefined || written(leader.at[0]) >= written(before[0]) ? "right" : "left"; -} - -/** Which line of the note the landing of a leader in this style meets. */ +/** Where the landing of a leader in this style meets the side of its note. */ export function leaderAttachment( leader: Pick, style: Pick, @@ -255,17 +275,26 @@ export function leaderAttachment( * `LEADER_OWN_ALWAYS`. */ const OWN = { + shaft: 1 << 0, gap: 1 << 5, landing: 1 << 7, arrowSize: 1 << 9, textStyle: 1 << 11, leftAttachment: 1 << 12, textHeight: 1 << 16, + frame: 1 << 17, rightAttachment: 1 << 25, + /** Set on every multileader whose note is above or below its point, as the CAD app's command sets it. */ + vertical: 1 << 26, + direction: 1 << 27, + topAttachment: 1 << 28, + bottomAttachment: 1 << 29, } as const; /** The bits every multileader the writers write holds: its content, its text's alignment, and its text. */ const LEADER_OWN_ALWAYS = (1 << 10) | (1 << 14) | (1 << 18); +/** The bits every multileader whose content is a block holds: its content, the block, its scale and its rotation. */ +const BLOCK_OWN_ALWAYS = (1 << 10) | (1 << 19) | (1 << 21) | (1 << 22); /** * The flags of the properties a multileader sets itself, as the writers write them: the three @@ -273,29 +302,75 @@ const LEADER_OWN_ALWAYS = (1 << 10) | (1 << 14) | (1 << 18); * A leader's own attachment sets the attachment of both sides. */ export function leaderOwnFlags( - leader: Pick, + leader: Pick< + Leader, + | "textStyle" + | "textHeight" + | "arrowSize" + | "landing" + | "gap" + | "attachment" + | "frame" + | "side" + | "verticalAttachment" + | "width" + | "shaft" + | "block" + | "text" + >, + style?: Pick, ): number { - let flags = LEADER_OWN_ALWAYS; + let flags = leaderBlock(leader, style) === undefined ? LEADER_OWN_ALWAYS : BLOCK_OWN_ALWAYS; if (leader.gap !== undefined) flags |= OWN.gap; if (leader.landing !== undefined) flags |= OWN.landing; if (leader.arrowSize !== undefined) flags |= OWN.arrowSize; if (leader.textStyle !== undefined) flags |= OWN.textStyle; if (leader.textHeight !== undefined) flags |= OWN.textHeight; if (leader.attachment !== undefined) flags |= OWN.leftAttachment | OWN.rightAttachment; + if (leader.frame !== undefined) flags |= OWN.frame; + if (leader.shaft !== undefined) flags |= OWN.shaft; + if (leader.verticalAttachment !== undefined) flags |= OWN.topAttachment | OWN.bottomAttachment; + const vertical = leader.side === "above" || leader.side === "below"; + if (leader.side !== undefined && vertical !== (style?.direction === "vertical")) { + flags |= OWN.direction; + } + if ( + leader.width === undefined && + (vertical || (leader.side === undefined && style?.direction === "vertical")) + ) { + flags |= OWN.vertical; + } return flags; } -/** How a multileader and its style name the line of the note the landing meets. */ -export function attachmentCode(attachment: LeaderAttachment): 1 | 3 { - return attachment === "first-line" ? 1 : 3; +/** How a multileader and its style number where the landing meets the side of the note. */ +export function attachmentCode(attachment: LeaderAttachment): number { + const code = LEADER_ATTACHMENTS.indexOf(attachment); + return code < 0 ? 1 : code; +} + +/** How a multileader and its style number where the landing meets a note above or below it. */ +export function verticalAttachmentCode(attachment: LeaderVerticalAttachment): 9 | 10 { + return attachment === "line" ? 10 : 9; +} + +/** + * The justification a multileader holds of its own, group 179, which its MTEXT's attachment, the + * picture's `noteAttachment`, need not be: 1 left, 3 right, 8 and 2 for a note above and below, + * and 1 for a note that wraps, as the leading CAD app holds one whose box was drawn. + */ +export function noteAttachmentPoint(side: LeaderSide, wraps: boolean): 1 | 2 | 3 | 8 { + // A note that wraps holds it as the leading CAD app holds one whose box was drawn. + if (wraps) return 1; + return side === "right" ? 1 : side === "left" ? 3 : side === "above" ? 8 : 2; } /** One line of a leader's note, as the leading CAD app draws it. */ export interface LeaderLine { readonly value: string; - /** The end of its baseline it is justified to: the left end, or the right end. */ + /** Where its first character is placed, on its baseline. */ readonly at: Point; - readonly align: "left" | "right"; + readonly align: "left"; /** The height of its capitals, in the units of the leader's space. */ readonly height: number; } @@ -313,35 +388,423 @@ export interface LeaderArrowheadDrawn { /** * What the leading CAD app draws for a leader, in the coordinates of the leader's space, with every - * number of the leader and of its style taken as the writers write it, and - * the numbers a file holds for it. + * number of the leader and of its style taken as the writers write it, and the numbers a file + * holds for it. */ export interface LeaderPicture { readonly sizes: LeaderSizes; readonly side: LeaderSide; readonly attachment: LeaderAttachment; + readonly verticalAttachment: LeaderVerticalAttachment; + /** True when the landing meets the note's top or bottom: a note above or below `at`. */ + readonly vertical: boolean; /** Where the shafts meet and the landing starts: `at`, as written. */ readonly connection: Point; - /** Along X, the way the landing runs: 1 to the right, -1 to the left. */ + /** + * Along X, the way the landing runs: 1 to the right, -1 to the left. For a note above, 1, and + * below, -1, as the file holds it. + */ readonly direction: 1 | -1; /** Each shaft as the leading CAD app draws it: from where its arrowhead leaves it, through its bends, to `connection`. */ readonly shafts: readonly (readonly Point[])[]; /** Each shaft's arrowhead. None for an arrow size of 0. */ readonly arrowheads: readonly LeaderArrowheadDrawn[]; - /** The landing, or undefined for a landing of 0. */ + /** The landing, or undefined for a landing of 0, a note above or below, and curved shafts. */ readonly landing?: readonly [Point, Point]; + /** Where the shafts of a second root on the note's far side meet, and the way its landing runs. */ + readonly farConnection?: Point; + readonly farDirection?: 1 | -1; + /** The second root's landing, as `landing` is the first's. */ + readonly farLanding?: readonly [Point, Point]; + /** True for shafts drawn as curves, each a list of points close enough to plot as the curve. */ + readonly curved: boolean; /** - * The corner of the note's box the landing side holds it by, at the top of its first line's - * capitals: its left for a note on the right, and its right for a note on the left. + * The note: a paragraph of its lines joined by `\P`, held at `location` by the top left of its + * box for a note on the right, the top right on the left, and the top center above or below. */ + readonly note: Paragraph; + /** How the note is held at `location`: 1 top left, 2 top center, 3 top right, as an MTEXT. */ + readonly noteAttachment: 1 | 2 | 3; + /** Where the note is held. */ readonly location: Point; - /** The left end of the note, its gap before it, at the height the landing meets the note. */ + /** Where the file says the note's content starts: past the landing, before the note on the left. */ readonly contentBase: Point; - /** Each line of the note, from the top. */ + /** The note's box, `[left, bottom, right, top]`: its widest line across, its lines down. */ + readonly box: readonly [number, number, number, number]; + /** Each line its attachment draws under or over the note. */ + readonly underlines: readonly (readonly [Point, Point])[]; + /** The frame around the note, its lower left corner first and counterclockwise. */ + readonly frame?: readonly [Point, Point, Point, Point]; + /** The mask behind the note, its lower left corner first and counterclockwise, and its color: the background unless given. */ + readonly mask?: { + readonly corners: readonly [Point, Point, Point, Point]; + readonly color?: number; + /** How far it reaches past the note: its factor of the text height, less one, each side. */ + readonly factor: number; + }; + /** The block in place of the note, as an insert of it, with its attributes. */ + readonly block?: Insert; + /** Each line of the note, from the top, by its first run. */ readonly lines: readonly LeaderLine[]; } const RADIANS = Math.PI / 180; +/** How far below a line's baseline an attachment's underline runs, in text heights. */ +const UNDERLINE = 0.2; +/** How far below the top of the note the first line's underline runs, in text heights. */ +const FIRST_UNDERLINE = 1.2; +/** A mask's factor of the text height unless given, as the leading CAD app sets one. */ +const MASK_FACTOR = 1.5; + +/** A block's own outline, as a block in place of a leader's note is placed by it. */ +interface Outline { + /** Its box, `[left, bottom, right, top]`, from its base point, or undefined when it draws nothing. */ + readonly box: readonly [number, number, number, number] | undefined; + /** Where it crosses the level line through its base point: the least and the greatest X. */ + readonly crossing: readonly [number, number] | undefined; +} + +const outlines = new WeakMap(); + +/** An affine map of a point, `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f. */ +type Affine = readonly [number, number, number, number, number, number]; + +const compose = (m: Affine, n: Affine): Affine => [ + m[0] * n[0] + m[2] * n[1], + m[1] * n[0] + m[3] * n[1], + m[0] * n[2] + m[2] * n[3], + m[1] * n[2] + m[3] * n[3], + m[0] * n[4] + m[2] * n[5] + m[4], + m[1] * n[4] + m[3] * n[5] + m[5], +]; + +/** A number of a block's data, or NaN for any other value, which the outline leaves out. */ +const num = (value: unknown): number => (typeof value === "number" ? value : Number.NaN); + +/** How many blocks deep the outline follows the inserts a block holds. */ +const OUTLINE_DEPTH = 8; + +/** + * The outline of a block's lines, polylines, circles and arcs, and of the blocks it inserts, up to + * `OUTLINE_DEPTH` deep, worked out once for each block: their box, and where they cross + * the level line through the base point. Text takes no part, nor anything past the first + * `OUTLINE_ITEMS` read at any depth. + */ +function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined): Outline { + const entities = block.entities as unknown; + if (typeof entities !== "object" || entities === null) + return { box: undefined, crossing: undefined }; + const known = outlines.get(block); + if (known) return known; + let box: [number, number, number, number] | undefined; + let crossing: [number, number] | undefined; + const add = (x: number, y: number): void => { + if (!Number.isFinite(x) || !Number.isFinite(y)) return; + box = box + ? [Math.min(box[0], x), Math.min(box[1], y), Math.max(box[2], x), Math.max(box[3], y)] + : [x, y, x, y]; + }; + const cross = (x: number): void => { + if (!Number.isFinite(x)) return; + crossing = crossing ? [Math.min(crossing[0], x), Math.max(crossing[1], x)] : [x, x]; + }; + const segment = (a: Point, b: Point): void => { + add(a[0], a[1]); + add(b[0], b[1]); + if ((a[1] <= 0 && b[1] >= 0) || (a[1] >= 0 && b[1] <= 0)) { + if (a[1] === b[1]) { + cross(a[0]); + cross(b[0]); + } else cross(a[0] + ((b[0] - a[0]) * -a[1]) / (b[1] - a[1])); + } + }; + let read = 0; + const open = new Set(); + const walk = (inner: Block, m: Affine, depth: number): void => { + const map = (p: unknown): Point => + Array.isArray(p) + ? [m[0] * num(p[0]) + m[2] * num(p[1]) + m[4], m[1] * num(p[0]) + m[3] * num(p[1]) + m[5]] + : [Number.NaN, Number.NaN]; + // An arc as short chords, close enough to place a block by. + const round = (center: unknown, r: number, from = 0, to = 360): void => { + if (!Array.isArray(center)) return; + const sweep = (((to - from) % 360) + 360) % 360 || 360; + const steps = 64; + let last: Point | undefined; + for (let i = 0; i <= steps; i++) { + const t = ((from + (sweep * i) / steps) * Math.PI) / 180; + const p = map([num(center[0]) + r * Math.cos(t), num(center[1]) + r * Math.sin(t)]); + if (last) segment(last, p); + last = p; + } + }; + // A side with a bulge as the arc it is: a quarter of its turn's tangent, counterclockwise when above 0. + const bulged = (a: unknown, b: unknown, bulge: number): void => { + if (!Array.isArray(a) || !Array.isArray(b)) return; + const [ax, ay, bx, by] = [num(a[0]), num(a[1]), num(b[0]), num(b[1])]; + const turn = 4 * Math.atan(bulge); + const [dx, dy] = [bx - ax, by - ay]; + const chord = Math.hypot(dx, dy); + if (!(chord > 0)) return; + // The center is off the chord's middle, to its left, by half the chord times cot(turn / 2). + const off = ((1 - bulge * bulge) / (2 * bulge)) * (chord / 2); + const [cx, cy] = [(ax + bx) / 2 - (dy / chord) * off, (ay + by) / 2 + (dx / chord) * off]; + const r = Math.hypot(ax - cx, ay - cy); + const from = Math.atan2(ay - cy, ax - cx); + const steps = 32; + let last = map([ax, ay]); + for (let i = 1; i <= steps; i++) { + const t = from + (turn * i) / steps; + const p = map([cx + r * Math.cos(t), cy + r * Math.sin(t)]); + segment(last, p); + last = p; + } + }; + open.add(inner); + for (const e of filled(inner.entities as readonly Entity[])) { + if (++read > OUTLINE_ITEMS) break; + if (typeof e !== "object" || e === null) continue; + if (e.kind === "line") segment(map(e.from), map(e.to)); + else if (e.kind === "polyline") { + const points = filled(e.points).slice(0, OUTLINE_ITEMS); + const bulges = filled(e.bulges); + read += points.length; + const sides = e.closed && points.length > 2 ? points.length : points.length - 1; + for (let i = 0; i < sides; i++) { + const [a, b] = [points[i]!, points[(i + 1) % points.length]!]; + const bulge = num(bulges[i] ?? 0); + if (!bulge || !Number.isFinite(bulge)) segment(map(a), map(b)); + else bulged(a, b, bulge); + } + } else if (e.kind === "circle") round(e.center, num(e.radius)); + else if (e.kind === "arc") round(e.center, num(e.radius), num(e.startAngle), num(e.endAngle)); + else if (e.kind === "insert" && depth < OUTLINE_DEPTH && typeof e.block === "string") { + const nested = findBlock?.(e.block); + if (nested === undefined || open.has(nested)) continue; + const [sx, sy] = Array.isArray(e.scale) ? e.scale : [1, 1]; + const turn = ((num(e.rotation ?? 0) || 0) * Math.PI) / 180; + const [cos, sin] = [Math.cos(turn), Math.sin(turn)]; + const [bx, by] = Array.isArray(nested.base) ? nested.base : [0, 0]; + const [ax, ay] = Array.isArray(e.at) ? e.at : [0, 0]; + // Its block's base point to its point, scaled and turned. + const placed: Affine = [ + cos * num(sx), + sin * num(sx), + -sin * num(sy), + cos * num(sy), + num(ax) - (cos * num(sx) * num(bx) - sin * num(sy) * num(by)), + num(ay) - (sin * num(sx) * num(bx) + cos * num(sy) * num(by)), + ]; + walk(nested, compose(m, placed), depth + 1); + } + } + open.delete(inner); + }; + const [bx, by] = Array.isArray(block.base) ? block.base : [0, 0]; + walk(block, [1, 0, 0, 1, -num(bx), -num(by)], 0); + const outline = { box, crossing }; + outlines.set(block, outline); + return outline; +} + +/** How many entities of a block, and points of a polyline, the outline reads. */ +const OUTLINE_ITEMS = 4096; + +/** How many straight pieces each span of a curved shaft is drawn with. */ +const CURVE_PIECES = 32; + +/** + * A curved shaft as the leading CAD app draws one, as points close enough to plot as the curve: + * the cubic through `fit` with knots spaced by the distance between its points, which leaves its + * first point along `start` and meets its last along `end`, each a unit vector and each its + * derivative there. Two points of the fit at one place count once. + */ +export function curveThrough(fit: readonly Point[], start: Point, end: Point): Point[] { + const q: Point[] = []; + for (const p of fit) { + const last = q[q.length - 1]; + if (last === undefined || Math.hypot(p[0] - last[0], p[1] - last[1]) > 0) q.push(p); + } + if (q.length < 2) return [...q]; + const n = q.length - 1; + const u = [0]; + for (let k = 1; k <= n; k++) + u.push(u[k - 1]! + Math.hypot(q[k]![0] - q[k - 1]![0], q[k]![1] - q[k - 1]![1])); + const total = u[n]!; + // The knots: four at each end, and each inner point's distance along the fit. + const knots = [0, 0, 0, 0, ...u.slice(1, n), total, total, total, total]; + // The control points: the ends, the two that set the derivatives there, and the rest solved + // so that the curve passes through each inner point, a system of three diagonals. + const p: Point[] = Array.from({ length: n + 3 }, (): Point => [0, 0]); + p[0] = q[0]!; + p[1] = [q[0]![0] + (knots[4]! / 3) * start[0], q[0]![1] + (knots[4]! / 3) * start[1]]; + p[n + 2] = q[n]!; + p[n + 1] = [ + q[n]![0] - ((total - knots[n + 2]!) / 3) * end[0], + q[n]![1] - ((total - knots[n + 2]!) / 3) * end[1], + ]; + if (n > 1) { + // Row k, for the inner point k, holds the weights of control points k, k + 1 and k + 2. + const rows = []; + for (let k = 1; k < n; k++) rows.push(basisAt(knots, k + 3, u[k]!)); + const unknown = n - 1; + const a = rows.map((r) => r[0]); + const b = rows.map((r) => r[1]); + const c = rows.map((r) => r[2]); + const dx = rows.map((_, i) => q[i + 1]![0]); + const dy = rows.map((_, i) => q[i + 1]![1]); + // The known control points move to the right side. + dx[0]! -= a[0]! * p[1]![0]; + dy[0]! -= a[0]! * p[1]![1]; + dx[unknown - 1]! -= c[unknown - 1]! * p[n + 1]![0]; + dy[unknown - 1]! -= c[unknown - 1]! * p[n + 1]![1]; + for (let i = 1; i < unknown; i++) { + const m = a[i]! / b[i - 1]!; + b[i]! -= m * c[i - 1]!; + dx[i]! -= m * dx[i - 1]!; + dy[i]! -= m * dy[i - 1]!; + } + const xs: number[] = Array.from({ length: unknown }, () => 0); + const ys: number[] = Array.from({ length: unknown }, () => 0); + xs[unknown - 1] = dx[unknown - 1]! / b[unknown - 1]!; + ys[unknown - 1] = dy[unknown - 1]! / b[unknown - 1]!; + for (let i = unknown - 2; i >= 0; i--) { + xs[i] = (dx[i]! - c[i]! * xs[i + 1]!) / b[i]!; + ys[i] = (dy[i]! - c[i]! * ys[i + 1]!) / b[i]!; + } + for (let i = 0; i < unknown; i++) p[i + 2] = [xs[i]!, ys[i]!]; + } + // Each span cut into pieces, by de Boor's evaluation. + const out: Point[] = [q[0]!]; + for (let span = 3; span < n + 3; span++) { + const [from, to] = [knots[span]!, knots[span + 1]!]; + if (!(to > from)) continue; + for (let i = 1; i <= CURVE_PIECES; i++) { + const t = from + ((to - from) * i) / CURVE_PIECES; + const d: Point[] = [p[span - 3]!, p[span - 2]!, p[span - 1]!, p[span]!]; + for (let r = 1; r <= 3; r++) { + for (let j = 3; j >= r; j--) { + const left = knots[span - 3 + j]!; + const right = knots[span + 1 + j - r]!; + const alpha = right > left ? (t - left) / (right - left) : 0; + d[j] = [ + (1 - alpha) * d[j - 1]![0] + alpha * d[j]![0], + (1 - alpha) * d[j - 1]![1] + alpha * d[j]![1], + ]; + } + } + out.push(i === CURVE_PIECES && span === n + 2 ? q[n]! : d[3]!); + } + } + return out; +} + +/** + * The three cubic B-spline weights not 0 at the knot `knots[span]`, which `t` is: of control + * points span - 3, span - 2 and span - 1. + */ +function basisAt(knots: readonly number[], span: number, t: number): [number, number, number] { + const left = [0, 0, 0, 0]; + const right = [0, 0, 0, 0]; + const n = [1, 0, 0, 0]; + for (let j = 1; j <= 3; j++) { + left[j] = t - knots[span + 1 - j]!; + right[j] = knots[span + j]! - t; + let saved = 0; + for (let r = 0; r < j; r++) { + const denominator = right[r + 1]! + left[j - r]!; + const temp = denominator === 0 ? 0 : n[r]! / denominator; + n[r] = saved + right[r + 1]! * temp; + saved = left[j - r]! * temp; + } + n[j] = saved; + } + // At a knot, the weight of control point span is 0. + return [n[0]!, n[1]!, n[2]!]; +} + +/** + * The side of `at` a leader's note is on: its own, or else, in a horizontal style, the side away + * from the first shaft's last point before `at`, right when `at` is not to the left of it, and in + * a vertical one, above when `at` is not below it, as written. A list is read up to its first + * empty slot. + */ +export function leaderSide( + leader: Pick, + style?: Pick, +): LeaderSide { + if (leader.side !== undefined) return leader.side; + const shaft = filled(filled(leader.shafts)[0]); + const before = shaft[shaft.length - 1]; + if (style?.direction === "vertical") { + return before === undefined || written(leader.at[1]) >= written(before[1]) ? "above" : "below"; + } + return before === undefined || written(leader.at[0]) >= written(before[0]) ? "right" : "left"; +} + +/** Where the landing of a leader in this style meets a note above or below it. */ +export function leaderVerticalAttachment( + leader: Pick, + style: Pick, +): LeaderVerticalAttachment { + return leader.verticalAttachment ?? style.verticalAttachment ?? "center"; +} + +/** + * A leader's mask as it is drawn: none for `false`, and for `true` or an object the drawing's + * background or a color index, and its factor as written. A field the rules refuse is drawn as + * its default, and any other value as no mask. + */ +export function maskOf( + mask: unknown, +): { readonly color?: number; readonly offsetFactor: number } | undefined { + if (mask === true) return { offsetFactor: MASK_FACTOR }; + if (typeof mask !== "object" || mask === null || Array.isArray(mask)) return undefined; + const { color, offsetFactor } = mask as Record; + const factor = + typeof offsetFactor === "number" && Number.isFinite(offsetFactor) + ? written(offsetFactor) + : MASK_FACTOR; + return { + ...(Number.isInteger(color) && (color as number) >= 1 && (color as number) <= 256 + ? { color: color as number } + : {}), + offsetFactor: factor, + }; +} + +/** + * The block a leader holds in place of a note: its own, or its style's for a leader with no note + * of its own, or undefined for a leader whose content is its note. + */ +export function leaderBlock( + leader: Pick, + style: Pick | undefined, +): unknown { + return leader.block ?? (leader.text === undefined ? style?.block : undefined); +} + +/** The note of a leader as the paragraph it is laid out as, before it is placed. */ +export function leaderNote( + leader: Pick, + sizes: LeaderSizes, + scale: number, + textStyleName: string | undefined, + attachment?: LeaderAttachment, +): Omit { + const width = leader.width === undefined ? undefined : written(written(leader.width) * scale); + // A note underlined line by line holds the code that underlines it, as the leading CAD app's does. + const underlined = attachment === "underline-all" ? "\\L" : ""; + return { + kind: "paragraph", + layer: leader.layer, + value: underlined + filled(leader.text).join("\\P"), + height: sizes.textHeight, + rotation: 0, + ...(width === undefined ? {} : { width }), + ...(textStyleName === undefined ? {} : { style: textStyleName }), + }; +} /** * What the leading CAD app draws for a leader in a style, for a leader and a style the rules have @@ -349,9 +812,10 @@ const RADIANS = Math.PI / 180; * points along the shaft's first segment: that app stops the shaft one arrow size short of the tip, * and the arrowhead draws the rest, but for the arrowhead `"none"`, whose shaft runs to the tip. * The landing runs level from `at`, as long as the leader's landing, to the side the note is on. - * The note starts a gap past the landing's end, justified left on the right and right on the left, - * with the middle of its first line's capitals, or of its last line's, level with `at`, and its - * lines `lineSpacing` apart. Each list is read up to its first empty slot. + * The note is a paragraph laid out by `layoutParagraph`, its lines set by their ink: a gap past the + * landing's end, justified left on the right and right on the left, as high as its attachment + * puts it; or a gap above or below `at`, centered on it. Each list is read up to its first empty + * slot. * * @param textStyle - The text style of the leader's note, unless it is `Standard`. */ @@ -359,11 +823,14 @@ export function leaderPicture( leader: Leader, style: LeaderStyle, textStyle?: TextStyle, + findBlock?: (name: string) => Block | undefined, ): LeaderPicture { const sizes = leaderSizes(leader, style); - const side = leaderSide(leader); + const side = leaderSide(leader, style); const attachment = leaderAttachment(leader, style); - const direction = side === "right" ? 1 : -1; + const verticalAttachment = leaderVerticalAttachment(leader, style); + const vertical = side === "above" || side === "below"; + const direction = side === "right" || side === "above" ? 1 : -1; const point = (p: Point): Point => [written(p[0]), written(p[1])]; const connection = point(leader.at); // An arrowhead the rules refuse is drawn as the default. @@ -374,96 +841,283 @@ export function leaderPicture( const shafts: Point[][] = []; const arrowheads: LeaderArrowheadDrawn[] = []; - for (const shaft of filled(leader.shafts)) { - const listed = filled(shaft); - // A shaft with no tip, which the rules refuse, draws nothing. - if (listed.length === 0) continue; - const points = [...listed.map(point), connection]; - const [tip, next] = [points[0]!, points[1]!]; - const length = Math.hypot(tip[0] - next[0], tip[1] - next[1]); - // The way the arrowhead points: from the shaft's next point to its tip. - const along: Point = - length > 0 ? [(tip[0] - next[0]) / length, (tip[1] - next[1]) / length] : [1, 0]; - const across: Point = [-along[1], along[0]]; - const place = ([x, y]: readonly [number, number]): Point => [ - tip[0] + (along[0] * x + across[0] * y) * size, - tip[1] + (along[1] * x + across[1] * y) * size, - ]; - if (size > 0) { - const drawn: { - filled: Point[]; - lines: [Point, Point][]; - disks: { center: Point; radius: number }[]; - } = { filled: [], lines: [], disks: [] }; - if (info.block === undefined) { - drawn.filled.push(tip, place([-1, 1 / 6]), place([-1, -1 / 6])); - } - for (const stroke of info.strokes ?? []) { - if (stroke.kind === "line") drawn.lines.push([place(stroke.from), place(stroke.to)]); - else { - // Two half circles about the middle of its two points, as wide as its width. - const [a, b] = [stroke.points[0]!, stroke.points[1]!]; - const radius = Math.hypot(b[0] - a[0], b[1] - a[1]) / 2 + stroke.width / 2; - drawn.disks.push({ - center: place([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]), - radius: radius * size, - }); + const curved = (leader.shaft ?? style.shaft) === "curved"; + /** + * Draws each shaft of a root from its tip to `end`: straight through its bends, or as a curve + * through them that meets `end` level, along `level`. + */ + const draw = (list: unknown, end: Point, level: number): void => { + for (const shaft of filled(list)) { + const listed = filled(shaft); + // A shaft with no tip, which the rules refuse, draws nothing. + if (listed.length === 0) continue; + const points = [...(listed as readonly Point[]).map(point), end]; + const [tip, next] = [points[0]!, points[1]!]; + const length = Math.hypot(tip[0] - next[0], tip[1] - next[1]); + // The way the arrowhead points: from the shaft's next point to its tip. + const along: Point = + length > 0 ? [(tip[0] - next[0]) / length, (tip[1] - next[1]) / length] : [1, 0]; + const across: Point = [-along[1], along[0]]; + const place = ([x, y]: readonly [number, number]): Point => [ + tip[0] + (along[0] * x + across[0] * y) * size, + tip[1] + (along[1] * x + across[1] * y) * size, + ]; + // A curve whose first stretch is shorter than the arrowhead has no room for one, and runs to + // its tip. A straight shaft keeps its arrowhead, as no case has shown otherwise. + const room = size > 0 && (!curved || length >= size); + if (room) { + const drawn: { + filled: Point[]; + lines: [Point, Point][]; + disks: { center: Point; radius: number }[]; + } = { filled: [], lines: [], disks: [] }; + if (info.block === undefined) { + drawn.filled.push(tip, place([-1, 1 / 6]), place([-1, -1 / 6])); + } + for (const stroke of info.strokes ?? []) { + if (stroke.kind === "line") drawn.lines.push([place(stroke.from), place(stroke.to)]); + else { + // Two half circles about the middle of its two points, as wide as its width. + const [a, b] = [stroke.points[0]!, stroke.points[1]!]; + const radius = Math.hypot(b[0] - a[0], b[1] - a[1]) / 2 + stroke.width / 2; + drawn.disks.push({ + center: place([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]), + radius: radius * size, + }); + } } + const turned = (((Math.atan2(along[1], along[0]) / RADIANS) % 360) + 360) % 360; + arrowheads.push({ + ...drawn, + ...(info.block === undefined + ? {} + : { insert: { at: tip, rotation: turned, scale: size } }), + }); } - const turned = (((Math.atan2(along[1], along[0]) / RADIANS) % 360) + 360) % 360; - arrowheads.push({ - ...drawn, - ...(info.block === undefined ? {} : { insert: { at: tip, rotation: turned, scale: size } }), - }); + const start: Point = info.toTip || !room ? tip : place([-1, 0]); + shafts.push( + curved + ? curveThrough([start, ...points.slice(1)], [-along[0], -along[1]], [level, 0]) + : [start, ...points.slice(1)], + ); } - const start: Point = info.toTip || !(size > 0) ? tip : place([-1, 0]); - shafts.push([start, ...points.slice(1)]); - } + }; + const h = sizes.textHeight; + // A vertical note that wraps is held by its top left, as the leading CAD app holds one whose + // box was drawn. + const wraps = leader.width !== undefined; + const noteAttachment = vertical ? (wraps ? 1 : 2) : side === "right" ? 1 : 3; + const align = noteAttachment === 1 ? "left" : noteAttachment === 2 ? "center" : "right"; + const unplaced = leaderNote( + leader, + sizes, + written(style.scale ?? 1), + leader.textStyle ?? style.textStyle, + vertical ? undefined : attachment, + ); + // A style whose font or width the rules refuse is laid out as `Standard`'s. + const layout = layoutParagraph( + paragraphInStyle({ ...unplaced, at: [0, 0], align }, textStyle ?? {}), + ); + const lines = layout.lines; + const [, bottom, , top0] = layout.frame; + // How far the note reaches across: its widest line's ink. + let wide = 0; + for (const line of lines) wide = Math.max(wide, line.end - line.start); + const lastBaseline = lines[lines.length - 1]?.baseline ?? -h; + // The height the leading CAD app takes a line of the note to have: its capitals, and how far + // the last line's letters reach below its baseline. + const line = h + Math.max(0, lastBaseline - bottom); + // A block in place of the note: its outline meets the landing's end, level with `at`. + const content = leaderBlock(leader, style); + const found = typeof content === "string" ? findBlock?.(content) : undefined; + let held: + | { + readonly insert: Insert; + readonly box: readonly [number, number, number, number]; + /** Where its outline starts along the landing's line. */ + readonly start: number; + } + | undefined; + if (found !== undefined) { + const outline = outlineOf(found, findBlock); + const s = written(style.blockScale ?? 1) * written(style.scale ?? 1); + const end = connection[0] + direction * sizes.landing; + const ext = outline.box ?? [0, 0, 0, 0]; + const byInsertion = style.blockConnection === "insertion" && outline.crossing !== undefined; + const [near, far] = byInsertion ? outline.crossing! : [ext[0], ext[2]]; + const x = end - (side === "left" ? far : near) * s; + const y = byInsertion ? connection[1] : connection[1] - ((ext[1] + ext[3]) / 2) * s; + const attributes = leader.attributes; + held = { + insert: { + kind: "insert", + layer: leader.layer, + block: found.name, + at: point([x, y]), + ...(s === 1 ? {} : { scale: [s, s] as const }), + ...(attributes === undefined ? {} : { attributes }), + }, + box: [x + ext[0] * s, y + ext[1] * s, x + ext[2] * s, y + ext[3] * s], + start: x + near * s, + }; + } + let location: Point; + let contentBase: Point; + const underlines: [Point, Point][] = []; const landing: readonly [Point, Point] | undefined = - sizes.landing > 0 + !vertical && !curved && sizes.landing > 0 ? [connection, [connection[0] + direction * sizes.landing, connection[1]]] : undefined; + if (vertical) { + const x = connection[0] - (noteAttachment === 1 ? wide / 2 : 0); + if (side === "above") { + location = [x, connection[1] + sizes.gap - bottom]; + contentBase = connection; + } else { + location = [x, connection[1] - sizes.gap]; + contentBase = [connection[0], location[1] + bottom - sizes.gap]; + } + if (verticalAttachment === "line") { + underlines.push([ + [connection[0] - wide / 2, connection[1]], + [connection[0] + wide / 2, connection[1]], + ]); + } + } else { + const x = connection[0] + direction * (sizes.landing + sizes.gap); + // How far the top of the note is above `at`, for each attachment. + const above: Record = { + "top-of-first": 0, + "first-line": line / 2, + middle: -bottom / 2, + "last-line": -bottom - line / 2, + "bottom-of-last": -bottom, + "underline-last": -lastBaseline + UNDERLINE * h, + "underline-first": FIRST_UNDERLINE * h, + "bottom-of-first": line, + "underline-all": FIRST_UNDERLINE * h, + }; + location = [x, connection[1] + above[attachment]]; + contentBase = + side === "right" + ? [connection[0] + direction * sizes.landing, connection[1]] + : [x - wide - sizes.gap, connection[1]]; + const from = connection[0] + direction * sizes.landing; + const far = x + direction * wide; + // The landing runs on under the line it meets, but not into a frame: to the note's far side, + // or to the end of the far root's landing. + if (attachment.startsWith("underline") && !(leader.frame ?? style.frame ?? false)) { + const reach = + filled(leader.farShafts).length > 0 ? far + direction * (sizes.gap + sizes.landing) : far; + underlines.push([ + [from, connection[1]], + [reach, connection[1]], + ]); + } + } - const height = sizes.textHeight; - const pitch = lineSpacing(height); - const text = filled(leader.text); - const count = text.length; - // The middle of the capitals of the line the landing meets is level with `at`. - const top = connection[1] + height / 2 + (attachment === "last-line" ? (count - 1) * pitch : 0); - const x = connection[0] + direction * (sizes.landing + sizes.gap); - const location: Point = [x, top]; - const align = side === "right" ? "left" : "right"; - const lines = text.map((value, k): LeaderLine => ({ - value, - at: [x, top - height - k * pitch], - align, - height, - })); - let width = 0; - for (const line of lines) { - // A style whose font or width the rules refuse is measured as `Standard`'s. - const measured = measureText({ - value: line.value, - height, - ...(typeof textStyle?.font === "string" ? { font: textStyle.font } : {}), - ...(typeof textStyle?.widthFactor === "number" ? { widthFactor: textStyle.widthFactor } : {}), - }); - width = Math.max(width, measured.length); + if (held) { + location = held.insert.at; + contentBase = [held.start, connection[1]]; + underlines.length = 0; + } + // Every point the file holds, as the writers write it. + location = point(location); + contentBase = point(contentBase); + // A second root on the note's far side: past its far edge on the side, or above or below it. + const farListed = filled(leader.farShafts); + let far: { connection: Point; direction: 1 | -1 } | undefined; + if (farListed.length > 0) { + if (vertical) { + const top = location[1] + top0; + far = + side === "above" + ? { connection: point([connection[0], top + sizes.gap]), direction: -1 } + : { + connection: point([connection[0], location[1] + bottom - sizes.gap]), + direction: 1, + }; + } else if (held) { + // A block's far side meets its landing with no gap. + const edge = side === "right" ? held.box[2] : held.box[0]; + far = { + connection: point([edge + direction * sizes.landing, connection[1]]), + direction: side === "right" ? -1 : 1, + }; + } else { + const edge = side === "right" ? location[0] + wide : location[0] - wide; + far = { + connection: point([edge + direction * (sizes.gap + sizes.landing), connection[1]]), + direction: side === "right" ? -1 : 1, + }; + } + } + // A curved shaft ends where the landing would, and meets it level; no landing is drawn. + const landingEnd = (from: Point, way: 1 | -1): Point => + vertical ? from : [from[0] + way * sizes.landing, from[1]]; + draw(leader.shafts, curved ? landingEnd(connection, direction) : connection, direction); + if (far) { + draw( + farListed, + curved ? landingEnd(far.connection, far.direction) : far.connection, + far.direction, + ); } - const left = side === "right" ? x : x - width; + const farLanding: readonly [Point, Point] | undefined = + far && !vertical && !curved && sizes.landing > 0 + ? [far.connection, [far.connection[0] + far.direction * sizes.landing, far.connection[1]]] + : undefined; + const note: Paragraph = { ...unplaced, ...(held ? { value: "" } : {}), at: location, align }; + const place = placer(note); + const left = noteAttachment === 1 ? 0 : noteAttachment === 2 ? -wide / 2 : -wide; + const box: [number, number, number, number] = held + ? [...held.box] + : [location[0] + left, location[1] + bottom, location[0] + left + wide, location[1] + top0]; + const grown = (by: number): [Point, Point, Point, Point] => [ + [box[0] - by, box[1] - by], + [box[2] + by, box[1] - by], + [box[2] + by, box[3] + by], + [box[0] - by, box[3] + by], + ]; + // A block in place of the note has no frame. + const framed = held === undefined && (leader.frame ?? style.frame) === true; + const mask = maskOf(leader.mask); + const masked = (m: { readonly color?: number; readonly offsetFactor: number }) => ({ + corners: grown((m.offsetFactor - 1) * h), + ...(m.color === undefined ? {} : { color: m.color }), + factor: m.offsetFactor, + }); return { sizes, side, attachment, + verticalAttachment, + vertical, connection, direction, shafts, arrowheads, ...(landing === undefined ? {} : { landing }), + ...(far === undefined ? {} : { farConnection: far.connection, farDirection: far.direction }), + ...(farLanding === undefined ? {} : { farLanding }), + curved, + note, + noteAttachment, location, - contentBase: [left - sizes.gap, connection[1]], - lines, + contentBase, + box, + underlines, + ...(framed ? { frame: grown(sizes.gap) } : {}), + ...(mask === undefined ? {} : { mask: masked(mask) }), + ...(held ? { block: held.insert } : {}), + lines: (held ? [] : lines).map((line) => ({ + value: line.value, + at: place(line.runs[0]?.x ?? line.start, line.baseline), + align: "left" as const, + height: h, + })), }; } @@ -477,8 +1131,23 @@ export function leaderDrawnProblem( leader: Leader, style: LeaderStyle, textStyle: TextStyle | undefined, + findBlock?: (name: string) => Block | undefined, ): string | undefined { - const picture = leaderPicture(leader, style, textStyle); + const picture = leaderPicture(leader, style, textStyle, findBlock); + const far = picture.farConnection; + if (far !== undefined) { + for (const shaft of filled(leader.farShafts)) { + const listed = filled(shaft) as readonly Point[]; + const [tip, next = far] = listed; + if ( + tip !== undefined && + written(tip[0]) === written(next[0]) && + written(tip[1]) === written(next[1]) + ) { + return LEADER_SHAFT_LENGTH; + } + } + } const numbers = [ ...picture.shafts.flat(2), ...picture.arrowheads.flatMap((a) => [ @@ -487,8 +1156,12 @@ export function leaderDrawnProblem( ...a.disks.flatMap((d) => [...d.center, d.radius]), ]), ...(picture.landing ?? []).flat(), + ...(picture.farLanding ?? []).flat(), + ...(picture.farConnection ?? []), ...picture.location, ...picture.contentBase, + ...picture.box, + ...picture.underlines.flat(2), ...picture.lines.flatMap((line) => line.at), ]; for (const value of numbers) { diff --git a/src/lint.ts b/src/lint.ts index 351ede3..74928c8 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -55,6 +55,7 @@ import { validIdHandle } from "./handles.ts"; import { validLayoutHandles, validViewportView, viewReaches } from "./layouts.ts"; import { leaderArrowheadHandles, + leaderBlock, leaderDrawnProblem, leaderRepeats, leaderStyleDictionaryHandle, @@ -119,6 +120,7 @@ import { leaderStyleNameProblem, leaderStyleProblem, leaderStyleTwinProblem, + leaderBlockContentProblem, leaderTextProblem, layerColorProblem, layerFlagProblem, @@ -1143,6 +1145,8 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (!problem && lettered) leaderStyles.set(key, style); }, ); + /** The tags of each block a leader holds in place of its note, worked out once. */ + const tagsOf = new WeakMap>(); /** Checks what a leader names, its note and its shafts. `sound` is false for one no rule can read. */ const lintLeader = ( leader: Leader, @@ -1161,13 +1165,41 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) else if (!leaderStyleNames.has(layerKey(name as string))) { add("undefined-leader-style", "error", undefinedLeaderStyleProblem(name as string)); } else style = leaderStyles.get(layerKey(name as string)); - const textProblem = leaderTextProblem(leader.text); - if (textProblem) add("leader", "error", textProblem); - else { - for (const line of leader.text) { - const warning = textWarning(line); - if (warning) { - add("text", "warning", warning); + const content = leaderBlock(leader, style); + let noteProblem: string | undefined; + const ownBlock: unknown = leader.block; + if (ownBlock !== undefined && typeof ownBlock !== "string") { + noteProblem = "a block is named by a string"; + add("undefined-block", "error", noteProblem); + } else if (content === undefined) { + noteProblem = leaderTextProblem(leader.text); + if (noteProblem) add("leader", "error", noteProblem); + else { + for (const line of leader.text ?? []) { + const warning = textWarning(line); + if (warning) { + add("text", "warning", warning); + break; + } + } + } + } else { + if (typeof content !== "string") noteProblem = "a block is named by a string"; + else if (!blocks.has(layerKey(content))) noteProblem = undefinedBlockProblem(content); + if (noteProblem) add("undefined-block", "error", noteProblem); + const problem = leaderBlockContentProblem(leader); + if (problem) add("leader", "error", problem); + noteProblem ??= problem; + // Each value names an attribute of the block, as an insert's does. + const held = typeof content === "string" ? blocks.get(layerKey(content)) : undefined; + const set: unknown = leader.attributes; + if (!problem && held && typeof set === "object" && set !== null) { + let tags = tagsOf.get(held); + if (!tags) tagsOf.set(held, (tags = new Set(filled(held.attributes).map((d) => d?.tag)))); + for (const tag of Object.keys(set)) { + if (tags.has(tag)) continue; + noteProblem = undefinedAttributeProblem(tag, held.name); + add("undefined-attribute", "error", noteProblem); break; } } @@ -1186,11 +1218,13 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } const ownProblem = leaderOwnProblem(leader, written(style?.scale ?? 1)); if (ownProblem) add("leader", "error", ownProblem); - if (!style || textProblem || shaftProblem || ownProblem || !lettered) return; + if (!style || noteProblem || shaftProblem || ownProblem || !lettered) return; if (own === undefined && style.textStyle !== undefined) { textStyle = stylesByKey.get(layerKey(style.textStyle)); } - const problem = leaderDrawnProblem(leader, style, textStyle); + const problem = leaderDrawnProblem(leader, style, textStyle, (name) => + blocks.get(layerKey(name)), + ); if (problem) add("leader", "error", problem); }; @@ -1329,6 +1363,18 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (clash) error("id-handle", clash); } }); + // A style's block is written by its record's handle, so it is one the drawing defines. + for (const style of leaderStyles.values()) { + const block: unknown = style.block; + if (typeof block === "string" && !blocks.has(layerKey(block))) { + out.push({ + rule: "undefined-block", + severity: "error", + message: `Leader style ${shown(style.name)}: ${undefinedBlockProblem(block)}`, + ...named("leaderStyle", style.name), + }); + } + } // An xref is a block to the leading CAD app, so it shares the blocks' names, and an insert finds // it as it finds a block. diff --git a/src/read/check.ts b/src/read/check.ts index 8215de6..dfdf497 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -203,11 +203,46 @@ const ENTITY: Readonly> = { at: "point", direction: "point", landing: "number", + roots: { + list: { + fields: { + at: "point", + direction: "point", + landing: "number", + shafts: { list: { list: "point" } }, + }, + }, + }, + shaft: { oneOf: ["straight", "curved", "none"] }, text: "string", textAt: "point", + textAttachment: "number", + width: "number", textHeight: "number", textStyle: "string", arrowSize: "number", + attachments: { fields: { left: "number", right: "number", top: "number", bottom: "number" } }, + "vertical?": "boolean", + "frame?": "boolean", + "mask?": { fields: { offsetFactor: "number", "color?": "number" } }, + "block?": { + fields: { + name: "string", + at: "point", + scale: "number", + rotation: "number", + "attributes?": { map: "string" }, + }, + }, + }, + leader: { + ...BASE, + kind: { oneOf: ["leader"] }, + style: "string", + points: { list: "point" }, + shaft: { oneOf: ["straight", "curved"] }, + arrowhead: "boolean", + "note?": "string", }, solid: { ...BASE, kind: { oneOf: ["solid"] }, points: { list: "point" } }, image: { diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 5dd5992..eae2088 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -14,10 +14,12 @@ import { costOf, handleAt, imageInWorld, + MAX_TAGS, nameCost, placementOf, readingOf, sidesOf, + type LeaderNames, type Later, type PendingStart, } from "./entities.ts"; @@ -167,9 +169,6 @@ const FIELD_WORK = 1_000_000; /** The most heights of one MTEXT's text that are kept. */ const MAX_INLINE_HEIGHTS = 64; -/** The most tags of one insert that are kept. */ -const MAX_TAGS = 1000; - /** The most groups one record keeps. */ const MAX_GROUPS = 1_000_000; @@ -190,6 +189,7 @@ const BLOCK_READS = new Set([ "IMAGE", "INSERT", "LARGE_RADIAL_DIMENSION", + "LEADER", "LINE", "LWPOLYLINE", "MTEXT", @@ -409,12 +409,10 @@ interface InsertOwner { readonly starts: PendingStart[]; } -/** A multileader whose styles are named by handle, until the file is read. */ -interface PendingLeader { +/** A multileader whose styles and block are named by handle, until the file is read. */ +interface PendingLeader extends LeaderNames { readonly entity: ReadMultileader; - readonly style?: string; - readonly textStyle?: string; - /** Where it was kept, which its styles' names are charged to. */ + /** Where it was kept, which its names are charged to. */ readonly target?: Target; } @@ -523,12 +521,7 @@ class DxfReader { >(); readonly #later: Later = { start: (pending) => this.#staged.starts.push(pending), - leader: (entity, style, textStyle) => - this.#staged.leaders.push({ - entity, - ...(style !== undefined && { style }), - ...(textStyle !== undefined && { textStyle }), - }), + leader: (entity, names) => this.#staged.leaders.push({ entity, ...names }), }; /** @@ -1584,17 +1577,34 @@ class DxfReader { } /** - * Names each multileader's style and its note's style, which the file names by handle. The - * names are charged to the budget the leader was kept in, and a leader they do not fit is - * counted as past the limit and left out. + * Names each multileader's style, its note's style and its block, which the file names by + * handle, and keys its block's labels by the tags of the definitions they fill, which the blocks + * read hold. The names are charged to the budget the leader was kept in, and a leader they do + * not fit is counted as past the limit and left out. */ #leaderStyles(styleNames: ReadonlyMap): void { const left = new Set(); const targets = new Set(); - for (const { entity, style, textStyle, target } of this.#leaders) { + let tags: Map | undefined; + for (const { entity, style, textStyle, block, target } of this.#leaders) { const named = style === undefined ? undefined : this.leaderStyles.get(style); const note = (textStyle === undefined ? undefined : styleNames.get(textStyle)) ?? "Standard"; - const cost = nameCost(named) + nameCost(note) - nameCost(entity.textStyle); + const blockName = block === undefined ? "" : (this.blockRecords.get(block) ?? ""); + let cost = nameCost(named) + nameCost(note) - nameCost(entity.textStyle); + if (entity.block) cost += nameCost(blockName) - nameCost(entity.block.name); + const held = entity.block?.attributes; + let attributes: Record | undefined; + if (held) { + tags ??= this.#definitionTags(); + for (const definition in held) { + const tag = tags.get(definition); + if (tag === undefined || tag.length > LONGEST_NAME || (attributes && tag in attributes)) + continue; + attributes ??= map(); + attributes[tag] = held[definition]!; + cost += nameCost(tag) - nameCost(definition); + } + } if (target && cost > this.#room(target)) { add(target.other, "past the limit"); left.add(entity); @@ -1603,13 +1613,27 @@ class DxfReader { } if (target?.block) this.#blockItems += cost; else if (target) this.#geometryItems += cost; - const mutable = entity as { style?: string; textStyle: string }; + const mutable = entity as { style?: string; textStyle: string; block?: object }; if (named !== undefined) mutable.style = named; mutable.textStyle = note; + if (entity.block) { + const { attributes: _, ...rest } = entity.block; + mutable.block = { ...rest, name: blockName, ...(attributes && { attributes }) }; + } } for (const target of targets) target.entities = target.entities.filter((e) => !left.has(e)); } + /** The tag of each attribute definition the blocks read hold, by its handle in capitals. */ + #definitionTags(): Map { + const tags = new Map(); + for (const block of this.blocks) + for (const { handle, tag } of block.attributeDefinitions) + if (handle !== undefined && !tags.has(handle.toUpperCase())) + tags.set(handle.toUpperCase(), tag); + return tags; + } + /** Gives each insert and dimension the handle of its block's record, found as the leading CAD app finds it. */ #blockHandles(): void { const records = new Map(); diff --git a/src/read/entities.ts b/src/read/entities.ts index 2e1c084..0c03970 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -21,6 +21,7 @@ import { facing, first, inSubclass, + map, name, num, placed, @@ -38,12 +39,17 @@ export type Reading = | { readonly other: string } | { readonly malformed: string }; +const HANDLE = /^[0-9A-Fa-f]{1,16}$/; + /** The handle a group holds: 1 to 16 hexadecimal digits, or undefined for anything else. */ export function handleAt(r: Rec, code: number): string | undefined { const value = first(r, code); - return value !== undefined && /^[0-9A-Fa-f]{1,16}$/.test(value) ? value : undefined; + return value !== undefined && HANDLE.test(value) ? value : undefined; } +/** The most tags of one insert, and labels of one multileader's block, that are kept. */ +export const MAX_TAGS = 1000; + /** The pen an entity sets for itself, with each part left out at ByLayer. */ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadEntityBase { const color = num(r, 62); @@ -152,12 +158,20 @@ function ownGroups(r: Rec): Rec { /** The names of the kinds of dimension `ReadDimension` does not hold, by group 70's low bits. */ const DIMENSION_KINDS = ["", "", "angular", "diameter", "radius", "angular 3-point", "ordinate"]; +/** What a multileader names by handle, until the file is read. */ +export interface LeaderNames { + readonly style?: string | undefined; + readonly textStyle?: string | undefined; + /** The record of the block that is its content. */ + readonly block?: string | undefined; +} + /** What the reader finishes once the whole file is read. */ export interface Later { /** A justified text whose start is worked out from its font. */ start(pending: PendingStart): void; - /** A multileader whose styles are named by these handles. */ - leader(entity: ReadMultileader, style: string | undefined, textStyle: string | undefined): void; + /** A multileader whose styles, block and block's labels are named by handle. */ + leader(entity: ReadMultileader, names: LeaderNames): void; } /** @@ -215,6 +229,8 @@ export function readingOf( return dimension(r, base, face, r12); case "MULTILEADER": return multileader(r, base, later); + case "LEADER": + return leader(r, base, face); case "IMAGE": return image(r, base); case "SOLID": { @@ -487,6 +503,12 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re return { entity }; } +/** The color index of a mask's color from the 32 bits a file holds: ByBlock 0, an index, else 256. */ +export function maskColor(raw: number): number { + const method = raw >>> 24; + return method === 0xc1 ? 0 : method === 0xc3 ? raw & 0xff : 256; +} + /** * A radius (group 70's kind 4), a diameter (3) or a jogged radius (9) dimension. A diameter holds * the far end of its line in group 10 and its center halfway to group 15. @@ -520,8 +542,9 @@ function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolea } /** - * A `MULTILEADER` with one root, straight shafts and a note, as the writers write one, from the - * context data that says how it is drawn. Any other is left out by what it holds. + * A `MULTILEADER`, from the context data that says how it is drawn: every root with its shafts, a + * note or a block, and the multileader's own groups after the context. One whose note or block + * leaves the plane is left out. */ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { const c = r.codes; @@ -529,9 +552,11 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { let where: "before" | "context" | "leader" | "line" | "after" = "before"; const roots: { shafts: Point[][]; groups: Record }[] = []; let shaft: Point[] = []; - // The first value of each group of the context and of what follows it, which hold each once. + // The first value of each group of the context and of what follows it, which hold each once, + // but for the block's labels after the context: groups 330 and 302 of each. const context: Record = {}; const after: Record = {}; + const labels: { definition: string | undefined; text: string }[] = []; for (let i = 0; i < c.length; i++) { const code = c[i]!; const value = v[i]!; @@ -552,7 +577,13 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { } else if (where === "leader" && code === 303) where = "context"; else if (where === "line") { if (code === 10 && c[i + 1] === 20) shaft.push([Number(value), Number(v[i + 1])]); - } else { + } else if (where === "after" && code === 330) { + const handle = value.trim(); + // A label of the null handle fills no definition. + const known = HANDLE.test(handle) && !/^0+$/.test(handle); + labels.push({ definition: known ? handle.toUpperCase() : undefined, text: "" }); + } else if (where === "after" && code === 302 && labels.length > 0) labels.at(-1)!.text = value; + else { const groups = where === "leader" ? roots.at(-1)!.groups : where === "context" ? context : after; if (!(code in groups)) groups[code] = value; @@ -564,41 +595,116 @@ function multileader(r: Rec, base: ReadEntityBase, later: Later): Reading { }; const pair = (groups: Record, x: number): Point | undefined => groups[x] === undefined ? undefined : [number(groups, x, 0), number(groups, x + 10, 0)]; - // Group 172 after the context is what the note is: 2 a text, 1 a block. 170 is the shafts' - // kind: 1 straight, 2 curved, 0 none. - if (number(after, 172, 2) !== 2) return { other: "MULTILEADER with a block" }; - if (number(after, 170, 1) !== 1) return { other: "MULTILEADER without straight shafts" }; - if (roots.length !== 1) return { other: "MULTILEADER with other than one root" }; - // The note's normal is groups 11, 21 and 31 of the context. - if ( - Math.abs(number(context, 11, 0)) > 1e-9 || - Math.abs(number(context, 21, 0)) > 1e-9 || - number(context, 31, 1) <= 0 - ) { - return { other: "MULTILEADER in 3D" }; + const up = (x: number): boolean => + Math.abs(number(context, x, 0)) <= 1e-9 && + Math.abs(number(context, x + 10, 0)) <= 1e-9 && + number(context, x + 20, 1) > 0; + // Group 290 of the context says it holds a note, and 296 a block; group 172 after it says the + // same, 2 a note and 1 a block, for a file that leaves the context's out. + const content = number(after, 172, 2); + const hasText = number(context, 290, content === 2 ? 1 : 0) === 1; + const hasBlock = !hasText && number(context, 296, content === 1 ? 1 : 0) === 1; + // The normal of the note is groups 11, 21 and 31 of the context, and of the block 14, 24 and 34. + if ((hasText && !up(11)) || (hasBlock && !up(14))) return { other: "MULTILEADER in 3D" }; + // A block's labels are keyed by the handle of the definition each fills until the file is read. + let attributes: Record | undefined; + let kept = 0; + for (const { definition, text } of hasBlock ? labels : []) { + attributes ??= map(); + if (definition === undefined || definition in attributes) continue; + if (kept++ >= MAX_TAGS) break; + attributes[definition] = textTwice(text); } - const root = roots[0]!; - const at = pair(root.groups, 10); - const textAt = pair(context, 12); - const text = context[304]; - if (text === undefined || !at || !textAt) return { other: "MULTILEADER without a note" }; + const block = hasBlock + ? { + name: "", + at: pair(context, 15) ?? [0, 0], + scale: number(context, 16, 1), + rotation: (number(context, 46, 0) * 180) / Math.PI, + ...(attributes && { attributes }), + } + : undefined; + const textAt = (hasText && pair(context, 12)) || block?.at || pair(context, 10) || [0, 0]; + const read = roots.map((root) => ({ + at: pair(root.groups, 10) ?? [0, 0], + direction: pair(root.groups, 11) ?? ([1, 0] as Point), + landing: number(root.groups, 40, 0), + shafts: root.shafts, + })); + const [first] = read; + const masked = hasText && number(context, 292, 0) === 1; const entity: ReadMultileader = { ...base, kind: "multileader", - shafts: root.shafts, - at, - direction: pair(root.groups, 11) ?? [1, 0], - landing: number(root.groups, 40, 0), - text: textOnce(text), + shafts: first?.shafts ?? [], + at: first?.at ?? textAt, + direction: first?.direction ?? [1, 0], + landing: first?.landing ?? 0, + roots: read, + // Group 170 after the context: 0 no shafts, 1 straight, 2 curved. + shaft: (["none", "straight", "curved"] as const)[number(after, 170, 1)] ?? "straight", + text: hasText ? textOnce(context[304] ?? "") : "", textAt, + textAttachment: hasText ? number(context, 171, 1) : 1, + width: hasText ? number(context, 43, 0) : 0, textHeight: number(context, 41, 0), textStyle: "Standard", arrowSize: number(context, 140, 0), + attachments: { + left: number(context, 174, 1), + right: number(context, 175, 1), + top: number(context, 273, 9), + bottom: number(context, 272, 9), + }, + ...(number(after, 271, 0) === 1 && { vertical: true }), + ...(number(after, 292, 0) === 1 && { frame: true }), + // Group 292 of the context masks the note, with the drawing's background where 291 says so + // and else with the color of group 91. + ...(masked && { + mask: { + offsetFactor: number(context, 141, 1.5), + ...(number(context, 291, 0) !== 1 && { + color: maskColor(number(context, 91, 0xc0000000)), + }), + }, + }), + ...(block && { block }), }; - later.leader(entity, after[340], context[340]); + later.leader(entity, { + style: after[340], + // A note names its text style in the context, and the multileader its own after it. + textStyle: hasText ? context[340] : after[343], + ...(hasBlock && { block: context[341] ?? after[344] }), + }); return { entity }; } +/** + * The old `LEADER`: its points as the file holds them, in the world's coordinates, and the handle + * of its note. The leading CAD app leaves group 71 out where it draws an arrowhead, and group 73 + * out where it has no note. + */ +function leader(r: Rec, base: ReadEntityBase, face: Facing): Reading { + if (face === 0) return { other: "LEADER in 3D" }; + const points: Point[] = []; + for (let i = 0; i < r.codes.length; i++) { + if (r.codes[i] !== 10) continue; + points.push([Number(r.values[i]), r.codes[i + 1] === 20 ? Number(r.values[i + 1]) : 0]); + } + const note = (num(r, 73) ?? 3) === 3 ? undefined : handleAt(r, 340); + return { + entity: { + ...base, + kind: "leader", + style: name(r, 3) ?? "Standard", + points, + shaft: num(r, 72) === 1 ? "curved" : "straight", + arrowhead: num(r, 71) !== 0, + ...(note !== undefined && { note }), + }, + }; +} + /** An attribute of an insert from its `ATTRIB` record. */ export function attributeOf( r: Rec, @@ -662,9 +768,25 @@ export function costOf(e: ReadEntity): number { return own + 5 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "multileader": { let points = 3; - for (const shaft of e.shafts) points += shaft.length; - return own + points + chars(e.text) + chars(e.textStyle) + chars(e.style); + for (const root of e.roots) { + points += 3; + for (const shaft of root.shafts) points += 1 + shaft.length; + } + let labels = 0; + const attributes = e.block?.attributes ?? {}; + for (const tag in attributes) labels += 1 + chars(tag) + chars(attributes[tag]); + return ( + own + + points + + labels + + chars(e.text) + + chars(e.textStyle) + + chars(e.style) + + chars(e.block?.name) + ); } + case "leader": + return own + e.points.length + chars(e.style) + chars(e.note); case "insert": { let more = 2 + chars(e.block); for (const tag in e.tags) more += 1 + chars(tag); diff --git a/src/read/model.ts b/src/read/model.ts index b388011..5b3cf84 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -428,29 +428,97 @@ export interface ReadRadialDimension extends ReadEntityBase { readonly blockHandle?: string; } -/** A multileader with one note and straight shafts that meet at one landing. */ +/** One root of a multileader: where some of its shafts meet, and the landing from there. */ +export interface ReadLeaderRoot { + /** Where its shafts meet and its landing starts. */ + readonly at: Point; + /** The way its landing runs from `at`, one unit long. */ + readonly direction: Point; + /** How long its landing is. */ + readonly landing: number; + /** Each shaft: its tip, then each point it bends at on its way to `at`. */ + readonly shafts: readonly (readonly Point[])[]; +} + +/** + * A multileader: a note or a block, with shafts from one root, or from two on either side of it. + * `shafts`, `at`, `direction` and `landing` are its first root's, and for one with no root none, + * `textAt` and no landing. + */ export interface ReadMultileader extends ReadEntityBase { readonly kind: "multileader"; /** Its leader style, when the file's dictionary of leader styles names it. */ readonly style?: string; - /** Each shaft: its tip, then each point it bends at on its way to `at`. */ + /** Each shaft of its first root: its tip, then each point it bends at on its way to `at`. */ readonly shafts: readonly (readonly Point[])[]; - /** Where the shafts meet and the landing starts. */ + /** Where its first root's shafts meet and its landing starts. */ readonly at: Point; - /** The way the landing runs from `at`, one unit long. */ + /** The way the first root's landing runs from `at`, one unit long. */ readonly direction: Point; - /** How long the landing is. */ + /** How long the first root's landing is. */ readonly landing: number; - /** Its note as the leading CAD app holds it, with `\P` between lines. */ + /** Each root, the first among them, in the order of the file. */ + readonly roots: readonly ReadLeaderRoot[]; + /** How its shafts are drawn: straight, as a curve through their points, or not at all. */ + readonly shaft: "straight" | "curved" | "none"; + /** Its note as the leading CAD app holds it, with `\P` between lines, or `""` for a block. */ readonly text: string; - /** The corner of the note's box that holds it. */ + /** The point of the note's box that `textAttachment` names, or a block's `at`. */ readonly textAt: Point; + /** Where `textAt` is on the note's box: 1 top left, 2 top center, 3 top right, as an MTEXT's. */ + readonly textAttachment: number; + /** The width the note wraps at, or 0 when it does not wrap. */ + readonly width: number; /** The height of the note's text. */ readonly textHeight: number; /** The note's text style. */ readonly textStyle: string; /** The length of an arrowhead. */ readonly arrowSize: number; + /** + * Where a landing meets the note, by the side of the note it meets: 0 to 8 at its left or right, + * from the top of its first line to an underline of every line, and 9, at the middle, or 10, + * with a line as wide as the note, at its top or bottom. + */ + readonly attachments: { + readonly left: number; + readonly right: number; + readonly top: number; + readonly bottom: number; + }; + /** True when its landings meet the note at its top or bottom, not its sides. */ + readonly vertical?: true; + /** True for a frame around the note. */ + readonly frame?: true; + /** + * The mask behind the note: the drawing's background, or a color index, over the note's box + * grown by `offsetFactor` times its text height less one. + */ + readonly mask?: { readonly offsetFactor: number; readonly color?: number }; + /** The block that is its content in place of a note, where it is placed, and its tags' values. */ + readonly block?: { + readonly name: string; + readonly at: Point; + readonly scale: number; + /** Degrees counterclockwise. */ + readonly rotation: number; + readonly attributes?: Readonly>; + }; +} + +/** The old leader: a line of points from its arrowhead, its note an entity of its own. */ +export interface ReadLeader extends ReadEntityBase { + readonly kind: "leader"; + /** Its dimension style, whose sizes it is drawn with. */ + readonly style: string; + /** Its points from its tip. */ + readonly points: readonly Point[]; + /** How it runs through its points: straight, or as a curve. */ + readonly shaft: "straight" | "curved"; + /** True when it draws an arrowhead at its tip. */ + readonly arrowhead: boolean; + /** The handle of its note, an `MTEXT`, a tolerance or an insert, when it has one. */ + readonly note?: string; } /** A filled outline of three or four corners, as a dimension draws an arrowhead. */ @@ -514,6 +582,7 @@ export type ReadEntity = | ReadDimension | ReadRadialDimension | ReadMultileader + | ReadLeader | ReadSolid | ReadImage; diff --git a/src/rules.ts b/src/rules.ts index 2b20aee..ff7f7ec 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -3196,16 +3196,56 @@ const LEADER_TEXT_LINES = "A leader's text is a string, one line, or an array of the lines of its note from the top"; const LEADER_SHAFTS = "A leader needs a shaft: to is a point, the tip of its one shaft, or a list of shafts, each its tip or its tip and the points it bends at on its way to the landing"; -const LEADER_SHAFT_LENGTH = +export const LEADER_SHAFT_LENGTH = "The tip of a shaft and the point after it are one point once they are written with the 6 decimals tsdraft writes, which leaves the leading CAD app no direction to point the arrowhead in. Move the tip, or the point after it"; -const LEADER_ATTACHMENT = 'attachment must be "first-line" or "last-line"'; -const LEADER_SIDE = 'side must be "left" or "right"'; - -/** Which line of its note a leader's landing meets: the first is the leading CAD app's own choice. */ -export const LEADER_ATTACHMENTS = ["first-line", "last-line"] as const; +/** + * Where a leader's landing meets the side of its note, in the order the leading CAD app numbers + * them: the top of the first line, the middle of the first line, which is that app's own choice, + * the middle of the note, the middle of the last line, the bottom of the last line, the bottom of + * the last line with the landing drawn on under it, the bottom of the first line with the landing + * under it, the bottom of the first line, and the bottom of the first line with every line + * underlined. + */ +export const LEADER_ATTACHMENTS = [ + "top-of-first", + "first-line", + "middle", + "last-line", + "bottom-of-last", + "underline-last", + "underline-first", + "bottom-of-first", + "underline-all", +] as const; /** Which side of the point where its shafts meet a leader's note is on. */ -export const LEADER_SIDES = ["left", "right"] as const; +export const LEADER_SIDES = ["left", "right", "above", "below"] as const; + +/** Whether a style's landings meet the side of its notes, or their top or bottom. */ +export const LEADER_DIRECTIONS = ["horizontal", "vertical"] as const; + +/** + * Where a landing meets a note above or below it: at the middle of its bottom or top, or there + * with a line as wide as the note. + */ +export const LEADER_VERTICAL_ATTACHMENTS = ["center", "line"] as const; + +/** How a leader's shafts run through their points: straight, or as a curve. */ +export const LEADER_SHAFT_KINDS = ["straight", "curved"] as const; + +/** How a block in place of a leader's note meets its landing: by its extents or its insertion point. */ +export const LEADER_BLOCK_CONNECTIONS = ["extents", "insertion"] as const; + +const LEADER_ATTACHMENT = `attachment must be one of LEADER_ATTACHMENTS: ${LEADER_ATTACHMENTS.map((a) => JSON.stringify(a)).join(", ")}`; +const LEADER_SIDE = 'side must be "left", "right", "above" or "below"'; +const LEADER_DIRECTION = 'direction must be "horizontal" or "vertical"'; +const LEADER_VERTICAL_ATTACHMENT = 'verticalAttachment must be "center" or "line"'; +const LEADER_SHAFT_KIND = 'shaft must be "straight" or "curved"'; +const LEADER_FRAME = "frame must be true or false"; +const LEADER_WIDTH = + "width must be greater than 0. It is the width the note wraps at; leave it out for a note that does not wrap"; +const LEADER_MASK = + "mask must be true, false, or { color?, offsetFactor? }: a color index from 1 to 256, where 256 is the layer's, and a factor of the text height from 1 to 5"; /** What is wrong with a leader in a block. */ export const LEADER_IN_BLOCK = @@ -3331,6 +3371,92 @@ export function leaderSideProblem(value: unknown): string | undefined { return (LEADER_SIDES as readonly unknown[]).includes(value) ? undefined : LEADER_SIDE; } +/** Returns what is wrong with a leader style's direction, or undefined. */ +export function leaderDirectionProblem(value: unknown): string | undefined { + return (LEADER_DIRECTIONS as readonly unknown[]).includes(value) ? undefined : LEADER_DIRECTION; +} + +/** Returns what is wrong with a leader's vertical attachment, or undefined. */ +export function leaderVerticalAttachmentProblem(value: unknown): string | undefined { + return (LEADER_VERTICAL_ATTACHMENTS as readonly unknown[]).includes(value) + ? undefined + : LEADER_VERTICAL_ATTACHMENT; +} + +/** Returns what is wrong with a leader's kind of shaft, or undefined. */ +export function leaderShaftKindProblem(value: unknown): string | undefined { + return (LEADER_SHAFT_KINDS as readonly unknown[]).includes(value) ? undefined : LEADER_SHAFT_KIND; +} + +/** Returns what is wrong with a leader's mask, or undefined. */ +export function leaderMaskProblem(value: unknown): string | undefined { + if (typeof value === "boolean") return undefined; + if (typeof value !== "object" || value === null || Array.isArray(value)) return LEADER_MASK; + const m = value as Record; + for (const key of Object.keys(m)) + if (key !== "color" && key !== "offsetFactor") return LEADER_MASK; + if ( + m.color !== undefined && + !(Number.isInteger(m.color) && (m.color as number) >= 1 && (m.color as number) <= 256) + ) { + return LEADER_MASK; + } + if ( + m.offsetFactor !== undefined && + !( + typeof m.offsetFactor === "number" && + written(m.offsetFactor) >= 1 && + written(m.offsetFactor) <= 5 + ) + ) { + return LEADER_MASK; + } + return undefined; +} + +/** The fields of a leader that only a note has, which a leader whose content is a block may not set. */ +const NOTE_ONLY = [ + "text", + "attachment", + "verticalAttachment", + "width", + "frame", + "mask", + "textStyle", + "textHeight", +] as const; + +/** + * Returns what is wrong with a leader whose content is a block, or undefined: it sets none of + * what only a note has, and its attributes are strings by their tags. + */ +export function leaderBlockContentProblem(leader: object): string | undefined { + const l = leader as Readonly>; + for (const field of NOTE_ONLY) { + if (l[field] !== undefined) { + return `${field}: a leader whose content is a block has no note to give it to. Leave it out, or give the leader a note instead`; + } + } + const set = l.attributes; + if (set === undefined) return undefined; + if (typeof set !== "object" || set === null || Array.isArray(set)) { + return "attributes must be an object of values by their tags"; + } + for (const value of Object.values(set)) { + if (typeof value !== "string") return "each value of attributes must be a string"; + const problem = textProblem(value); + if (problem) return `attributes: ${problem}`; + } + return undefined; +} + +/** Returns what is wrong with a leader's width, or undefined: a finite length greater than 0. */ +export function leaderWidthProblem(value: unknown): string | undefined { + return typeof value === "number" && Number.isFinite(value) && written(value) > 0 + ? magnitudeProblem(value) + : LEADER_WIDTH; +} + /** * Returns what is wrong with sizes a leader is drawn with, times the scale of its style, or * undefined: each must be under 1e100, and a text height or an arrow size above 0 must not be @@ -3340,14 +3466,14 @@ function leaderScaledProblem( sizes: Readonly>, scale: number, ): string | undefined { - for (const field of ["textHeight", "arrowSize", "landing", "gap"] as const) { + for (const field of ["textHeight", "arrowSize", "landing", "gap", "width"] as const) { if (sizes[field] === undefined) continue; const size = written(sizes[field] as number); const scaled = size * scale; if (!(Math.abs(scaled) < 1e100)) { return `${field}: times the scale it is ${scaled}, and the leading CAD app reads only two exponent digits from DXF, so every size of a leader must be under 1e100. Use a smaller size or scale`; } - if ((field === "textHeight" || field === "arrowSize") && size > 0 && written(scaled) === 0) { + if (field !== "landing" && field !== "gap" && size > 0 && written(scaled) === 0) { return `${field}: times the scale it is ${scaled}, which is written as 0 with the 6 decimals tsdraft writes. Use a larger size or scale${field === "arrowSize" ? ", or an arrow size of 0" : ""}`; } } @@ -3386,6 +3512,34 @@ export function leaderStyleProblem(style: unknown): string | undefined { const problem = leaderAttachmentProblem(s.attachment); if (problem) return problem; } + if (s.direction !== undefined) { + const problem = leaderDirectionProblem(s.direction); + if (problem) return problem; + } + if (s.verticalAttachment !== undefined) { + const problem = leaderVerticalAttachmentProblem(s.verticalAttachment); + if (problem) return problem; + } + if (s.frame !== undefined && typeof s.frame !== "boolean") return LEADER_FRAME; + if (s.shaft !== undefined) { + const problem = leaderShaftKindProblem(s.shaft); + if (problem) return problem; + } + if (s.block !== undefined) { + if (typeof s.block !== "string") return "block: a block is named by a string"; + const problem = blockNameProblem(s.block); + if (problem) return `block: ${problem}`; + } + if ( + s.blockConnection !== undefined && + !(LEADER_BLOCK_CONNECTIONS as readonly unknown[]).includes(s.blockConnection) + ) { + return 'blockConnection must be "extents" or "insertion"'; + } + if (s.blockScale !== undefined) { + const problem = styleScaleProblem(s.blockScale, LEADER_SCALE); + if (problem) return `blockScale: ${problem}`; + } if (s.scale !== undefined) { const problem = styleScaleProblem(s.scale, LEADER_SCALE); if (problem) return `scale: ${problem}`; @@ -3497,6 +3651,28 @@ export function leaderOwnProblem(given: object, scale: number): string | undefin const problem = leaderAttachmentProblem(leader.attachment); if (problem) return problem; } + if (leader.verticalAttachment !== undefined) { + const problem = leaderVerticalAttachmentProblem(leader.verticalAttachment); + if (problem) return problem; + } + if (leader.frame !== undefined && typeof leader.frame !== "boolean") return LEADER_FRAME; + if (leader.shaft !== undefined) { + const problem = leaderShaftKindProblem(leader.shaft); + if (problem) return problem; + } + if (leader.mask !== undefined) { + const problem = leaderMaskProblem(leader.mask); + if (problem) return problem; + } + if (leader.width !== undefined) { + const problem = leaderWidthProblem(leader.width); + if (problem) return `width: ${problem}`; + } + if (leader.farShafts !== undefined) { + // The far root's point comes from the note, so a shaft of one point is held to it once drawn. + const problem = leaderShaftsProblem(leader.farShafts, [Number.NaN, Number.NaN]); + if (problem) return `farShafts: ${problem}`; + } if (leader.textStyle !== undefined) { if (typeof leader.textStyle !== "string") return "textStyle: a text style is named by a string"; const problem = textStyleNameProblem(leader.textStyle); diff --git a/src/shape.ts b/src/shape.ts index fb60aaf..19cb577 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -541,14 +541,23 @@ function shapes(all: boolean, typed = all): Shapes { kind, layer: string, style: ruled(string), - text: ruled(list(string)), at: point, shafts: ruled(list(list(point))), }, { id: ruled(string), + text: ruled(list(string)), + block: ruled(string), + attributes: ruled(map(string)), side: ruled(string), attachment: ruled(string), + verticalAttachment: ruled(string), + width: ruled(number), + frame: ruled(boolean), + // true, false or an object: the rule reports any other. + mask: LEFT, + shaft: ruled(string), + farShafts: ruled(list(list(point))), textStyle: ruled(string), textHeight: ruled(number), arrowSize: ruled(number), @@ -683,6 +692,13 @@ function shapes(all: boolean, typed = all): Shapes { textStyle: ruled(string), arrowhead: ruled(string), attachment: ruled(string), + direction: ruled(string), + verticalAttachment: ruled(string), + frame: ruled(boolean), + shaft: ruled(string), + block: ruled(string), + blockConnection: ruled(string), + blockScale: ruled(number), scale: ruled(number), }, ), diff --git a/src/standard/default.ts b/src/standard/default.ts index 225d3ca..8f43401 100644 --- a/src/standard/default.ts +++ b/src/standard/default.ts @@ -23,13 +23,14 @@ const architectural = (id: string, label: string, inches: number) => export const BUILT_IN_DOCUMENT = { id: "tsdraft", - version: "2", + version: "3", paperUnits: "in", minTextHeight: 0.0625, linetypeScale: 0.5, plotStyle: "monochrome.ctb", defaultSheetFormat: "arch-d", defaultDimensionStyle: "dims", + defaultLeaderStyle: "notes", disciplines: { G: { title: "General" }, C: { title: "Civil" }, @@ -133,6 +134,18 @@ export const BUILT_IN_DOCUMENT = { description: "Closed filled arrows, with the text centered in a break of the line", }, }, + leaderStyles: { + notes: { + role: "note", + arrowhead: "closed-filled", + arrowSize: 0.125, + landing: 0.125, + gap: 0.0625, + attachment: "first-line", + description: + "Notes in the note role, a closed filled arrow, the landing meeting the first line", + }, + }, titleBlocks: { plain: { paper: "ARCH D", diff --git a/src/standard/define.ts b/src/standard/define.ts index 70b180f..25e2aec 100644 --- a/src/standard/define.ts +++ b/src/standard/define.ts @@ -146,7 +146,7 @@ const plainDrawing = (): Drawing => (plain ??= remember(frozen(plainTitleBlock() * standard. A change to what it states needs a new version, which the CHANGELOG gives, and then * this hash. */ -const BUILT_IN_HASH = "1362b9bbdeb7f2e7ef79c87edb2e234329d86488513561beb27c351ffd9b214c"; +const BUILT_IN_HASH = "8b06bfddcddd73c7256c66c35f94a2446709c22939b303a0e6daaf19ba2e05ae"; let builtIn: Standard | undefined; /** The built-in standard, made once. */ diff --git a/src/standard/document.ts b/src/standard/document.ts index 7e73b79..02af2c1 100644 --- a/src/standard/document.ts +++ b/src/standard/document.ts @@ -12,7 +12,15 @@ import type { LeaderArrowhead, ZERO_SUPPRESSIONS, } from "../arrowheads.ts"; -import type { Drawing, LeaderAttachment, Point, Units } from "../drawing.ts"; +import type { + Drawing, + LeaderAttachment, + LeaderDirection, + LeaderShaftKind, + LeaderVerticalAttachment, + Point, + Units, +} from "../drawing.ts"; import type { Font } from "../fonts.ts"; import type { PaperUnit } from "../paper.ts"; import type { Paper, PlotStyleTable } from "../papers.ts"; @@ -218,6 +226,10 @@ export interface LeaderStyleFieldsDocument extends Commented { readonly landing?: number; readonly gap?: number; readonly attachment?: string; + readonly direction?: string; + readonly verticalAttachment?: string; + readonly frame?: boolean; + readonly shaft?: string; readonly description?: string; } @@ -405,6 +417,10 @@ export interface StandardLeaderStyleFields { readonly landing?: number; readonly gap?: number; readonly attachment?: LeaderAttachment; + readonly direction?: LeaderDirection; + readonly verticalAttachment?: LeaderVerticalAttachment; + readonly frame?: boolean; + readonly shaft?: LeaderShaftKind; readonly description?: string; } @@ -415,6 +431,10 @@ export interface StandardLeaderStyle { readonly landing: number; readonly gap: number; readonly attachment: LeaderAttachment; + readonly direction: LeaderDirection; + readonly verticalAttachment: LeaderVerticalAttachment; + readonly frame: boolean; + readonly shaft: LeaderShaftKind; readonly discipline?: string; readonly description?: string; readonly byDiscipline?: { readonly [discipline: string]: StandardLeaderStyleFields }; diff --git a/src/standard/lint.ts b/src/standard/lint.ts index 7a023e5..5c22e61 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -432,6 +432,10 @@ export function lintStandard( ["landing", style.landing, fields.landing], ["gap", style.gap, fields.gap], ["attachment", style.attachment ?? "first-line", fields.attachment], + ["direction", style.direction ?? "horizontal", fields.direction], + ["verticalAttachment", style.verticalAttachment ?? "center", fields.verticalAttachment], + ["frame", style.frame ?? false, fields.frame], + ["shaft", style.shaft ?? "straight", fields.shaft], [ "scale", style.scale ?? 1, diff --git a/src/standard/shape.ts b/src/standard/shape.ts index a40164e..e7b594a 100644 --- a/src/standard/shape.ts +++ b/src/standard/shape.ts @@ -41,9 +41,15 @@ import { layerColorProblem, layerNameProblem, LEADER_ATTACHMENTS, + LEADER_DIRECTIONS, + LEADER_SHAFT_KINDS, + LEADER_VERTICAL_ATTACHMENTS, leaderArrowheadProblem, leaderAttachmentProblem, + leaderDirectionProblem, + leaderShaftKindProblem, leaderSizeProblem, + leaderVerticalAttachmentProblem, lineweightValueProblem, linetypeProblem, linetypeScaleProblem, @@ -602,9 +608,31 @@ const LEADER_FIELDS = { gap: size(leaderSizeProblem, "The gap between the end of the landing and the note"), attachment: { node: string({ enum: LEADER_ATTACHMENTS }, leaderAttachmentProblem), - description: "Which line of the note the landing meets, at the middle of its capitals", + description: "Where the landing meets the side of the note: one of LEADER_ATTACHMENTS", default: "first-line", }, + direction: { + node: string({ enum: LEADER_DIRECTIONS }, leaderDirectionProblem), + description: + 'Whether the landing meets the side of the note, "horizontal", or its top or bottom, "vertical"', + default: "horizontal", + }, + verticalAttachment: { + node: string({ enum: LEADER_VERTICAL_ATTACHMENTS }, leaderVerticalAttachmentProblem), + description: + 'Where the landing meets a note above or below it: "center", or "line" with a line as wide as the note', + default: "center", + }, + frame: { + node: boolean, + description: "True for a frame around each note, one gap outside it", + default: false, + }, + shaft: { + node: string({ enum: LEADER_SHAFT_KINDS }, leaderShaftKindProblem), + description: 'How the shafts run through their points: "straight", or "curved"', + default: "straight", + }, description, } as const satisfies FieldsOf; diff --git a/src/svg.ts b/src/svg.ts index 2490c40..44723ce 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -74,7 +74,7 @@ import { fontInfo, STANDARD_FONT, capHeightOf } from "./fonts.ts"; import { fmt, written } from "./format.ts"; import { layerKey, layerKeys } from "./layers.ts"; import { findLayout, validViewportView } from "./layouts.ts"; -import { leaderPicture, type LeaderPicture } from "./leaders.ts"; +import { leaderBlock, leaderPicture, type LeaderPicture } from "./leaders.ts"; import { builtInLinetype, LINEWEIGHTS, lineweightCode } from "./linetypes.ts"; import { drawnValue, inStyle, layoutText } from "./measure.ts"; import { @@ -526,7 +526,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ): LeaderPicture => { const known = pictures.get(e); if (known?.style === style && known.textStyle === textStyle) return known.picture; - const picture = leaderPicture(e, style, textStyle); + const picture = leaderPicture(e, style, textStyle, (name) => blocks.get(key(name))); pictures.set(e, { style, textStyle, picture }); return picture; }; @@ -709,7 +709,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const named = e.textStyle ?? style?.textStyle; const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); const picture = style === undefined ? undefined : pictureOf(e, style, textStyle); - return leaderToSvg(e, picture, textStyle, mark, drawnPen, look, matrix, room, sides); + const layOut = () => paragraphs.layout(paragraphInStyle(picture!.note, textStyle)); + return leaderToSvg(e, picture, layOut, mark, drawnPen, look, matrix, room, sides); } if (e.kind === "image") { // One whose fields cannot be drawn, which `lint` refuses, draws nothing. @@ -818,9 +819,29 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): * holds is judged entity by entity, unless the insert's own layer is frozen. */ const shownOf = (entities: readonly Entity[]): [number, Entity][] => - [...filled(entities).entries()].filter(([, e]) => - e.kind === "insert" ? !frozen({ name: e.layer }) : !hidden({ name: e.layer }), - ); + [...filled(entities).entries()] + .filter(([, e]) => + e.kind === "insert" ? !frozen({ name: e.layer }) : !hidden({ name: e.layer }), + ) + .flatMap(([i, e]): [number, Entity][] => { + // A leader whose content is a block draws the block as an insert of it, after itself. + const content = e.kind === "leader" ? contentOf(e) : undefined; + return content === undefined + ? [[i, e]] + : [ + [i, e], + [i, content], + ]; + }); + /** The insert of the block in place of a leader's note, where its picture places it. */ + const contentOf = (e: Leader): Insert | undefined => { + const tables = tablesOf(undefined); + const style = tables.leaderStyles.get(key(e.style)); + if (style === undefined || leaderBlock(e, style) === undefined) return undefined; + const named = e.textStyle ?? style.textStyle; + const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); + return pictureOf(e, style, textStyle).block; + }; /** * An element for each entity that is drawn, as `look` draws it, in the space `space` names. @@ -1302,7 +1323,7 @@ function styled(e: Drawn): Pick { function leaderToSvg( e: Leader, picture: LeaderPicture | undefined, - textStyle: TextStyle | undefined, + layOut: () => ParagraphLayout, mark: string, pen: Pen, look: Look, @@ -1331,16 +1352,23 @@ function leaderToSvg( .map(at) .map(([x, y]) => `${fmt(x)},${fmt(y)}`) .join(" "); + // A mask hides what is drawn before the leader, and none of the leader's own parts. + if (picture.mask) { + const color = picture.mask.color; + const fill = color === undefined ? "#ffffff" : color === 256 ? pen.color : look.color(color); + // One in the drawing's background is marked, for a viewer whose background is not white. + const background = color === undefined ? ` data-mask="background"` : ""; + add( + () => + ``, + ); + } for (const shaft of picture.shafts) { shape("shaft", { kind: "polyline", layer: e.layer, points: shaft, closed: false }); } - if (picture.landing) { - shape("landing", { - kind: "line", - layer: e.layer, - from: picture.landing[0], - to: picture.landing[1], - }); + for (const landing of [picture.landing, picture.farLanding]) { + if (landing) + shape("landing", { kind: "line", layer: e.layer, from: landing[0], to: landing[1] }); } for (const arrowhead of picture.arrowheads) { if (arrowhead.filled.length > 0) { @@ -1362,18 +1390,13 @@ function leaderToSvg( ); } } - for (const line of picture.lines) { - const text: Text = { - kind: "text", - layer: e.layer, - at: line.at, - height: line.height, - value: line.value, - rotation: 0, - ...(line.align === "right" ? { align: "right" as const } : {}), - }; - add((left) => entityToSvg(text, `data-part="text"`, pen, look, textStyle, matrix, left)); + for (const [from, to] of picture.underlines) { + shape("underline", { kind: "line", layer: e.layer, from, to }); + } + if (picture.frame) { + shape("frame", { kind: "polyline", layer: e.layer, points: picture.frame, closed: true }); } + add((left) => paragraphToSvg(picture.note, layOut, `data-part="text"`, pen, look, matrix, left)); return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } diff --git a/standard.json b/standard.json index 70f1935..a63c880 100644 --- a/standard.json +++ b/standard.json @@ -1,7 +1,7 @@ { "$schema": "https://cdn.jsdelivr.net/npm/tsdraft@0.5.3/standard.schema.json", "id": "tsdraft", - "version": "2", + "version": "3", "title": "tsdraft", "paperUnits": "in", "minTextHeight": 0.0625, @@ -10,6 +10,7 @@ "sheetFiles": "one-drawing", "defaultSheetFormat": "arch-d", "defaultDimensionStyle": "dims", + "defaultLeaderStyle": "notes", "disciplines": { "C": { "title": "Civil" @@ -360,7 +361,21 @@ "description": "Feet and inches to the nearest 1/16\", as 4'-1 7/16\"" } }, - "leaderStyles": {}, + "leaderStyles": { + "notes": { + "role": "note", + "arrowhead": "closed-filled", + "arrowSize": 0.125, + "landing": 0.125, + "gap": 0.0625, + "attachment": "first-line", + "direction": "horizontal", + "verticalAttachment": "center", + "frame": false, + "shaft": "straight", + "description": "Notes in the note role, a closed filled arrow, the landing meeting the first line" + } + }, "titleBlocks": { "plain": { "paper": "ARCH D", diff --git a/standard.schema.json b/standard.schema.json index 02a62ce..dfd8677 100644 --- a/standard.schema.json +++ b/standard.schema.json @@ -610,10 +610,43 @@ }, "attachment": { "type": "string", - "enum": ["first-line", "last-line"], - "description": "Which line of the note the landing meets, at the middle of its capitals", + "enum": [ + "top-of-first", + "first-line", + "middle", + "last-line", + "bottom-of-last", + "underline-last", + "underline-first", + "bottom-of-first", + "underline-all" + ], + "description": "Where the landing meets the side of the note: one of LEADER_ATTACHMENTS", "default": "first-line" }, + "direction": { + "type": "string", + "enum": ["horizontal", "vertical"], + "description": "Whether the landing meets the side of the note, \"horizontal\", or its top or bottom, \"vertical\"", + "default": "horizontal" + }, + "verticalAttachment": { + "type": "string", + "enum": ["center", "line"], + "description": "Where the landing meets a note above or below it: \"center\", or \"line\" with a line as wide as the note", + "default": "center" + }, + "frame": { + "type": "boolean", + "description": "True for a frame around each note, one gap outside it", + "default": false + }, + "shaft": { + "type": "string", + "enum": ["straight", "curved"], + "description": "How the shafts run through their points: \"straight\", or \"curved\"", + "default": "straight" + }, "description": { "type": "string", "pattern": "^[\\u0020-\\u007e\\u0080-\\ud7ff\\ue000-\\ue7ff\\ue900-\\uffff]*$", @@ -671,8 +704,37 @@ }, "attachment": { "type": "string", - "enum": ["first-line", "last-line"], - "description": "Which line of the note the landing meets, at the middle of its capitals" + "enum": [ + "top-of-first", + "first-line", + "middle", + "last-line", + "bottom-of-last", + "underline-last", + "underline-first", + "bottom-of-first", + "underline-all" + ], + "description": "Where the landing meets the side of the note: one of LEADER_ATTACHMENTS" + }, + "direction": { + "type": "string", + "enum": ["horizontal", "vertical"], + "description": "Whether the landing meets the side of the note, \"horizontal\", or its top or bottom, \"vertical\"" + }, + "verticalAttachment": { + "type": "string", + "enum": ["center", "line"], + "description": "Where the landing meets a note above or below it: \"center\", or \"line\" with a line as wide as the note" + }, + "frame": { + "type": "boolean", + "description": "True for a frame around each note, one gap outside it" + }, + "shaft": { + "type": "string", + "enum": ["straight", "curved"], + "description": "How the shafts run through their points: \"straight\", or \"curved\"" }, "description": { "type": "string", diff --git a/test/leaders.test.ts b/test/leaders.test.ts index 3e10bb7..8967982 100644 --- a/test/leaders.test.ts +++ b/test/leaders.test.ts @@ -8,6 +8,7 @@ import { leaderPicture, lineSpacing, lint, + readDXF, toDXF, toSVG, type Drawing, @@ -43,7 +44,20 @@ test("a leader style and a leader are checked as literals and when the code runs assert.throws(() => d.leaderStyle({ ...STYLE, name: "A", textHeight: 0 }), /textHeight/); // @ts-expect-error: a scale is above 0. assert.throws(() => d.leaderStyle({ ...STYLE, name: "A", scale: 0 }), /scale: .*greater than 0/); + // @ts-expect-error: an attachment is one of LEADER_ATTACHMENTS. + assert.throws(() => d.leaderStyle({ ...STYLE, name: "A", attachment: "top" }), /LEADER_ATT/); + // @ts-expect-error: a direction is horizontal or vertical. + assert.throws(() => d.leaderStyle({ ...STYLE, name: "A", direction: "up" }), /direction/); + // @ts-expect-error: a vertical attachment is center or line. + assert.throws(() => d.leaderStyle({ ...STYLE, name: "A", verticalAttachment: "top" }), /center/); d.leaderStyle({ ...STYLE, name: "NOTES", arrowhead: "dot", attachment: "last-line" }); + d.leaderStyle({ + ...STYLE, + name: "UP", + direction: "vertical", + verticalAttachment: "line", + frame: true, + }); assert.throws(() => d.leaderStyle({ ...STYLE, name: "notes" }), /already has a leader style/); const at = [1, 1] as const; @@ -62,6 +76,46 @@ test("a leader style and a leader are checked as literals and when the code runs assert.throws(() => d.leader("A", { style: "NOTES", at, to: [] }), /needs a shaft/); assert.throws(() => d.leader("A", { style: "NOTES", at, to: [1, 1] }), /one point/); assert.throws(() => d.leader("A", { style: "NOTES", at, to: [0, 0], textStyle: "NONE" }), /NONE/); + // @ts-expect-error: a note wraps at a width greater than 0. + assert.throws(() => d.leader("A", { style: "NOTES", at, to: [0, 0], width: 0 }), /width/); + // @ts-expect-error: a side is one of LEADER_SIDES. + assert.throws(() => d.leader("A", { style: "NOTES", at, to: [0, 0], side: "up" }), /side/); + const offsetFactor = 9; + assert.throws( + () => d.leader("A", { style: "NOTES", at, to: [0, 0], mask: { offsetFactor } }), + /mask/, + ); + d.leader("A", { style: "UP", at, to: [0, 0], width: 2, mask: { color: 1 } }); + // A block in place of the note is one the drawing defines, and takes nothing only a note has. + d.block("TAG", {}, () => d.circle([0, 0], 0.1)); + assert.throws(() => d.leader({ block: "NONE" }, { style: "NOTES", at, to: [0, 0] }), /NONE/); + assert.throws( + () => d.leader({ block: "TAG" }, { style: "NOTES", at, to: [0, 0], width: 1 }), + /width/, + ); + d.leader( + { block: "TAG" }, + { style: "NOTES", at, to: [0, 0], toFarSide: [3, 0], shaft: "curved" }, + ); + // @ts-expect-error: a kind of shaft is straight or curved. + assert.throws(() => d.leader("A", { style: "NOTES", at, to: [0, 0], shaft: "bent" }), /shaft/); + assert.throws( + () => d.leader("A", { style: "NOTES", at, to: [0, 0], toFarSide: [] }), + /needs a shaft/, + ); + // A value names an attribute of the block, and a style's block is one the drawing defines. + assert.throws( + () => d.leader({ block: "TAG", attributes: { NUM: "7" } }, { style: "NOTES", at, to: [0, 0] }), + /no attribute with the tag "NUM"/, + ); + d.leaderStyle({ ...STYLE, name: "KEYS", block: "NONE" }); + assert.match( + lint(d.build()) + .map((x) => x.message) + .join("\n"), + /Leader style "KEYS": Block "NONE"/, + ); + d.leader("A", { style: "NOTES", at, to: [0, 0], side: "below", frame: true, mask: true }); d.leader("A", { style: "notes", at, @@ -112,6 +166,31 @@ test("lint finds what the builder refuses, in a drawing built by hand", () => { "leader-style", "undefined-leader-style", ]); + // A block in place of the note whose polyline has a side with no point is reported, not read. + const side = { kind: "polyline", layer: "0", points: [null, [2, 0]], bulges: [1] } as never; + assert.deepEqual( + rules( + [{ kind: "leader", layer: "0", style: "NOTES", block: "B", at: [1, 1], shafts: [[[0, 0]]] }], + { + blocks: [{ name: "B", entities: [side] }], + }, + ), + ["format", "format"], + ); +}); + +test("a block's label comes back from a DXF as an attribute's value does", async () => { + const d = createDrawing(); + d.leaderStyle({ name: "NOTES", ...STYLE }); + d.block("KEY", {}, () => d.circle([0, 0], 0.1).attribute("NUM", [0, 0], { height: 0.1 })); + const value = "\\U+0000 ^J"; + d.leader( + { block: "KEY", attributes: { NUM: value } }, + { style: "NOTES", at: [0, 1], to: [0, 0] }, + ); + const read = await readDXF(toDXF(d.build()), { geometry: true }); + const [leader] = read.model.entities ?? []; + assert.equal(leader?.kind === "multileader" && leader.block?.attributes?.NUM, value); }); test("a leader is drawn where the leading CAD app draws it", () => { @@ -154,25 +233,17 @@ test("a leader is drawn where the leading CAD app draws it", () => { [9, 1], [10, 5], ]); - // The middle of the first line's capitals is level with `at`, the lines 5/3 of the height apart. - const pitch = lineSpacing(0.2); - assert.deepEqual(right.location, [10.5, 5.1]); - assert.deepEqual( - right.lines.map((line) => [line.align, line.at[0], Number((line.at[1] - 5).toFixed(12))]), - [ - ["left", 10.5, -0.1], - ["left", 10.5, Number((-0.1 - pitch).toFixed(12))], - ["left", 10.5, Number((-0.1 - 2 * pitch).toFixed(12))], - ], - ); - // On the left, held by its last line, the note is justified right. + // The note is a paragraph held by its top left a gap past the landing, with the middle of its + // first line, from its top to its baseline, level with `at`. + const first = right.lines[0]!; + assert.deepEqual([right.noteAttachment, right.note.align, right.location[0]], [1, "left", 10.5]); + assert.ok(Math.abs((right.location[1] + first.at[1]) / 2 - 5) < 1e-12); + // On the left, held by its last line, the note is held by its top right and justified right, + // and the middle of its last line is level with `at`. const left = leaderPicture({ ...leader, side: "left", attachment: "last-line" }, style); assert.equal(left.direction, -1); - assert.ok(Math.abs(left.lines.at(-1)!.at[1] - 4.9) < 1e-12); - assert.deepEqual( - left.lines.map((line) => [line.align, line.at[0]]), - left.lines.map(() => ["right", 9.5]), - ); + assert.deepEqual([left.noteAttachment, left.note.align, left.location[0]], [3, "right", 9.5]); + assert.ok(left.location[1] > right.location[1]); // A dot is a disk as wide as the arrow size, and with no arrowhead the shaft runs to the tip. const dot = leaderPicture(leader, { ...style, arrowhead: "dot" }).arrowheads[0]!; assert.deepEqual( diff --git a/test/read-agreement.ts b/test/read-agreement.ts index e802084..edf3559 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -450,12 +450,15 @@ export function readProblems( const style = findLeaderStyle(drawing, want.style); if (!style) return; const named = want.textStyle ?? style.textStyle; - const picture = leaderPicture(want, style, styleOf(named)); + const picture = leaderPicture(want, style, styleOf(named), (name) => + blocks.get(layerKey(name)), + ); if (!sameName(got.style, style.name)) say(`${label}: style ${got.style}`); if (!sameName(got.textStyle, styleOf(named)?.name ?? named ?? "Standard")) { say(`${label}: note in ${got.textStyle}`); } - if (got.text !== once(want.text.join("\\P"))) + // The note as written, with the code an underline of every line puts before it. + if (got.text !== once(picture.note.value)) say(`${label}: note ${JSON.stringify(got.text)}`); const loose = by === "cad"; for (const [what, a, b] of [ @@ -467,7 +470,9 @@ export function readProblems( if (!near(a, b, loose)) say(`${label}: ${what} ${a}, expected ${b}`); } if (!nearPoint(got.at, picture.connection, loose)) say(`${label}: at ${got.at}`); - if (!nearPoint(got.textAt, picture.location, loose)) say(`${label}: note at ${got.textAt}`); + // A block in place of the note is held at the block's point. + const noteAt = picture.block === undefined ? picture.location : point(picture.block.at); + if (!nearPoint(got.textAt, noteAt, loose)) say(`${label}: note at ${got.textAt}`); if ( got.shafts.length !== want.shafts.length || got.shafts.some( diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index 4ef4498..bf99141 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -85,11 +85,185 @@ export function seedFiles(): Uint8Array[] { images.insert("LOGO", [0, 10]); }); return [ - toDXF(sheet), - toDXF(kitchen), - toDXF(d.build(), { version: "R12" }), - toDXF(images.build()), - ].map((t) => encoder.encode(t)); + ...[ + toDXF(sheet), + toDXF(kitchen), + toDXF(d.build(), { version: "R12" }), + toDXF(images.build()), + ].map((t) => encoder.encode(t)), + leaderFile(), + ]; +} + +type Pair = readonly [code: number, value: string | number]; + +/** A multileader's record, with a note or a block, from its roots: each a list of shafts. */ +function multileaderRecord( + handle: string, + roots: readonly (readonly (readonly Pair[])[])[], + options: { block?: boolean; shaft?: number; labels?: readonly string[] }, +): Pair[] { + const out: Pair[] = [ + [0, "MULTILEADER"], + [5, handle], + [8, "0"], + [100, "AcDbMLeader"], + ]; + out.push([270, 2], [300, "CONTEXT_DATA{"], [40, 1], [10, 5], [20, 5], [30, 0], [41, 0.18]); + out.push([140, 0.18], [145, 0.09], [174, 1], [175, 1], [176, 0], [177, 0]); + if (options.block) { + out.push([290, 0], [296, 1], [341, "1F"], [14, 0], [24, 0], [34, 1], [15, 6], [25, 5]); + out.push([35, 0], [16, 2], [26, 2], [36, 2], [46, 0.5], [93, -1056964608]); + for (let i = 0; i < 16; i++) out.push([47, i % 5 === 0 ? 1 : 0]); + } else { + out.push([290, 1], [304, "NOTE\\PTWO"], [11, 0], [21, 0], [31, 1], [340, "11"]); + out.push([12, 6], [22, 5], [32, 0], [13, 1], [23, 0], [33, 0], [42, 0], [43, 2], [44, 0]); + out.push([45, 1], [170, 1], [90, -1073741824], [171, 1], [172, 5], [91, -1023410175]); + out.push([141, 1.5], [92, 0], [291, 0], [292, 1], [293, 0], [294, 0], [296, 0]); + } + out.push([110, 0], [120, 0], [130, 0], [111, 1], [121, 0], [131, 0], [112, 0], [122, 1]); + out.push([132, 0], [297, 0]); + roots.forEach((lines, r) => { + out.push([302, "LEADER{"], [290, 1], [291, 1], [10, 5 - r], [20, 5], [30, 0], [11, 1]); + out.push([21, 0], [31, 0], [90, 0], [40, 0.36]); + lines.forEach((points, l) => out.push([304, "LEADER_LINE{"], ...points, [91, l], [305, "}"])); + out.push([271, 0], [303, "}"]); + }); + out.push([272, 9], [273, 9], [301, "}"], [340, "12"], [90, 6816768], [170, options.shaft ?? 1]); + out.push([91, -1056964608], [341, "14"], [171, -2], [290, 1], [291, 1], [41, 0.36], [42, 0.18]); + out.push([172, options.block ? 1 : 2], [343, "11"], [173, 1], [95, 1], [174, 1], [175, 0]); + out.push([92, -1056964608], [292, 1], [344, "1F"], [93, -1056964608], [10, 1], [20, 1]); + out.push([30, 1], [43, 0], [176, 0], [293, 0]); + (options.labels ?? []).forEach((definition, i) => + out.push([330, definition], [177, i], [44, 0], [302, `V${i}`]), + ); + out.push([294, 0], [178, 0], [179, 1], [45, 1], [271, 1], [272, 9], [273, 9], [295, 0]); + return out; +} + +/** An old leader's record through `points`, with its note's handle unless it has none. */ +const leaderRecord = (handle: string, points: number, more: readonly Pair[]): Pair[] => [ + [0, "LEADER"], + [5, handle], + [8, "0"], + [100, "AcDbLeader"], + [3, "Standard"], + ...more, + [76, points], + ...Array.from({ length: points }, (_, i): Pair[] => [ + [10, i], + [20, i % 2], + [30, 0], + ]).flat(), +]; + +/** + * A file of multileaders of many roots, shafts and points, one whose block has labels, of more + * definitions than a read keeps among them, and old leaders, one of many points and one in 3D. + */ +function leaderFile(): Uint8Array { + const shaft = (n: number): Pair[] => + Array.from({ length: n }, (_, i): Pair[] => [ + [10, i], + [20, i], + [30, 0], + ]).flat(); + const roots = (r: number, l: number, n: number) => + Array.from({ length: r }, () => Array.from({ length: l }, () => shaft(n))); + const labels = [ + "2A", + ...Array.from({ length: 1200 }, (_, i) => (0x1000 + i).toString(16)), + "2B", + "2A", + "0", + "zz", + ]; + const groups: Pair[] = [ + ...([ + [0, "SECTION"], + [2, "HEADER"], + [9, "$ACADVER"], + [1, "AC1032"], + [0, "ENDSEC"], + ] as Pair[]), + ...([ + [0, "SECTION"], + [2, "TABLES"], + [0, "TABLE"], + [2, "BLOCK_RECORD"], + ] as Pair[]), + ...([ + [0, "BLOCK_RECORD"], + [5, "1F"], + [2, "TAG"], + [0, "ENDTAB"], + [0, "ENDSEC"], + ] as Pair[]), + ...([ + [0, "SECTION"], + [2, "BLOCKS"], + [0, "BLOCK"], + [5, "20"], + [330, "1F"], + [8, "0"], + ] as Pair[]), + ...([ + [2, "TAG"], + [70, 2], + [10, 0], + [20, 0], + ] as Pair[]), + ...(["2A", "2B"].flatMap((h, i) => [ + [0, "ATTDEF"], + [5, h], + [330, "1F"], + [8, "0"], + [10, 0], + [20, i], + [40, 0.1], + [1, "1"], + [3, "Prompt"], + [2, `T${i}`], + [70, 0], + ]) as Pair[]), + ...([ + [0, "ENDBLK"], + [5, "21"], + [330, "1F"], + [8, "0"], + [0, "ENDSEC"], + ] as Pair[]), + ...([ + [0, "SECTION"], + [2, "ENTITIES"], + ] as Pair[]), + ...multileaderRecord("40", roots(3, 4, 6), { shaft: 2 }), + ...multileaderRecord("41", roots(2, 1, 2), { block: true, labels }), + ...multileaderRecord("42", [], { shaft: 0 }), + ...multileaderRecord("43", [[]], {}), + ...multileaderRecord("44", roots(50, 10, 40), { block: true, labels: ["2A"] }), + ...leaderRecord("50", 3, [ + [71, 0], + [72, 1], + [73, 0], + [340, "40"], + ]), + ...leaderRecord("51", 5000, []), + ...leaderRecord("52", 2, [ + [73, 0], + [340, "41"], + [210, 1], + [220, 0], + [230, 0], + ]), + ...([ + [0, "ENDSEC"], + [0, "EOF"], + ] as Pair[]), + ]; + return encoder.encode( + groups.map(([code, value]) => `${String(code).padStart(3)}\r\n${value}\r\n`).join(""), + ); } const NUMBERS = ["0", "1", "-1", "4294967295", "1e308", "-1e308", "1e999", "NaN", "", "1.#QNAN"]; @@ -132,7 +306,7 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { const at = index(groups.length); const group = groups[at]; if (!group) break; - switch (index(11)) { + switch (index(12)) { case 0: { // Codes swapped. const other = groups[index(groups.length)]!; @@ -195,8 +369,21 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { 73, 90, 102, + 76, + 170, + 172, + 177, + 290, + 296, + 300, + 301, + 302, + 303, + 304, + 305, 330, 340, + 341, 360, 1001, index(1100), @@ -219,6 +406,7 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { "MTEXT", "DIMENSION", "MULTILEADER", + "LEADER", "SECTION", "ENDSEC", "BLOCK", @@ -244,6 +432,19 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { if (handles.length > 1) pick(handles)[1] = pick(handles)[1]; break; } + case 11: { + // A run of a record's groups repeated, such as a multileader's roots, shafts, points or + // labels, up to a million groups in all. + const [from, to] = record(); + const start = from + index(to - from); + const end = start + 1 + index(Math.min(40, to - start)); + const copies = Math.min(1 + index(2000), Math.floor(1e6 / (end - start))); + const run = groups.slice(start, end); + const after = groups.splice(end); + for (let k = 0; k < copies; k++) for (const g of run) groups.push([...g]); + for (const g of after) groups.push(g); + break; + } } } return encoder.encode(textOf(groups)); diff --git a/test/read.test.ts b/test/read.test.ts index d8a5427..b4445c4 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -1018,8 +1018,11 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only [0, "MULTILEADER"], [8, "A"], [300, "CONTEXT_DATA{"], + [290, 1], + [11, 1], + [21, 0], + [31, 0], [301, "}"], - [172, 1], ], [ [0, "LINE"], @@ -1062,7 +1065,7 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only assert.deepEqual(Object.keys(plain(plainLine) as object).sort(), ["from", "kind", "layer", "to"]); assert.deepEqual(plain(read.model.other), { "DIMENSION angular": 1, - "MULTILEADER with a block": 1, + "MULTILEADER in 3D": 1, }); assert.deepEqual(plain(read.unread.malformed), { "LINE with a number that is not finite": 1 }); assert.deepEqual(read.opensAt, { center: [6, 7], height: 10, width: 15 }); diff --git a/test/shape.test.ts b/test/shape.test.ts index c048bb6..37b2331 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -22,6 +22,7 @@ import { type Layout, type LeaderStyle, type Linetype, + type Leader, type Polyline, type TextStyle, type Viewport, @@ -34,12 +35,15 @@ const justified = { style: "NOTES", align: "center", valign: "middle" } as const /** * Each kind of entity with every field it can have: a field left out is a compile error. A - * polyline has a width or widths for each side, and `wide` has the other. + * polyline has a width or widths for each side, and `wide` has the other. A leader has a note, + * and `keyed` a block in its place. */ const kinds: { readonly [K in Entity["kind"]]: K extends "polyline" ? Required> - : Required>; + : K extends "leader" + ? Required> + : Required>; } = { line: { kind: "line", layer: "WALL", from: [0, 0], to: [10, 0], id: "a", ...styled }, polyline: { @@ -147,6 +151,12 @@ const kinds: { ], side: "right", attachment: "last-line", + verticalAttachment: "line", + width: 2, + frame: true, + mask: { color: 1, offsetFactor: 1.25 }, + shaft: "curved", + farShafts: [[[45, 5]]], textStyle: "NOTES", textHeight: 0.08, arrowSize: 0.05, @@ -221,6 +231,35 @@ const wide: Required> = { ...styled, }; +const keyed: Required< + Omit< + Leader, + | "text" + | "attachment" + | "verticalAttachment" + | "width" + | "frame" + | "mask" + | "textStyle" + | "textHeight" + > +> = { + kind: "leader", + layer: "0", + style: "NOTE", + block: "TREE", + attributes: { TAG: "T-2" }, + at: [60, 10], + shafts: [[[55, 5]]], + side: "right", + shaft: "straight", + farShafts: [[[65, 5]]], + arrowSize: 0.05, + landing: 0.1, + gap: 0.02, + id: "keyed", +}; + /** One of everything an R2018 drawing can hold, with every field of every object. */ const full: Required & { readonly linetypes: readonly [Required]; @@ -309,6 +348,13 @@ const full: Required & { landing: 0.1, gap: 0.05, attachment: "first-line", + direction: "vertical", + verticalAttachment: "line", + frame: true, + shaft: "curved", + block: "TREE", + blockConnection: "insertion", + blockScale: 2, scale: 10, }, ], @@ -353,6 +399,7 @@ const full: Required & { ...Object.values(kinds), { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }, wide, + keyed, ], layouts: [ { diff --git a/test/standard.test.ts b/test/standard.test.ts index a161724..31f8e91 100644 --- a/test/standard.test.ts +++ b/test/standard.test.ts @@ -341,7 +341,7 @@ test("a child replaces an entry whole under its parent's spelling, and null remo // @ts-expect-error: the removed layer is not in the child's type. void child.layers["C-ROAD-CNTR"]; assert.equal(child.layers["A-WALL"].color, 2); - assert.deepEqual(child.chain, [{ id: "tsdraft", version: "2", hash: BUILT_IN_STANDARD.hash }]); + assert.deepEqual(child.chain, [{ id: "tsdraft", version: "3", hash: BUILT_IN_STANDARD.hash }]); assert.equal(child.title, "acme"); assert.equal(child.minTextHeight, BUILT_IN_STANDARD.minTextHeight); assert.ok( @@ -398,8 +398,8 @@ test("a child replaces an entry whole under its parent's spelling, and null remo `paperUnits: A standard that extends nothing must have the field "paperUnits"`, `minTextHeight: A standard that extends nothing must have the field "minTextHeight"`, ]); - assert.deepEqual(problems({ ...base, id: "tsdraft", version: "2" }), [ - `extends: The standard "tsdraft" version "2" extends itself`, + assert.deepEqual(problems({ ...base, id: "tsdraft", version: "3" }), [ + `extends: The standard "tsdraft" version "3" extends itself`, ]); assert.match( problems({ ...base, minTextHeight: 0.1 })[0]!, @@ -819,7 +819,7 @@ test("the hash is what the merged document states for a check", () => { const checked = defineStandard(BUILT_IN_DOCUMENT as never); assert.equal(JSON.stringify(checked), JSON.stringify(BUILT_IN_STANDARD)); assert.deepEqual(lint(BUILT_IN_STANDARD.titleBlocks.plain.block!), []); - assert.equal(BUILT_IN_STANDARD.version, "2"); + assert.equal(BUILT_IN_STANDARD.version, "3"); }); test("SHA-256 gives the digests of FIPS 180-4 and of node:crypto", () => { From cc9b806d44fe5e9db3da8e6c60b21dea789fad39 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 10:13:48 -0500 Subject: [PATCH 11/35] Angular dimensions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Angular dimensions, drawn as the leading CAD app draws them: - `d.angularDimension(vertex, from, to, at, options)` measures the angle at `vertex` between the line to `from` and the line to `to`. Its arc runs about the vertex through `at`, and `at` picks the angle as the leading CAD app does: the angle between the two lines that holds `at`, or the rest of the turn, so the order of `from` and `to` means nothing. - Each extension line runs along its line from the style's offset off its point to past the arc, out from the vertex or in toward it. The arc runs between the arrowheads or ticks, and the text stands at its middle along it, above it or centered in a break of it. Words below make a second line of the one text, which stands on the arc. Where a centered text leaves the marks no room, they turn outward with a tail past each. - A dimension style writes the angle by `angleUnits` (`"degrees"`, `"degrees-minutes-seconds"`, `"grads"` or `"radians"`), `anglePrecision` (0 to 8; in degrees, minutes and seconds it picks the parts, `123°27'24"` at 3 and 4) and `suppressAngleZeros`. Its `prefix` and `suffix` stand around the angle. A standard's dimension style takes all three. - `lint` refuses an angular dimension whose points leave no angle or no arc; one whose arc's point is on one of its lines, or whose arc passes through one of its points, where the leading CAD app decides by a rounding; one whose text would move out on a leader; one whose centered text leaves its arc no room each side; one whose closed arrowheads are as long as its arc is wide; one whose arc runs all but a whole turn, which its 6 decimals write with one angle at both ends; and words below a centered text. - `toDXF` writes them, and `readDXF` reads them as `angular-dimension`, by three points or by two lines, with the angle in degrees. The command's dimension summary lists them, with the angle in degrees. - `toSVG` and `toPDF` draw a dimension's arc. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 8 + GUIDE.md | 4 + cli/src/state.ts | 9 +- cli/src/worker.ts | 6 +- docs/dimensions.md | 52 ++++- docs/reading.md | 6 +- src/arrowheads.ts | 14 ++ src/dimensions.ts | 416 ++++++++++++++++++++++++++++++++++++++- src/drawing.ts | 98 +++++++++ src/dxf-r2018.ts | 39 +++- src/extents.ts | 10 +- src/index.ts | 7 + src/inspect.ts | 1 + src/lint.ts | 7 +- src/read/check.ts | 19 ++ src/read/dxf.ts | 3 +- src/read/entities.ts | 38 ++++ src/read/model.ts | 30 +++ src/rules.ts | 77 ++++++++ src/shape.ts | 16 ++ src/standard/document.ts | 10 + src/standard/lint.ts | 7 + src/standard/literal.ts | 16 +- src/standard/shape.ts | 21 ++ src/svg.ts | 18 ++ standard.json | 6 + standard.schema.json | 34 ++++ test/bounded.test.ts | 16 ++ test/dimensions.test.ts | 133 ++++++++++++- test/read-agreement.ts | 34 ++++ test/read.test.ts | 4 +- test/shape.test.ts | 20 +- 32 files changed, 1154 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e9bcf1..cad0ec5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,14 @@ coordinates, and lists the file's image definitions in `images`, with how many images name each, one that none names among them. The example sheet has a vicinity map above its key plan. [docs/images.md](docs/images.md) describes them. +- Angular dimensions: `angularDimension(vertex, from, to, at, options)` measures the angle at + `vertex` between the lines to `from` and `to`, its arc through `at`, which picks the angle as the + leading CAD app does: the one between the lines that holds `at`, or the rest of the turn. Drawn as + that app draws them, with the text above the arc or centered in it, words below as a second + line, and the marks turned outward where a centered text leaves them no room. A dimension style's + `angleUnits` (`"degrees"`, `"degrees-minutes-seconds"`, `"grads"` or `"radians"`), + `anglePrecision` and `suppressAngleZeros` write the angle. `toDXF` writes them, and `readDXF` + reads them as `angular-dimension`, by three points or by two lines, with the angle in degrees. - Radius, diameter and jogged radius dimensions: `radiusDimension(center, point, options)`, `diameterDimension(center, point, options)` and `joggedRadiusDimension(center, point, start, jog, options)`, drawn as the leading CAD app draws them, with the R and the diameter sign it diff --git a/GUIDE.md b/GUIDE.md index 7ff475c..429d53d 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -381,6 +381,10 @@ d.linearDimension([24, 30], [76, 30], [0, 20], { style: "PLAN" }); `joggedRadiusDimension(center, point, start, jog, options)` dimension circles and arcs; CAD writes the R and the diameter sign. `textFromCenter` places the text along the line, and a style's `radialText: "horizontal"` levels it. +- `angularDimension(vertex, from, to, at, options)` dimensions the angle at `vertex` between the + lines to `from` and `to`, its arc through `at`, which picks the angle. A style's `angleUnits`, + `anglePrecision` and `suppressAngleZeros` write it, as `37°15'30"` in + `"degrees-minutes-seconds"`. - Never draw a dimension from lines and text. [docs/dimensions.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/dimensions.md) has the rest. diff --git a/cli/src/state.ts b/cli/src/state.ts index 3738547..d0b5b69 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -355,14 +355,15 @@ export interface DimensionSummary { readonly id: string | null; readonly layer: string; /** - * `linear` measures along one direction, `aligned` from point to point, and `radius`, - * `diameter` and `jogged-radius` a circle or an arc. + * `linear` measures along one direction, `aligned` from point to point, `radius`, `diameter` + * and `jogged-radius` a circle or an arc, and `angular` the angle between two lines. */ - readonly kind: "linear" | "aligned" | "radius" | "diameter" | "jogged-radius"; + readonly kind: "linear" | "aligned" | "radius" | "diameter" | "jogged-radius" | "angular"; /** The dimension style as the dimension names it. */ readonly style: string; /** - * The length it measures, in the units of its space, before its style's measurement scale. + * The length it measures, in the units of its space, before its style's measurement scale, or + * an angular dimension's angle in degrees. * `null` when it cannot be worked out: its style is not defined, or the copy of tsdraft * the drawing loaded is from before dimensions. */ diff --git a/cli/src/worker.ts b/cli/src/worker.ts index bb6a333..5bff596 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -1553,6 +1553,7 @@ const SUMMARY_KINDS = { "radius-dimension": "radius", "diameter-dimension": "diameter", "jogged-radius-dimension": "jogged-radius", + "angular-dimension": "angular", } as const; /** Each dimension among some entities, with what the library the drawing loaded says it reads. */ @@ -1572,7 +1573,10 @@ function dimensionSummaries( : undefined; const picture = style && library.dimensionPicture?.(dimension, style); if (picture && Number.isFinite(picture.measurement)) { - read = { measurement: picture.measurement, text: picture.label.value }; + // An angle in degrees, as every angle of a drawing is. + const degrees = dimension.kind === "angular-dimension"; + const measurement = degrees ? (picture.measurement * 180) / Math.PI : picture.measurement; + read = { measurement, text: picture.label.value }; } } catch { // A dimension or a style that breaks a rule, which the diagnostics say. diff --git a/docs/dimensions.md b/docs/dimensions.md index fcad012..11814be 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -188,6 +188,55 @@ A dimension style sets two things of these kinds alone: or its diameter sign; a placed text in a style that levels the text or centers it in the line; a jogged one in a style that centers its text; and a radius of 0. +### Angular + +`d.angularDimension(vertex, from, to, at, options)` measures the angle at `vertex` between the line +to `from` and the line to `to`. Its arc runs about the vertex through `at`, and `at` picks the +angle, as the leading CAD app picks it: the angle between the two lines that holds `at`, or the rest +of the turn when `at` is on the other side, so the order of `from` and `to` means nothing. + +```ts +d.angularDimension([0, 0], [10, 0], [0, 10], [6, 6], { style: "DIMS" }); // 90° +d.angularDimension([0, 0], [10, 0], [0, 10], [-6, -6], { style: "DIMS" }); // 270° +``` + +Each extension line runs along its line, from the style's offset off its point toward the arc, to +the style's length past the arc: out from the vertex when the arc is beyond the point, and in +toward it when the arc is nearer. The arc runs between the arrowheads, each a chord of the arrow +size long, or between the ticks. The text stands at the middle of the arc, turned along it to read +upright: a gap above it, or centered in a break of it. Words below make a second line of the one +text, which stands on the arc, `90°` over the arc and `MIN.` under it. + +Where a centered text and its gaps leave the marks no room on the arc, the marks turn outward, each +with a tail an arrow size long past it, and the arc runs whole under the text. A closed arrowhead +also turns outward so for a style whose text fit is `"leader"`. A text above the arc stays put, +and so do its marks, as short as the arc is. + +A dimension style sets how its angles are written: + +- `angleUnits`: `"degrees"`, the default, as `45.5°`; `"degrees-minutes-seconds"`, as `45°30'`; + `"grads"`, as `50.56g`; or `"radians"`, as `0.79r`. +- `anglePrecision`, the decimals, from 0, the default, to 8. In degrees, minutes and seconds it + picks the parts, and the zeros are always written: + + | `anglePrecision` | 0 | 1 and 2 | 3 and 4 | 5 | 8 | + | ---------------- | ------ | --------- | ------------ | -------------- | ----------------- | + | 123.4567° | `123°` | `123°27'` | `123°27'24"` | `123°27'24.1"` | `123°27'24.1412"` | + +- `suppressAngleZeros`, the zeros an angle leaves out, as `suppressZeros` does for a length: + `"leading"` writes 0.50° as `.50°`, `"trailing"` as `0.5°`, and `"both"` as `.5°`. + +An angle is rounded half up as a length is, and carries: 45.99999° is `46°0'0.0"` at a precision of 5. The style's `prefix` and `suffix` stand around it, and its `measurementScale` takes no part. + +`lint` refuses an angular dimension whose vertex is one of its points, whose arc's point is its +vertex, or whose lines run one way; one whose arc's point is on one of its lines, where the leading +CAD app takes the angle or the rest of the turn by a rounding; one whose arc passes through one of +its points, where that app runs the point's extension line either way by a rounding; one whose +text is too wide for its arc in a style whose text fit is `"leader"`, which that app moves outside; +one whose centered text leaves its arc no room each side; one whose closed arrowheads are as long +as its arc is wide; one whose arc runs all but a whole turn, which its 6 decimals write with one +angle at both ends; and words below in a style that centers its text. + ## How a measurement is written A measurement is the length between the points as the file holds them, with 6 decimals, @@ -362,7 +411,8 @@ no dimension style holds nothing else for dimensions. ## What is not drawn yet -Angular, arc length and ordinate dimensions. A radial dimension's center mark, which the leading +Arc length and ordinate dimensions, an angular dimension by two lines, and an angular dimension's +level text or text a drafter placed. A radial dimension's center mark, which the leading CAD app draws only without the line to the center, and a level text placed along its line. Tolerances and alternate units, and the unit formats but decimal and feet and inches. The other fits of a text, such as moving the arrowheads first, and a text a drafter placed. A dimension tied to an entity, which diff --git a/docs/reading.md b/docs/reading.md index 0a2a927..61de4bf 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -120,12 +120,16 @@ leader: - `dimension`: a linear or aligned dimension, with its two points, the point where its dimension line meets its second extension line, its direction, the middle of its text, what it measures, its text and the words below its line, which the file holds after `\X`, its style and the - block of its picture. Angular and ordinate dimensions are counted under `other`. + block of its picture. Ordinate dimensions are counted under `other`. - `radial-dimension`: a radius, a diameter or a jogged radius dimension, its `type`, with its center, the point of the circle or arc its line meets, a jogged one's start and jog, the middle of its text, `placed` where the file holds the text where it was placed, what it measures, its text, its style and the block of its picture. A file holds a diameter's far point, and the center is halfway to the point. +- `angular-dimension`: an angular dimension, its `type`, `"three-point"` with its `vertex` and + a point of each line, `from` and `to`, or `"two-line"` with its `first` and `second` lines, each + two points; a point its arc passes through, `at`, the middle of its text, `placed`, the angle it + measures in degrees, its text, its style and the block of its picture. - `multileader`: a note or a block, with its `style`, `textHeight` and `arrowSize`. `roots` holds each root in the file's order, one with no shafts among them: the point `at` where its shafts meet, its landing's `direction` and length, and its `shafts`, each from its tip. `shafts`, `at`, diff --git a/src/arrowheads.ts b/src/arrowheads.ts index 25f3672..6e8b4eb 100644 --- a/src/arrowheads.ts +++ b/src/arrowheads.ts @@ -206,3 +206,17 @@ export const STANDARD_DIMENSION_STYLE = "Standard"; /** The leader style a drawing with leaders has beside its own, in the spelling the leading CAD app gives it. */ export const STANDARD_LEADER_STYLE = "Standard"; + +/** + * The units an angular dimension writes its angle in, as `DIMAUNIT` 0 to 3: decimal degrees, + * degrees, minutes and seconds, grads and radians. + */ +export const DIMENSION_ANGLE_UNITS = [ + "degrees", + "degrees-minutes-seconds", + "grads", + "radians", +] as const; + +/** The most decimals an angle takes, as `DIMADEC` holds them. */ +export const MAX_ANGLE_PRECISION = 8; diff --git a/src/dimensions.ts b/src/dimensions.ts index 727b78d..98cdb6d 100644 --- a/src/dimensions.ts +++ b/src/dimensions.ts @@ -3,6 +3,7 @@ // for a measurement, and the lines, arrowheads and text that app draws for a dimension. import type { AlignedDimension, + AngularDimension, DiameterDimension, DimensionStyle, Drawing, @@ -17,6 +18,7 @@ import { ARROWHEADS, DEFAULT_ARROWHEAD, JOG_ANGLE, + MAX_ANGLE_PRECISION, MAX_PRECISION, type Arrowhead, } from "./arrowheads.ts"; @@ -36,6 +38,17 @@ import { DIMENSION_LEADER_ARROWS, DIMENSION_LEADER_BELOW, dimensionMeasureProblem, + ANGULAR_ARC_LOST, + ANGULAR_ARC_ON_LINE, + ANGULAR_ARROWS_LONG, + arcProblem, + ANGULAR_ARC_ON_POINT, + ANGULAR_CENTERED_SHORT, + ANGULAR_CENTERED_BELOW, + ANGULAR_NO_ANGLE, + ANGULAR_TEXT_OUT, + ANGULAR_NO_ARC, + ANGULAR_NO_SIDE, RADIAL_CENTERED, RADIAL_JOG_SHORT, RADIAL_NO_RADIUS, @@ -56,14 +69,17 @@ export type StraightDimension = LinearDimension | AlignedDimension; export type RadialDimension = RadiusDimension | DiameterDimension | JoggedRadiusDimension; /** A dimension of any kind. */ -export type Dimension = StraightDimension | RadialDimension; +export type Dimension = StraightDimension | RadialDimension | AngularDimension; /** Whether an entity is a dimension. */ export function isDimension( entity: E, ): entity is Extract { return ( - entity.kind === "linear-dimension" || entity.kind === "aligned-dimension" || isRadial(entity) + entity.kind === "linear-dimension" || + entity.kind === "aligned-dimension" || + entity.kind === "angular-dimension" || + isRadial(entity) ); } @@ -122,6 +138,8 @@ export interface DimensionPictureHandles { readonly leader: readonly [string, string]; /** The text below the dimension line. */ readonly belowText: string; + /** The pieces of an angular dimension's arc. */ + readonly dimensionArcs: readonly [string, string, string]; } /** Where a dimension is: its id, or else its place among the entities of its space. */ @@ -157,6 +175,7 @@ export function validDimensionPictureHandles(place: DimensionPlace): DimensionPi ], leader: [handle("leader-1"), handle("leader-2")], belowText: handle("text-below"), + dimensionArcs: [handle("arc-1"), handle("arc-2"), handle("arc-3")], }; } @@ -183,6 +202,7 @@ export function pictureHandleList(handles: DimensionPictureHandles): string[] { ...handles.dimensionLines.slice(1), ...handles.leader, handles.belowText, + ...handles.dimensionArcs, ]; } @@ -486,6 +506,8 @@ export interface DimensionPicture { readonly dimensionLines: readonly (readonly [Point, Point])[]; /** The lines of the leader to a text moved outside the extension lines. Empty for none. */ readonly leader: readonly (readonly [Point, Point])[]; + /** The pieces of an angular dimension's arc. Empty for a dimension of any other kind. */ + readonly dimensionArcs: readonly DimensionArc[]; /** The outline of each arrowhead, which is filled. None for an arrow size of 0. */ readonly arrowheads: readonly (readonly Point[])[]; /** @@ -513,6 +535,27 @@ export interface DimensionPicture { readonly lineweights: { readonly dimension: number; readonly extension: number }; } +/** A piece of an arc: its center, its radius, and the degrees it runs counterclockwise between. */ +export interface DimensionArc { + readonly center: Point; + readonly radius: number; + readonly start: number; + readonly end: number; +} + +/** The points of an arc's piece that bound it: its ends, and its points furthest along each axis. */ +export function dimensionArcPoints(arc: DimensionArc): Point[] { + const sweep = (((arc.end - arc.start) % 360) + 360) % 360; + const out: Point[] = []; + for (const degrees of [arc.start, arc.end, 0, 90, 180, 270]) { + const past = (((degrees - arc.start) % 360) + 360) % 360; + if (degrees !== arc.start && degrees !== arc.end && past > sweep) continue; + const [x, y] = direction(degrees); + out.push([arc.center[0] + x * arc.radius, arc.center[1] + y * arc.radius]); + } + return out; +} + /** A style's lineweight as group 370 holds it: ByBlock where it gives none. */ function lineweightCode(weight: number | undefined): number { if (weight === undefined) return -2; @@ -605,6 +648,10 @@ export function dimensionMeasure(dimension: Dimension): { readonly angle: number; readonly measurement: number; } { + if (dimension.kind === "angular-dimension") { + const { start, sweep } = angularArc(dimension); + return { angle: start + sweep / 2, measurement: sweep * RADIANS }; + } if (isRadial(dimension)) { const [x1, y1] = [written(dimension.center[0]), written(dimension.center[1])]; const [x2, y2] = [written(dimension.point[0]), written(dimension.point[1])]; @@ -655,6 +702,7 @@ export function dimensionPicture( textStyle?: DimensionFont, ): DimensionPicture { if (isRadial(dimension)) return radialPicture(dimension, style, textStyle); + if (dimension.kind === "angular-dimension") return angularPicture(dimension, style, textStyle); const from: Point = [written(dimension.from[0]), written(dimension.from[1])]; const to: Point = [written(dimension.to[0]), written(dimension.to[1])]; const { angle, measurement } = dimensionMeasure(dimension); @@ -850,6 +898,7 @@ export function dimensionPicture( dimensionLine, dimensionLines, leader, + dimensionArcs: [], arrowheads, arrowheadEntities, label: label(aboveText, textMiddle, topLayout), @@ -1115,6 +1164,7 @@ function radialPicture( dimensionLine: [center, point], dimensionLines: lines, leader: [], + dimensionArcs: [], arrowheads, arrowheadEntities, label: label(aboveText, textMiddle, topLayout), @@ -1132,6 +1182,365 @@ function radialPicture( }; } +/** + * An angular dimension's arc as the writers write its points: its vertex, its radius, and the + * degrees, from 0 up to 360, its arc runs counterclockwise between, from `start` through `sweep`. + * The angle between the two lines from `from` round to `to` holds the arc's point, or else the + * rest of the turn does, and the arc spans that one. `first` is the point at its start. + */ +export function angularArc(dimension: AngularDimension): { + readonly vertex: Point; + readonly radius: number; + readonly start: number; + readonly sweep: number; + readonly first: Point; + readonly second: Point; +} { + const p = (q: Point): Point => [written(q[0]), written(q[1])]; + const [vertex, from, to, at] = [ + p(dimension.vertex), + p(dimension.from), + p(dimension.to), + p(dimension.at), + ]; + const angleOf = (q: Point): number => { + const a = Math.atan2(q[1] - vertex[1], q[0] - vertex[0]) / RADIANS; + return a < 0 ? a + 360 : a; + }; + const turn = (a: number, b: number): number => (((b - a) % 360) + 360) % 360; + const [a, b, c] = [angleOf(from), angleOf(to), angleOf(at)]; + const inside = turn(a, c) <= turn(a, b); + const [start, end, first, second] = inside ? [a, b, from, to] : [b, a, to, from]; + return { + vertex, + radius: Math.hypot(at[0] - vertex[0], at[1] - vertex[1]), + start, + sweep: turn(start, end), + first, + second, + }; +} + +/** + * An angle as the leading CAD app writes it in a style, before any prefix or suffix: in the + * style's `angleUnits`, with `anglePrecision` decimals, rounded half up as a length is, and without + * the zeros `suppressAngleZeros` leaves out. In degrees, minutes and seconds the precision picks + * the parts: 0 the degrees, 1 and 2 the minutes, 3 and 4 the seconds, and each more a decimal of + * the seconds; no zero is left out of them. + * + * @param radians - The angle, not negative. + */ +export function angleNumber( + radians: number, + style: Pick, +): string { + const units = style.angleUnits ?? "degrees"; + const places = Math.min( + MAX_ANGLE_PRECISION, + Math.max(0, Math.trunc(style.anglePrecision ?? 0) || 0), + ); + const degrees = radians / RADIANS; + const round = (value: number, decimals: number): string => + (value + belowHalf(value)).toFixed(decimals); + if (units === "degrees-minutes-seconds") { + if (places === 0) return `${round(degrees, 0)}°`; + if (places <= 2) { + const minutes = Number(round(degrees * 60, 0)); + return `${Math.floor(minutes / 60)}°${minutes % 60}'`; + } + const decimals = Math.max(0, places - 4); + const tenths = 10 ** decimals; + const seconds = Number(round(degrees * 3600 * tenths, 0)); + const whole = Math.floor(seconds / tenths); + const part = (seconds % tenths) / tenths; + return `${Math.floor(whole / 3600)}°${Math.floor(whole / 60) % 60}'${((whole % 60) + part).toFixed(decimals)}"`; + } + const value = units === "grads" ? (degrees * 400) / 360 : units === "radians" ? radians : degrees; + let text = round(value, places); + const suppress = style.suppressAngleZeros; + if ((suppress === "trailing" || suppress === "both") && text.includes(".")) { + text = text.replace(/0+$/, "").replace(/\.$/, ""); + } + if ((suppress === "leading" || suppress === "both") && text.startsWith("0.")) + text = text.slice(1); + return `${text}${units === "degrees" ? "°" : units === "grads" ? "g" : "r"}`; +} + +/** What an angular dimension draws above its arc and below it, as `dimensionTexts` for a length. */ +export function angularTexts( + dimension: AngularDimension, + radians: number, + style: DimensionStyle, +): readonly [above: string, below: string | undefined] { + const measured = `${style.prefix ?? ""}${angleNumber(radians, style)}${style.suffix ?? ""}`; + const text = dimensionFileText(dimension); + const at = text === undefined ? -1 : text.indexOf("<>"); + const drawn = + text === undefined + ? measured + : at < 0 + ? text + : `${text.slice(0, at)}${measured}${text.slice(at + 2)}`; + const cut = drawn.indexOf("\\X"); + return cut < 0 ? [drawn, undefined] : [drawn.slice(0, cut), drawn.slice(cut + 2)]; +} + +/** + * What the leading CAD app draws for an angular dimension in a style. Each extension line runs + * along its line from the style's offset off its point, toward the arc, to the style's length + * past the arc. The arc runs between the arrowheads, each of which takes a chord of the arrow + * size, or between the ticks. The text stands at the middle of the arc, along it, turned to read + * upright: a gap above it, or centered in a break of it. + */ +function angularPicture( + dimension: AngularDimension, + style: DimensionStyle, + textStyle: DimensionFont | undefined, +): DimensionPicture { + const { vertex, radius, start, sweep, first, second } = angularArc(dimension); + const end = start + sweep; + const measurement = sweep * RADIANS; + const polar = (degrees: number, distance: number): Point => { + const [x, y] = direction(degrees); + return [vertex[0] + x * distance, vertex[1] + y * distance]; + }; + const move = (from: Point, by: Point, distance: number): Point => [ + from[0] + by[0] * distance, + from[1] + by[1] * distance, + ]; + const sizes = dimensionSizes(style); + const size = sizes.arrowSize; + const gap = sizes.textGap; + const info = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD); + const stroke = info?.stroke; + const tick = stroke !== undefined; + + // An extension line runs from its point toward the arc, and past it. + const extension = (degrees: number, side: Point): readonly [Point, Point] => { + const r = Math.hypot(side[0] - vertex[0], side[1] - vertex[1]); + const out = radius > r ? 1 : -1; + return [ + polar(degrees, r + out * sizes.extensionOffset), + polar(degrees, radius + out * sizes.extensionBeyond), + ]; + }; + const extensionLines = [extension(start, first), extension(end, second)]; + + const [aboveText, belowText] = angularTexts(dimension, measurement, style); + const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => + layoutDimensionText({ + value, + height: sizes.textHeight, + font, + widthFactor: written(textStyle?.widthFactor ?? 1), + obliqueAngle: written(textStyle?.obliqueAngle ?? 0), + align: "center", + valign: "middle", + }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => + layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + // Words below the arc are a second line of the one text, which stands on the arc. + const value = belowText === undefined ? aboveText : `${aboveText}\\P${belowText}`; + const layout = lay(mtextOfLabel(value)); + const textWidth = widest(layout); + const half = boxHeight(layout) / 2; + const centered = style.textPlacement === "centered"; + + // An arrowhead takes a chord of its size at each end of the arc, and a tick none. + const sizeChord = size > 0 ? (2 * Math.asin(Math.min(1, size / (2 * radius)))) / RADIANS : 0; + const closed = !tick && size > 0; + const chord = closed ? sizeChord : 0; + const middle = start + sweep / 2; + // Where a centered text, or a text that would move out, leaves the marks no room on the arc, + // they turn outward, each with a tail past it, and the arc runs whole between them. + const room = angularRoom(radius, sweep, textWidth, style); + // An arrow size of 0 draws no marks, which have nothing to turn. + const flipped = + size > 0 && (closed ? centered || style.textFit === "leader" : centered) && !room.marks; + const arc = (from: number, to: number): DimensionArc => ({ + center: vertex, + radius, + start: ((from % 360) + 360) % 360, + end: ((to % 360) + 360) % 360, + }); + const lineMiddle = polar(middle, radius); + const rotation = readable(middle - 90); + const quarter = direction(rotation); + const above: Point = + rotation % 90 === 0 + ? [-quarter[1], quarter[0]] + : [-Math.sin(rotation * RADIANS), Math.cos(rotation * RADIANS)]; + let textMiddle: Point; + const dimensionArcs: DimensionArc[] = []; + if (flipped) { + dimensionArcs.push( + arc(start - chord - sizeChord, start - chord), + arc(end + chord, end + chord + sizeChord), + arc(start, end), + ); + } else if (centered && belowText === undefined) { + const opening = Math.asin(Math.min(1, (gap + textWidth / 2) / radius)) / RADIANS; + dimensionArcs.push(arc(start + chord, middle - opening), arc(middle + opening, end - chord)); + } else { + dimensionArcs.push(arc(start + chord, end - chord)); + } + textMiddle = + centered || belowText !== undefined ? lineMiddle : move(lineMiddle, above, gap + half); + + const arrowheads: Point[][] = []; + const arrowheadEntities: ArrowheadEntity[] = []; + /** An arrowhead at the arc's end at `degrees`, pointing on round the circle the way `turn` says. */ + const arrow = (degrees: number, turn: 1 | -1): void => { + if (!(size > 0)) return; + const tip = polar(degrees, radius); + if (tick) { + const pointing = (((degrees + turn * 90) % 360) + 360) % 360; + const way = direction(pointing); + arrowheadEntities.push({ + kind: "insert", + block: info!.block!, + at: tip, + rotation: pointing, + scale: size, + }); + const halfStroke = move( + move([0, 0], way, stroke.to[0] * size), + [-way[1], way[0]], + stroke.to[1] * size, + ); + const wide = (stroke.width * size) / 2 / Math.SQRT2; + const edge: Point = [(way[0] + way[1]) * wide, (way[1] - way[0]) * wide]; + arrowheads.push([ + [tip[0] - halfStroke[0] + edge[0], tip[1] - halfStroke[1] + edge[1]], + [tip[0] + halfStroke[0] + edge[0], tip[1] + halfStroke[1] + edge[1]], + [tip[0] + halfStroke[0] - edge[0], tip[1] + halfStroke[1] - edge[1]], + [tip[0] - halfStroke[0] - edge[0], tip[1] - halfStroke[1] - edge[1]], + ]); + return; + } + const base = polar(degrees - turn * chord, radius); + const length = Math.hypot(tip[0] - base[0], tip[1] - base[1]); + const way: Point = [(tip[0] - base[0]) / length, (tip[1] - base[1]) / length]; + const left: Point = [-way[1], way[0]]; + arrowheads.push([tip, move(base, left, size / 6), move(base, left, -size / 6)]); + arrowheadEntities.push({ + kind: "solid", + corners: [move(base, left, size / 6), move(base, left, -size / 6), tip], + }); + }; + arrow(start, flipped ? 1 : -1); + arrow(end, flipped ? -1 : 1); + + const textStyleName = style.textStyle; + const label = (value: string, at: Point, layout: ParagraphLayout): DimensionLabel => ({ + value, + at: move(at, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + ...(textStyleName === undefined ? {} : { style: textStyleName }), + }); + const at: Point = [written(dimension.at[0]), written(dimension.at[1])]; + return { + measurement, + definitionPoint: at, + extensionLines, + dimensionLine: [polar(start, radius), polar(end, radius)], + dimensionLines: [], + leader: [], + dimensionArcs, + arrowheads, + arrowheadEntities, + label: label(value, textMiddle, layout), + textMiddle, + textPoint: textMiddle, + textWidth, + lineweights: { + dimension: lineweightCode(style.dimensionLineweight), + extension: lineweightCode(style.extensionLineweight), + }, + }; +} + +/** What is wrong with an angular dimension in its style, or undefined. */ +function angularDrawnProblem( + dimension: AngularDimension, + style: DimensionStyle, + textStyle: TextStyle | undefined, +): string | undefined { + const p = (q: Point): Point => [written(q[0]), written(q[1])]; + const vertex = p(dimension.vertex); + const off = (q: Point): number => Math.hypot(p(q)[0] - vertex[0], p(q)[1] - vertex[1]); + if (off(dimension.from) === 0 || off(dimension.to) === 0) return ANGULAR_NO_SIDE; + if (off(dimension.at) === 0) return ANGULAR_NO_ARC; + const { radius, sweep, first, second } = angularArc(dimension); + if (!(sweep > 0) || sweep >= 360) return ANGULAR_NO_ANGLE; + // Where the arc's point lies on one of the lines, a rounding picks the angle or the rest of the + // turn. + const at = p(dimension.at); + for (const side of [first, second]) { + const [ux, uy] = [side[0] - vertex[0], side[1] - vertex[1]]; + const [vx, vy] = [at[0] - vertex[0], at[1] - vertex[1]]; + const cross = ux * vy - uy * vx; + if (ux * vx + uy * vy > 0 && Math.abs(cross) <= 1e-12 * Math.hypot(ux, uy) * Math.hypot(vx, vy)) + return ANGULAR_ARC_ON_LINE; + } + // The leading CAD app runs an extension line one way or the other by a rounding where the arc + // passes through its point. + for (const side of [first, second]) { + const r = Math.hypot(side[0] - vertex[0], side[1] - vertex[1]); + if (Math.abs(r - radius) <= 1e-9 * Math.max(1, radius)) return ANGULAR_ARC_ON_POINT; + } + // A closed arrowhead is a chord of the arc as long as the arrow size. + const size = dimensionSizes(style).arrowSize; + const closed = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke === undefined; + if (closed && size >= 2 * radius) return ANGULAR_ARROWS_LONG; + const picture = angularPicture(dimension, style, textStyle); + // An arc of all but a whole turn is written with one angle at both ends, which draws nothing. + for (const piece of picture.dimensionArcs) { + if (arcProblem(piece.start, piece.end)) return ANGULAR_ARC_LOST; + } + const room = angularRoom(radius, sweep, picture.textWidth, style); + if (style.textFit === "leader" && !room.text) return ANGULAR_TEXT_OUT; + // A centered text breaks the arc, and each piece must run on from its mark to the text: one + // that would run back past its mark, the long way round, is not laid out. Each half of the + // arc holds a closed arrowhead's chord and half the text's opening. + // Turned outward, the marks and their tails must stay clear of each other round the back. + if (picture.dimensionArcs.length === 3) { + const tail = (2 * Math.asin(size / (2 * radius))) / RADIANS; + if (sweep + 2 * ((closed ? tail : 0) + tail) >= 360) return ANGULAR_ARROWS_LONG; + } + if (style.textPlacement === "centered" && picture.dimensionArcs.length === 2) { + const chord = closed && size > 0 ? (2 * Math.asin(size / (2 * radius))) / RADIANS : 0; + const half = dimensionSizes(style).textGap + picture.textWidth / 2; + const opening = Math.asin(Math.min(1, half / radius)) / RADIANS; + if (opening + chord > sweep / 2 + 1e-9) return ANGULAR_CENTERED_SHORT; + } + if (style.textPlacement === "centered" && dimension.textBelow !== undefined) + return ANGULAR_CENTERED_BELOW; + return pictureNumbersProblem(picture); +} + +/** + * Whether an angular dimension's arc holds its text, with a gap each side, and its marks too: a + * closed arrowhead's size each side more. The arc is measured along its length. + */ +function angularRoom( + radius: number, + sweep: number, + textWidth: number, + style: DimensionStyle, +): { readonly text: boolean; readonly marks: boolean } { + const sizes = dimensionSizes(style); + const length = radius * sweep * RADIANS; + const needs = textWidth + 2 * sizes.textGap; + const tick = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke !== undefined; + const arrows = !tick && sizes.arrowSize > 0 ? 2 * sizes.arrowSize : 0; + return { text: length > needs, marks: length > needs + arrows }; +} + /** * The widest a character of any font in `FONTS` is drawn, as a share of the text's height, * before its style's width factor: for the characters of a measurement, the widest the leading CAD @@ -1229,6 +1638,8 @@ export function dimensionDrawnProblem( ): string | undefined { const { measurement } = dimensionMeasure(dimension); if (isRadial(dimension)) return radialDrawnProblem(dimension, measurement, style, textStyle); + if (dimension.kind === "angular-dimension") + return angularDrawnProblem(dimension, style, textStyle); // The arrowheads need room for the wider of the texts above and below the line. const [above, below] = dimensionTexts(dimension, measurement, style); let drawn = above; @@ -1343,6 +1754,7 @@ function pictureNumbersProblem(picture: DimensionPicture): string | undefined { ...picture.dimensionLine.flat(), ...picture.dimensionLines.flat(2), ...picture.leader.flat(2), + ...picture.dimensionArcs.flatMap((arc) => [...arc.center, arc.radius]), ...picture.arrowheads.flat(2), ...picture.label.at, picture.label.height, diff --git a/src/drawing.ts b/src/drawing.ts index bb87720..deebdc2 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -18,6 +18,7 @@ import { type DIMENSION_TEXT_PLACEMENTS, type DIMENSION_TEXT_FITS, type DIMENSION_RADIAL_TEXTS, + type DIMENSION_ANGLE_UNITS, type FEET_INCH_ZEROS, type LeaderArrowhead, type ZERO_SUPPRESSIONS, @@ -622,6 +623,30 @@ export interface JoggedRadiusDimension extends RadialDimensionBase { readonly jog: Point; } +/** + * An angular dimension: the angle at `vertex` between the line to `from` and the line to `to`, its + * arc through `at`. The arc's point picks the angle, as the leading CAD app picks it: the one + * between the two lines that holds `at`, or the rest of the turn, so the order of `from` and `to` + * means nothing. Its extension lines run from near `from` and `to` along their lines to past the + * arc, and its text stands at the middle of the arc. + */ +export interface AngularDimension extends Placed { + readonly kind: "angular-dimension"; + /** A dimension style of the drawing. */ + readonly style: string; + /** Where the two lines meet. */ + readonly vertex: Point; + /** A point of each line, which its extension line starts near. */ + readonly from: Point; + readonly to: Point; + /** A point the dimension's arc passes through, about the vertex. */ + readonly at: Point; + /** A text to draw in place of the measurement, as a linear dimension's `text`. */ + readonly text?: string; + /** Words drawn under its arc, opposite the text, as a linear dimension's `textBelow`. */ + readonly textBelow?: string; +} + /** Which side of the point where its shafts meet a leader's note is on. */ export type LeaderSide = (typeof LEADER_SIDES)[number]; @@ -759,6 +784,7 @@ export type Entity = | RadiusDimension | DiameterDimension | JoggedRadiusDimension + | AngularDimension | Leader | Image; @@ -905,6 +931,19 @@ export interface DimensionStyle { readonly radialText?: (typeof DIMENSION_RADIAL_TEXTS)[number]; /** The angle of a jogged radius dimension's jog to its line, in degrees from 5 to 90. Defaults to 45. */ readonly jogAngle?: number; + /** + * The units an angular dimension writes its angle in: `"degrees"`, the default, as `45.5°`, + * `"degrees-minutes-seconds"`, as `45°30'`, `"grads"`, as `50.56g`, or `"radians"`, as `0.79r`. + */ + readonly angleUnits?: (typeof DIMENSION_ANGLE_UNITS)[number]; + /** + * How many decimals an angle takes, from 0, the default, to 8. In degrees, minutes and seconds, + * 0 writes the degrees, 1 and 2 the minutes too, 3 and 4 the seconds, and more the seconds' + * decimals. + */ + readonly anglePrecision?: number; + /** The zeros an angle leaves out, as `suppressZeros` does for a length. */ + readonly suppressAngleZeros?: "leading" | "trailing" | "both"; } /** @@ -1739,6 +1778,19 @@ export interface DimensionStyleDefinition< readonly radialText?: (typeof DIMENSION_RADIAL_TEXTS)[number]; /** The angle of a jogged radius dimension's jog to its line, in degrees from 5 to 90. Defaults to 45. */ readonly jogAngle?: number; + /** + * The units an angular dimension writes its angle in: `"degrees"`, the default, as `45.5°`, + * `"degrees-minutes-seconds"`, as `45°30'`, `"grads"`, as `50.56g`, or `"radians"`, as `0.79r`. + */ + readonly angleUnits?: (typeof DIMENSION_ANGLE_UNITS)[number]; + /** + * How many decimals an angle takes, from 0, the default, to 8. In degrees, minutes and seconds, + * 0 writes the degrees, 1 and 2 the minutes too, 3 and 4 the seconds, and more the seconds' + * decimals. + */ + readonly anglePrecision?: number; + /** The zeros an angle leaves out, as `suppressZeros` does for a length. */ + readonly suppressAngleZeros?: "leading" | "trailing" | "both"; } /** What every dimension is drawn with. */ @@ -1804,6 +1856,13 @@ export type DiameterDimensionOptions< I extends string = string, > = RadiusDimensionOptions; +/** The options of `angularDimension()`. */ +export type AngularDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, +> = DimensionOptions; + /** The options of `joggedRadiusDimension()`. */ export type JoggedRadiusDimensionOptions< S extends string = string, @@ -3593,6 +3652,7 @@ export class DrawingBuilder< const { prefix, suffix, suppressZeros, feetInchZeros } = definition; const { fraction, fractionScale, textPlacement, textFit } = definition; const { dimensionLineweight, extensionLineweight, radialText, jogAngle } = definition; + const { angleUnits, anglePrecision, suppressAngleZeros } = definition; const units = definition.units ?? "decimal"; const scale = definition.scale ?? 1; const measurementScale = definition.measurementScale ?? 1; @@ -3621,6 +3681,9 @@ export class DrawingBuilder< ...(extensionLineweight === undefined ? {} : { extensionLineweight }), ...(radialText === undefined || radialText === "aligned" ? {} : { radialText }), ...(jogAngle === undefined || written(jogAngle) === JOG_ANGLE.default ? {} : { jogAngle }), + ...(angleUnits === undefined || angleUnits === "degrees" ? {} : { angleUnits }), + ...(anglePrecision === undefined || anglePrecision === 0 ? {} : { anglePrecision }), + ...(suppressAngleZeros === undefined ? {} : { suppressAngleZeros }), }); this.#dimensionStylesAudited.set(layerAuditKey(named), named); } @@ -3764,6 +3827,36 @@ export class DrawingBuilder< ); } + /** + * Draws an angular dimension on the current layer: the angle at `vertex` between the lines to + * `from` and to `to`, with its arc through `at`. The arc's point picks which angle, so the order + * of `from` and `to` means nothing. + */ + angularDimension( + vertex: Point, + from: Point, + to: Point, + at: Point, + options: Z extends Standard + ? StandardAlignedDimensionOptions + : V extends "R12" + ? R12Dimensions + : AngularDimensionOptions, + ): this { + return this.#add(DrawingBuilder.prototype.angularDimension, idOf(options), () => + this.#dimension(options as unknown as AngularDimensionOptions | undefined, (style, text) => ({ + kind: "angular-dimension", + layer: this.#current, + style, + vertex: pt(vertex), + from: pt(from), + to: pt(to), + at: pt(at), + ...text, + })), + ); + } + /** A radius or a diameter dimension, with its text where `options.textFromCenter` says. */ #radial( kind: K, @@ -3928,6 +4021,11 @@ export class DrawingBuilder< ...(extensionLineweight === undefined ? {} : { extensionLineweight }), ...(fields.radialText === "aligned" ? {} : { radialText: fields.radialText }), ...(fields.jogAngle === JOG_ANGLE.default ? {} : { jogAngle: fields.jogAngle }), + ...(fields.angleUnits === "degrees" ? {} : { angleUnits: fields.angleUnits }), + ...(fields.anglePrecision === 0 ? {} : { anglePrecision: fields.anglePrecision }), + ...(fields.suppressAngleZeros === undefined + ? {} + : { suppressAngleZeros: fields.suppressAngleZeros }), }); return this.#dimensionStyles.get(layerKey(name))!; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 20c6122..fe4ec88 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -10,6 +10,7 @@ import { arrowheadInfo, DEFAULT_ARROWHEAD, DEFAULT_LEADER_ARROWHEAD, + DIMENSION_ANGLE_UNITS, JOG_ANGLE, leaderArrowheadInfo, type LeaderArrowheadStroke, @@ -1214,6 +1215,8 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) ? 0 : ZERO_SUPPRESSION_CODES[style.suppressZeros], ); // DIMZIN + const angleZeros = style.suppressAngleZeros; + if (angleZeros !== undefined) g(79, ANGLE_ZERO_CODES[angleZeros]); // DIMAZIN g(140, style.textHeight); // DIMTXT g(144, style.measurementScale ?? 1); // DIMLFAC if (style.fractionScale !== undefined) g(146, style.fractionScale); // DIMTFAC @@ -1222,7 +1225,10 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) const leader = style.textFit === "leader"; // DIMTIX: the text between the extension lines whatever fits, or moved out where it does not. g(174, leader ? 0 : 1); + if ((style.anglePrecision ?? 0) !== 0) g(179, style.anglePrecision!); // DIMADEC g(271, style.precision); // DIMDEC + const angleUnits = style.angleUnits ?? "degrees"; + if (angleUnits !== "degrees") g(275, DIMENSION_ANGLE_UNITS.indexOf(angleUnits)); // DIMAUNIT // DIMFRAC: stacked across, stacked diagonally, or on the line, as 1 7/16. if (architectural) g(276, FRACTION_CODES[style.fraction ?? "inline"]); g(277, architectural ? 4 : 2); // DIMLUNIT: architectural or decimal @@ -1234,6 +1240,9 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) if (style.extensionLineweight !== undefined) g(372, Math.round(style.extensionLineweight * 100)); // DIMLWE } +/** `DIMAZIN` for the zeros an angle leaves out. */ +const ANGLE_ZERO_CODES = { leading: 1, trailing: 2, both: 3 } as const; + /** `DIMFRAC` for each way a style writes a fraction of an inch. */ const FRACTION_CODES = { stacked: 0, diagonal: 1, inline: 2 } as const; @@ -1252,7 +1261,13 @@ function writeDimension( drawn: DimensionPicture | undefined, ): void { // `lint` refuses a dimension in a style the drawing does not have, which has no picture. - const at = isRadial(e) ? e.center : e.kind === "linear-dimension" ? e.line : e.to; + const at = isRadial(e) + ? e.center + : e.kind === "linear-dimension" + ? e.line + : e.kind === "angular-dimension" + ? e.at + : e.to; const picture = drawn ?? { definitionPoint: at, textPoint: at }; const jogged = e.kind === "jogged-radius-dimension"; g(0, jogged ? "LARGE_RADIAL_DIMENSION" : "DIMENSION"); @@ -1275,6 +1290,13 @@ function writeDimension( // itself, and keeps the picture the file holds. if (style) g(42, measurementValue(e, style)); g(3, style?.name ?? e.style); + if (e.kind === "angular-dimension") { + g(100, "AcDb3PointAngularDimension"); + point(g, 13, ...e.from); + point(g, 14, ...e.to); + point(g, 15, ...e.vertex); + return; + } if (isRadial(e)) { if (e.kind === "jogged-radius-dimension") { g(100, "AcDbRadialDimensionLarge"); @@ -1341,6 +1363,7 @@ const DIMENSION_TYPES = { "diameter-dimension": 3, "radius-dimension": 4, "jogged-radius-dimension": 9, + "angular-dimension": 5, } as const; /** The block of a dimension's picture, with what the writer needs for it. */ @@ -1401,6 +1424,14 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi point(g, 10, ...from); point(g, 11, ...to); } + picture.dimensionArcs.forEach((arc, i) => { + begin("ARC", handles.dimensionArcs[i]!, "AcDbCircle", weights.dimension); + point(g, 10, ...arc.center); + g(40, arc.radius); + g(100, "AcDbArc"); + g(50, writtenAngle(arc.start)); + g(51, writtenAngle(arc.end)); + }); picture.arrowheadEntities.forEach((arrowhead, i) => { const handle = handles.arrowheads[i]!; if (arrowhead.kind === "solid") { @@ -1468,9 +1499,9 @@ function writeMtextValue(g: Group, value: string): void { /** What a dimension reads, as the DXF writes it: the length times the style's measurement scale. */ function measurementValue(dimension: Dimension, style: DimensionStyle): string { - return fifteenDigits( - dimensionMeasure(dimension).measurement * written(style.measurementScale ?? 1), - ); + // An angle, in radians, takes no measurement scale. + const scale = dimension.kind === "angular-dimension" ? 1 : written(style.measurementScale ?? 1); + return fifteenDigits(dimensionMeasure(dimension).measurement * scale); } /** A layout with what the writer works out for it once. */ diff --git a/src/extents.ts b/src/extents.ts index 9b3797a..916c293 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -10,7 +10,12 @@ import { type Referenced, } from "./blocks.ts"; import { imageCorners, imageDrawable, imageFrame } from "./images.ts"; -import { dimensionPicture, pictureTexts, type Dimension } from "./dimensions.ts"; +import { + dimensionArcPoints, + dimensionPicture, + pictureTexts, + type Dimension, +} from "./dimensions.ts"; import type { AttributeDefinition, Block, @@ -315,6 +320,7 @@ export function boxer( case "radius-dimension": case "diameter-dimension": case "jogged-radius-dimension": + case "angular-dimension": dimension(e, from, add); break; case "leader": { @@ -416,6 +422,8 @@ export function boxer( add(...line[0]); add(...line[1]); } + for (const arc of picture.dimensionArcs) + for (const p of dimensionArcPoints(arc)) add(p[0], p[1]); for (const arrowhead of picture.arrowheads) for (const corner of arrowhead) add(...corner); // Each text by the box of what it draws, as its block's paragraph lays it out. for (const text of pictureTexts(picture, font)) { diff --git a/src/index.ts b/src/index.ts index 0021def..8a9736e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ export { export { ARROWHEADS, DEFAULT_LEADER_ARROWHEAD, + DIMENSION_ANGLE_UNITS, DIMENSION_FRACTIONS, DIMENSION_RADIAL_TEXTS, DIMENSION_TEXT_FITS, @@ -28,7 +29,9 @@ export { } from "./arrowheads.ts"; export type { CallSite } from "./callsite.ts"; export { + angleNumber, arrowheadHandles, + dimensionArcPoints, dimensionAngle, dimensionFileText, dimensionMeasure, @@ -40,6 +43,7 @@ export { mtextOfLabel, pictureTexts, type ArrowheadEntity, + type DimensionArc, type DimensionFont, type DimensionLabel, type DimensionPicture, @@ -74,6 +78,8 @@ export { type Insert, type JoggedRadiusDimension, type JoggedRadiusDimensionOptions, + type AngularDimension, + type AngularDimensionOptions, type InsertOptions, type Layer, type LayerOptions, @@ -351,6 +357,7 @@ export { type ReadCircle, type ReadDimension, type ReadRadialDimension, + type ReadAngularDimension, type ReadDimensionStyle, type ReadDrawingFile, type ReadEntity, diff --git a/src/inspect.ts b/src/inspect.ts index 3a8f6f5..b8f75a4 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -601,6 +601,7 @@ function looked( case "radius-dimension": case "diameter-dimension": case "jogged-radius-dimension": + case "angular-dimension": case "leader": return true; default: diff --git a/src/lint.ts b/src/lint.ts index 74928c8..78f9bec 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -520,6 +520,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) case "radius-dimension": case "diameter-dimension": case "jogged-radius-dimension": + case "angular-dimension": cost += long1(e.style) + long1(e.text) + long1(e.textBelow); break; case "leader": @@ -2297,7 +2298,8 @@ function costsBoxes(e: Readonly>): boolean { kind === "aligned-dimension" || kind === "radius-dimension" || kind === "diameter-dimension" || - kind === "jogged-radius-dimension" + kind === "jogged-radius-dimension" || + kind === "angular-dimension" ); } @@ -2387,6 +2389,9 @@ function geometryProblems(e: Entity): string[] { case "jogged-radius-dimension": finite("its points", ...e.center, ...e.point, ...e.start, ...e.jog); break; + case "angular-dimension": + finite("its points", ...e.vertex, ...e.from, ...e.to, ...e.at); + break; case "leader": finite("its point", ...e.at); break; diff --git a/src/read/check.ts b/src/read/check.ts index dfdf497..b28d9e2 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -195,6 +195,25 @@ const ENTITY: Readonly> = { "block?": "string", "blockHandle?": "string", }, + "angular-dimension": { + ...BASE, + kind: { oneOf: ["angular-dimension"] }, + type: { oneOf: ["three-point", "two-line"] }, + "vertex?": "point", + "from?": "point", + "to?": "point", + "first?": { list: "point" }, + "second?": { list: "point" }, + at: "point", + textAt: "point", + "placed?": "boolean", + "measurement?": "number", + "text?": "string", + "textBelow?": "string", + style: "string", + "block?": "string", + "blockHandle?": "string", + }, multileader: { ...BASE, kind: { oneOf: ["multileader"] }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index eae2088..ff95dcd 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -1648,7 +1648,8 @@ class DxfReader { if ( entity.kind !== "insert" && entity.kind !== "dimension" && - entity.kind !== "radial-dimension" + entity.kind !== "radial-dimension" && + entity.kind !== "angular-dimension" ) continue; const block = entity.block; diff --git a/src/read/entities.ts b/src/read/entities.ts index 0c03970..ee48829 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -8,6 +8,7 @@ import type { ReadAttribute, ReadDimension, ReadRadialDimension, + ReadAngularDimension, ReadEntity, ReadEntityBase, ReadImage, @@ -479,6 +480,7 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re // The kind is group 70's low four bits, 9 for a jogged radius: 32, 64 and 128 are flags. const kind = (num(r, 70) ?? 0) & 15; if (kind === 3 || kind === 4 || kind === 9) return radialDimension(r, base, kind, r12); + if (kind === 2 || kind === 5) return angularDimension(r, base, kind, r12); if (kind > 1) return { other: `DIMENSION ${DIMENSION_KINDS[kind] ?? "of another kind"}` }; const angle = kind === 0 ? (num(r, 50) ?? 0) : 0; // The leading CAD app leaves the measurement out when it is 1. An R12 file holds none. @@ -541,6 +543,40 @@ function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolea return { entity }; } +/** + * An angular dimension by two lines (group 70's kind 2), 13 to 14 and 15 to 10, its arc through + * 16, or by three points (5), its vertex 15, its lines through 13 and 14, its arc through 10. + */ +function angularDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolean): Reading { + const radians = num(r, 42) ?? (r12 ? undefined : 1); + // An angle of radians too large for degrees is left out, as no angle. + const degrees = + radians === undefined ? undefined : radians === -1 ? -1 : radians * (180 / Math.PI); + const measurement = degrees !== undefined && Number.isFinite(degrees) ? degrees : undefined; + const text = first(r, 1); + const block = name(r, 2); + const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); + const entity: ReadAngularDimension = { + ...base, + kind: "angular-dimension", + ...(kind === 5 + ? { type: "three-point", vertex: point(r, 15), from: point(r, 13), to: point(r, 14) } + : { + type: "two-line", + first: [point(r, 13), point(r, 14)], + second: [point(r, 15), point(r, 10)], + }), + at: point(r, kind === 5 ? 10 : 16), + textAt: point(r, 11), + ...(((num(r, 70) ?? 0) & 128) !== 0 && { placed: true }), + ...(measurement !== undefined && { measurement }), + ...parts, + style: name(r, 3) ?? "Standard", + ...(block !== undefined && block !== "" && { block }), + }; + return { entity }; +} + /** * A `MULTILEADER`, from the context data that says how it is drawn: every root with its shafts, a * note or a block, and the multileader's own groups after the context. One whose note or block @@ -766,6 +802,8 @@ export function costOf(e: ReadEntity): number { return own + 4 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "radial-dimension": return own + 5 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); + case "angular-dimension": + return own + 6 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "multileader": { let points = 3; for (const root of e.roots) { diff --git a/src/read/model.ts b/src/read/model.ts index 5b3cf84..b7b9fa6 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -428,6 +428,35 @@ export interface ReadRadialDimension extends ReadEntityBase { readonly blockHandle?: string; } +/** + * An angular dimension: by three points, its vertex and a point of each line, or by two lines, + * each by two points, which need not meet. + */ +export interface ReadAngularDimension extends ReadEntityBase { + readonly kind: "angular-dimension"; + readonly type: "three-point" | "two-line"; + /** By three points: where the lines meet, and a point of each. */ + readonly vertex?: Point; + readonly from?: Point; + readonly to?: Point; + /** By two lines: each line, by two of its points. */ + readonly first?: readonly [Point, Point]; + readonly second?: readonly [Point, Point]; + /** A point its arc passes through. */ + readonly at: Point; + /** The middle of its text. */ + readonly textAt: Point; + /** True where the file holds its text where it was placed, not where the leading CAD app puts it. */ + readonly placed?: boolean; + /** The angle it measures, in degrees, as the file states it; -1 where the file says -1. */ + readonly measurement?: number; + readonly text?: string; + readonly textBelow?: string; + readonly style: string; + readonly block?: string; + readonly blockHandle?: string; +} + /** One root of a multileader: where some of its shafts meet, and the landing from there. */ export interface ReadLeaderRoot { /** Where its shafts meet and its landing starts. */ @@ -581,6 +610,7 @@ export type ReadEntity = | ReadMtext | ReadDimension | ReadRadialDimension + | ReadAngularDimension | ReadMultileader | ReadLeader | ReadSolid diff --git a/src/rules.ts b/src/rules.ts index ff7f7ec..105345d 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -14,6 +14,8 @@ import { DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, + DIMENSION_ANGLE_UNITS, + MAX_ANGLE_PRECISION, JOG_ANGLE, DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, @@ -226,6 +228,10 @@ const TEXT_PLACEMENT_MESSAGE = 'textPlacement must be "above" or "centered"'; const TEXT_FIT_MESSAGE = 'textFit must be "inside" or "leader"'; const RADIAL_TEXT_MESSAGE = 'radialText must be "aligned" or "horizontal"'; const JOG_ANGLE_MESSAGE = "jogAngle must be a number of degrees from 5 to 90"; +const ANGLE_UNITS_MESSAGE = + 'angleUnits must be "degrees", "degrees-minutes-seconds", "grads" or "radians"'; +const ANGLE_PRECISION_MESSAGE = `anglePrecision must be a whole number from 0 to ${MAX_ANGLE_PRECISION}`; +const ANGLE_ZEROS_MESSAGE = 'suppressAngleZeros must be "leading", "trailing" or "both"'; const ZEROS_OF_UNITS = 'suppressZeros is for a style in decimal units, and feetInchZeros for one in "architectural" units, which writes feet and inches'; const DIMENSION_FORMATTING = @@ -2923,6 +2929,29 @@ export function radialTextProblem(value: unknown): string | undefined { : RADIAL_TEXT_MESSAGE; } +/** Returns what is wrong with a dimension style's `angleUnits`, or undefined. */ +export function angleUnitsProblem(value: unknown): string | undefined { + return (DIMENSION_ANGLE_UNITS as readonly unknown[]).includes(value) + ? undefined + : ANGLE_UNITS_MESSAGE; +} + +/** Returns what is wrong with a dimension style's `anglePrecision`, or undefined. */ +export function anglePrecisionProblem(value: unknown): string | undefined { + return Number.isInteger(value) && + (value as number) >= 0 && + (value as number) <= MAX_ANGLE_PRECISION + ? undefined + : ANGLE_PRECISION_MESSAGE; +} + +/** Returns what is wrong with a dimension style's `suppressAngleZeros`, or undefined. */ +export function angleZerosProblem(value: unknown): string | undefined { + return (ZERO_SUPPRESSIONS as readonly unknown[]).includes(value) + ? undefined + : ANGLE_ZEROS_MESSAGE; +} + /** Returns what is wrong with a dimension style's `jogAngle`, or undefined. */ export function jogAngleProblem(value: unknown): string | undefined { return typeof value === "number" && @@ -2972,6 +3001,14 @@ export function dimensionStyleLookProblem(s: Record): string | const problem = jogAngleProblem(s.jogAngle); if (problem) return problem; } + for (const [field, problemOf] of [ + ["angleUnits", angleUnitsProblem], + ["anglePrecision", anglePrecisionProblem], + ["suppressAngleZeros", angleZerosProblem], + ] as const) { + const problem = s[field] === undefined ? undefined : problemOf(s[field]); + if (problem) return problem; + } for (const field of ["dimensionLineweight", "extensionLineweight"] as const) { const value = s[field]; if (value === undefined) continue; @@ -3068,6 +3105,46 @@ export const RADIAL_JOG_SHORT = export const RADIAL_NO_RADIUS = "its point is its center once they are written with the 6 decimals tsdraft writes, so it has no radius"; +/** An angular dimension with a line of no length. */ +export const ANGULAR_NO_SIDE = + "its vertex is one of its two points once they are written with the 6 decimals tsdraft writes, so that line has no direction"; + +/** An angular dimension whose arc has no radius. */ +export const ANGULAR_NO_ARC = + "its arc's point is its vertex once they are written with the 6 decimals tsdraft writes, so the arc has no radius"; + +/** An angular dimension whose arc passes through one of its points. */ +export const ANGULAR_ARC_ON_POINT = + "its arc passes through one of its two points, where the leading CAD app runs that point's extension line toward the vertex or away from it by a rounding, which is not laid out yet, so tsdraft refuses it. Move the arc's point nearer the vertex or further from it"; + +/** An angular dimension whose arc, or a piece of it, is all but a whole turn. */ +export const ANGULAR_ARC_LOST = + "its arc, or a piece of it, runs all but a whole turn, so its two angles are one once they are written with the 6 decimals tsdraft writes, and the leading CAD app draws such an arc as nothing"; + +/** An angular dimension whose closed arrowheads are longer than its arc is wide. */ +export const ANGULAR_ARROWS_LONG = + "its closed arrowheads are as long as its arc is wide or longer, which is not laid out yet, so tsdraft refuses it. Move the arc's point further from the vertex, or use a smaller arrow size"; + +/** An angular dimension whose arc's point lies on one of its lines. */ +export const ANGULAR_ARC_ON_LINE = + "its arc's point is on one of its two lines, where the leading CAD app takes the angle between them or the rest of the turn by a rounding, which is not laid out yet, so tsdraft refuses it. Move the arc's point into the angle it measures"; + +/** An angular dimension whose centered text leaves its arc no room each side. */ +export const ANGULAR_CENTERED_SHORT = + 'its arc is too short for its text "centered" in it and its arrowheads, where the leading CAD app may turn the arrowheads outward, which is not laid out yet, so tsdraft refuses it. Move the arc\'s point further from the vertex, or put the text "above"'; + +/** An angular dimension whose text would move out on a leader. */ +export const ANGULAR_TEXT_OUT = + 'its arc is too short for its text, which the style\'s textFit "leader" moves outside, and that is not laid out yet, so tsdraft refuses it. Move the arc\'s point further from the vertex, or use textFit "inside"'; + +/** An angular dimension with words below and its text centered in its arc. */ +export const ANGULAR_CENTERED_BELOW = + 'its words below the arc with its text "centered" in the arc is not laid out yet, so tsdraft refuses it'; + +/** An angular dimension whose two lines run one way. */ +export const ANGULAR_NO_ANGLE = + "its two lines run the same way once their points are written with the 6 decimals tsdraft writes, so there is no angle between them"; + /** What is wrong with a dimension in a block. */ export const DIMENSION_IN_BLOCK = "a dimension cannot be in a block. The leading CAD app draws nothing for a dimension inside a block when it opens the file, so an insert of the block would show nothing of it. Draw it in model space or on a layout"; diff --git a/src/shape.ts b/src/shape.ts index 19cb577..1e25ac7 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -21,6 +21,7 @@ import type { RadiusDimension, DiameterDimension, JoggedRadiusDimension, + AngularDimension, Linetype, Paragraph, Polyline, @@ -535,6 +536,18 @@ function shapes(all: boolean, typed = all): Shapes { { kind, layer: string, style: ruled(string), center: point, point, start: point, jog: point }, { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, ), + "angular-dimension": fields( + { + kind, + layer: string, + style: ruled(string), + vertex: point, + from: point, + to: point, + at: point, + }, + { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + ), // A rule of `lint` reports the note, the shafts and the leader's own fields, whatever their type. leader: fields( { @@ -675,6 +688,9 @@ function shapes(all: boolean, typed = all): Shapes { extensionLineweight: ruled(numberOrName), radialText: ruled(string), jogAngle: ruled(number), + angleUnits: ruled(string), + anglePrecision: ruled(number), + suppressAngleZeros: ruled(string), }, ), ); diff --git a/src/standard/document.ts b/src/standard/document.ts index 02af2c1..4923c67 100644 --- a/src/standard/document.ts +++ b/src/standard/document.ts @@ -6,6 +6,7 @@ import type { DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, + DIMENSION_ANGLE_UNITS, DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, @@ -200,6 +201,9 @@ export interface DimensionStyleFieldsDocument extends Commented { readonly extensionLineweight?: number; readonly radialText?: string; readonly jogAngle?: number; + readonly angleUnits?: string; + readonly anglePrecision?: number; + readonly suppressAngleZeros?: string; readonly writing?: { readonly [U in Units]?: WritingDocument }; readonly description?: string; } @@ -380,6 +384,9 @@ export interface StandardDimensionStyleFields { readonly extensionLineweight?: number; readonly radialText?: (typeof DIMENSION_RADIAL_TEXTS)[number]; readonly jogAngle?: number; + readonly angleUnits?: (typeof DIMENSION_ANGLE_UNITS)[number]; + readonly anglePrecision?: number; + readonly suppressAngleZeros?: (typeof ZERO_SUPPRESSIONS)[number]; readonly writing?: { readonly [U in Units]?: StandardWriting }; readonly description?: string; } @@ -397,6 +404,9 @@ export interface StandardDimensionStyle { readonly extensionLineweight?: number; readonly radialText: (typeof DIMENSION_RADIAL_TEXTS)[number]; readonly jogAngle: number; + readonly angleUnits: (typeof DIMENSION_ANGLE_UNITS)[number]; + readonly anglePrecision: number; + readonly suppressAngleZeros?: (typeof ZERO_SUPPRESSIONS)[number]; readonly writing: { readonly [U in Units]?: StandardWriting }; /** Its name in the leading CAD app on a layout, when it is not its id in capitals. */ readonly layoutName?: string; diff --git a/src/standard/lint.ts b/src/standard/lint.ts index 5c22e61..c49308d 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -365,6 +365,13 @@ export function lintStandard( ["textFit", style.textFit ?? "inside", fields.textFit], ["radialText", style.radialText ?? "aligned", fields.radialText], ["jogAngle", style.jogAngle ?? JOG_ANGLE.default, fields.jogAngle], + ["angleUnits", style.angleUnits ?? "degrees", fields.angleUnits], + ["anglePrecision", style.anglePrecision ?? 0, fields.anglePrecision], + [ + "suppressAngleZeros", + style.suppressAngleZeros ?? "none", + fields.suppressAngleZeros ?? "none", + ], ["dimensionLineweight", style.dimensionLineweight, fields.dimensionLineweight], ["extensionLineweight", style.extensionLineweight, fields.extensionLineweight], ]; diff --git a/src/standard/literal.ts b/src/standard/literal.ts index 228a1f1..bec2861 100644 --- a/src/standard/literal.ts +++ b/src/standard/literal.ts @@ -4,7 +4,9 @@ import type { DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, + DIMENSION_ANGLE_UNITS, DIMENSION_TEXT_PLACEMENTS, + ZERO_SUPPRESSIONS, } from "../arrowheads.ts"; import type { ArrowheadOf, @@ -338,11 +340,15 @@ type StyleFields = { ? Str> : F extends "radialText" ? Str> - : F extends "writing" - ? { readonly [U in keyof E[F]]: Writing } - : F extends "discipline" - ? Discipline - : unknown; + : F extends "angleUnits" + ? Str> + : F extends "suppressAngleZeros" + ? Str> + : F extends "writing" + ? { readonly [U in keyof E[F]]: Writing } + : F extends "discipline" + ? Discipline + : unknown; }; type DimensionStyle = { diff --git a/src/standard/shape.ts b/src/standard/shape.ts index e7b594a..a40f532 100644 --- a/src/standard/shape.ts +++ b/src/standard/shape.ts @@ -10,6 +10,8 @@ import { DIMENSION_FRACTIONS, DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, + DIMENSION_ANGLE_UNITS, + MAX_ANGLE_PRECISION, JOG_ANGLE, DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, @@ -30,6 +32,9 @@ import { textFitProblem, radialTextProblem, jogAngleProblem, + angleUnitsProblem, + anglePrecisionProblem, + angleZerosProblem, textPlacementProblem, blockNameProblem, dimensionPrefixProblem, @@ -539,6 +544,22 @@ const STYLE_FIELDS = { description: "The angle of a jogged radius dimension's jog to its line, in degrees", default: JOG_ANGLE.default, }, + angleUnits: { + node: string({ enum: DIMENSION_ANGLE_UNITS }, angleUnitsProblem), + description: + "The units an angular dimension writes its angle in: degrees, degrees, minutes and seconds, grads or radians", + default: "degrees", + }, + anglePrecision: { + node: number({ minimum: 0, maximum: MAX_ANGLE_PRECISION }, anglePrecisionProblem), + description: + "How many decimals an angle takes; in degrees, minutes and seconds, 0 writes the degrees, 1 and 2 the minutes too, and 3 and 4 the seconds", + default: 0, + }, + suppressAngleZeros: { + node: string({ enum: ZERO_SUPPRESSIONS }, angleZerosProblem), + description: "The zeros an angle leaves out. Defaults to none", + }, textFit: { node: string({ enum: DIMENSION_TEXT_FITS }, textFitProblem), description: diff --git a/src/svg.ts b/src/svg.ts index 44723ce..039ef1a 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -1499,6 +1499,24 @@ function dimensionToSvg( const parts = [ ...picture.extensionLines.map((ends) => line("extension-line", ends, extension)), ...picture.dimensionLines.map((ends) => line("dimension-line", ends, dimension)), + ...picture.dimensionArcs.map((arc) => + entityToSvg( + { + kind: "arc", + layer: e.layer, + center: arc.center, + radius: arc.radius, + startAngle: arc.start, + endAngle: arc.end, + }, + `data-part="dimension-line"`, + dimension, + look, + undefined, + matrix, + room, + ), + ), ...picture.leader.map((ends) => line("leader", ends, dimension)), ...picture.arrowheads.map((corners) => { if (thin) return line("arrowhead", [corners[0]!, corners[1]!], dimension); diff --git a/standard.json b/standard.json index a63c880..c7eb93c 100644 --- a/standard.json +++ b/standard.json @@ -266,6 +266,8 @@ "textPlacement": "centered", "radialText": "aligned", "jogAngle": 45, + "angleUnits": "degrees", + "anglePrecision": 0, "textFit": "inside", "writing": { "in": { @@ -304,6 +306,8 @@ "textPlacement": "above", "radialText": "aligned", "jogAngle": 45, + "angleUnits": "degrees", + "anglePrecision": 0, "textFit": "inside", "writing": { "in": { @@ -341,6 +345,8 @@ "textPlacement": "above", "radialText": "aligned", "jogAngle": 45, + "angleUnits": "degrees", + "anglePrecision": 0, "textFit": "inside", "writing": { "in": { diff --git a/standard.schema.json b/standard.schema.json index dfd8677..e434d36 100644 --- a/standard.schema.json +++ b/standard.schema.json @@ -321,6 +321,24 @@ "description": "The angle of a jogged radius dimension's jog to its line, in degrees", "default": 45 }, + "angleUnits": { + "type": "string", + "enum": ["degrees", "degrees-minutes-seconds", "grads", "radians"], + "description": "The units an angular dimension writes its angle in: degrees, degrees, minutes and seconds, grads or radians", + "default": "degrees" + }, + "anglePrecision": { + "type": "number", + "minimum": 0, + "maximum": 8, + "description": "How many decimals an angle takes; in degrees, minutes and seconds, 0 writes the degrees, 1 and 2 the minutes too, and 3 and 4 the seconds", + "default": 0 + }, + "suppressAngleZeros": { + "type": "string", + "enum": ["leading", "trailing", "both"], + "description": "The zeros an angle leaves out. Defaults to none" + }, "textFit": { "type": "string", "enum": ["inside", "leader"], @@ -440,6 +458,22 @@ "maximum": 90, "description": "The angle of a jogged radius dimension's jog to its line, in degrees" }, + "angleUnits": { + "type": "string", + "enum": ["degrees", "degrees-minutes-seconds", "grads", "radians"], + "description": "The units an angular dimension writes its angle in: degrees, degrees, minutes and seconds, grads or radians" + }, + "anglePrecision": { + "type": "number", + "minimum": 0, + "maximum": 8, + "description": "How many decimals an angle takes; in degrees, minutes and seconds, 0 writes the degrees, 1 and 2 the minutes too, and 3 and 4 the seconds" + }, + "suppressAngleZeros": { + "type": "string", + "enum": ["leading", "trailing", "both"], + "description": "The zeros an angle leaves out. Defaults to none" + }, "textFit": { "type": "string", "enum": ["inside", "leader"], diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 8481ecb..d95ff2e 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2080,8 +2080,24 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint }; }), ); + // Angular ones: an arc near the vertex or far, a sliver of an angle or most of a turn. + (pick([drawing, layout]).entities as Data[]).push( + ...Array.from({ length: pick([1, 300]) }, (_, i): Data => ({ + kind: "angular-dimension", + layer: "0", + style: style.name, + vertex: [0, i], + from: [10, i], + to: [pick([10, -10, 1e9]), i + pick([0.001, 10, -1e9])], + at: [pick([0.01, 5, 1e9]), i + pick([0.0001, 3, -2])], + text: pick(["<>", long]), + textBelow: pick([long, "A\\P".repeat(5_000)]), + })), + ); style.radialText = pick(["aligned", "horizontal"]); style.jogAngle = pick([5, 45, 90]); + style.angleUnits = pick(["degrees", "degrees-minutes-seconds", "grads", "radians"]); + style.anglePrecision = pick([0, 4, 8]); } // A leader style whose arrowhead or text style every leader reads. if (random() < 0.2) { diff --git a/test/dimensions.test.ts b/test/dimensions.test.ts index 860221e..630aeb5 100644 --- a/test/dimensions.test.ts +++ b/test/dimensions.test.ts @@ -25,7 +25,7 @@ import { type Drawing, type Entity, } from "../src/index.ts"; -import { arrowRoom, measurementText, WIDEST_CHARACTERS } from "../src/dimensions.ts"; +import { angleNumber, arrowRoom, measurementText, WIDEST_CHARACTERS } from "../src/dimensions.ts"; import { toDXFR2018 } from "../src/dxf-r2018.ts"; import { extents } from "../src/extents.ts"; @@ -807,6 +807,7 @@ test("a dimension is written with its style, its points and the block of its pic dimensionLines: ["14E64A214426A5", "1A23E71AA31D32", "1A22E71AA31F7D", "1A25E71AA31254"], leader: ["1C6E99C485049E", "1C7199C48501B7"], belowText: "1A5AD40549288F", + dimensionArcs: ["1FAB45DF867869", "1FAC45DF867AA4", "1FAD45DF867CF3"], }); assert.equal(dimensionPictureHandles({ index: 1 }).record, "16DCBD6115A74B"); assert.equal(dimensionPictureHandles({ index: 0, layout: "a-101" }).record, "1D645DAA891E34"); @@ -1105,3 +1106,133 @@ test("a radial dimension is refused where the leading CAD app would draw what ts /shorter than its text/, ); }); + +test("an angular dimension is built, written and read back, its arc's point picking the angle", async () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + d.angularDimension([0, 0], [2, 0], [0, 2], [3, 3], { style: "S", id: "a" }); + // Its point on the far side of the vertex picks the rest of the turn. + d.angularDimension([0, 0], [2, 0], [0, 2], [-3, -3], { style: "S", text: "<> TYP." }); + const drawing = d.build(); + assert.deepEqual(lint(drawing), []); + assert.deepEqual(fromJSON(toJSON(drawing)), drawing); + const style = drawing.dimensionStyles![0]!; + assert.deepEqual( + drawing.entities.map((e) => dimensionPicture(e as never, style).label.value), + ["90°", "270° TYP."], + ); + const read = await readDXF(toDXF(drawing), { geometry: true }); + const angular = (read.model.entities ?? []).filter((e) => e.kind === "angular-dimension"); + assert.deepEqual( + angular.map((e) => [e.type, e.vertex, e.from, e.to, e.at, Math.round(e.measurement!)]), + [ + ["three-point", [0, 0], [2, 0], [0, 2], [3, 3], 90], + ["three-point", [0, 0], [2, 0], [0, 2], [-3, -3], 270], + ], + ); + // An angle too large for degrees reads as no angle. + const huge = toDXF(drawing).replace("42\r\n1.5707963267949\r\n", "42\r\n1e308\r\n"); + const hugeRead = await readDXF(huge, { geometry: true }); + assert.equal((hugeRead.model.entities![0] as { measurement?: number }).measurement, undefined); +}); + +test("an angle is written in each unit and precision as the leading CAD app writes it", () => { + const at = (degrees: number, style: Parameters[1]): string => + angleNumber((degrees * Math.PI) / 180, style); + const dms = { angleUnits: "degrees-minutes-seconds" } as const; + // Each from a case the app drew, of the angle its points make. + assert.deepEqual( + [0, 1, 2, 3, 4, 5, 6, 8].map((places) => at(123.456705888, { ...dms, anglePrecision: places })), + [ + "123°", + "123°27'", + "123°27'", + `123°27'24"`, + `123°27'24"`, + `123°27'24.1"`, + `123°27'24.14"`, + `123°27'24.1412"`, + ], + ); + // Rounding carries into the minutes and the degrees. + assert.equal(at(45.999993816, { ...dms, anglePrecision: 5 }), `46°0'0.0"`); + assert.equal(at(45.999993816, { ...dms, anglePrecision: 6 }), `45°59'59.98"`); + assert.equal(at(123.456705888, { anglePrecision: 2 }), "123.46°"); + assert.equal(at(89.995007537, { anglePrecision: 2 }), "90.00°"); + assert.equal(at(45.000007829, { angleUnits: "grads", anglePrecision: 2 }), "50.00g"); + assert.equal(at(20.000009666, { angleUnits: "radians", anglePrecision: 3 }), "0.349r"); + assert.deepEqual( + (["leading", "trailing", "both"] as const).map((zeros) => + at(0.5, { anglePrecision: 2, suppressAngleZeros: zeros }), + ), + [".50°", "0.5°", ".5°"], + ); +}); + +test("an angular dimension is refused where the leading CAD app would draw what tsdraft does not", () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + d.dimensionStyle({ ...sizes, name: "OUT", textFit: "leader" }); + assert.throws( + () => d.angularDimension([0, 0], [0, 0], [0, 2], [3, 3], { style: "S" }), + /no direction/, + ); + assert.throws( + () => d.angularDimension([0, 0], [2, 0], [0, 2], [0, 0], { style: "S" }), + /no radius/, + ); + assert.throws( + () => d.angularDimension([0, 0], [2, 0], [4, 0], [3, 3], { style: "S" }), + /no angle/, + ); + // The arc through one of its points, whose extension line runs either way by a rounding. + assert.throws( + () => d.angularDimension([0, 0], [2, 0], [0, 2], [1.2, 1.6], { style: "S" }), + /passes through one of its two points/, + ); + // The arc's point on one of the lines, where a rounding picks the angle or the rest of the turn. + assert.throws( + () => d.angularDimension([1.1, 2.3], [1.2, 2.37], [1.03, 2.4], [1.3, 2.44], { style: "S" }), + /on one of its two lines/, + ); + // A centered text that leaves the arc no room each side, with no marks to turn. + d.dimensionStyle({ ...sizes, name: "BARE", arrowSize: 0, textPlacement: "centered" }); + assert.throws( + () => d.angularDimension([0, 0], [2, 0], [2, 0.05], [1, 0.01], { style: "BARE" }), + /too short for its text "centered"/, + ); + // The rest of the turn, its centered text and arrowheads too wide for each half of it. + d.dimensionStyle({ + ...sizes, + name: "WIDE", + textPlacement: "centered", + textHeight: 0.25, + textGap: 0.1, + extensionOffset: 0, + extensionBeyond: 0, + }); + assert.throws( + () => d.angularDimension([0, 0], [2, 0], [2, -0.2], [-0.55, 0], { style: "WIDE" }), + /too short for its text "centered"/, + ); + // An arc of all but a whole turn, which its 6 decimals write with one angle at both ends. + d.dimensionStyle({ ...sizes, name: "THIN", arrowSize: 0 }); + assert.throws( + () => d.angularDimension([0, 0], [1000, 0], [1000, 0.000007], [-2000, 0], { style: "THIN" }), + /all but a whole turn/, + ); + // Closed arrowheads longer than the arc is wide. + assert.throws( + () => d.angularDimension([0, 0], [2, 0], [0, 2], [0.04, 0.04], { style: "S" }), + /as long as its arc is wide/, + ); + // A text too wide for the arc, which "leader" moves outside. + assert.throws( + () => d.angularDimension([0, 0], [2, 0], [2, 0.1], [0.5, 0.01], { style: "OUT" }), + /too short for its text/, + ); + assert.throws( + () => d.dimensionStyle({ ...sizes, name: "BAD", anglePrecision: 9 }), + /anglePrecision must be a whole number from 0 to 8/, + ); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index edf3559..90ae724 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -445,6 +445,40 @@ export function readProblems( } return; } + case "angular-dimension": { + if (!kind("angular-dimension") || got.kind !== "angular-dimension") return; + if (got.type !== "three-point") say(`${label}: ${got.type}, expected three-point`); + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if ( + !nearPoint(got.vertex ?? [NaN, NaN], point(want.vertex)) || + !nearPoint(got.from ?? [NaN, NaN], point(want.from)) || + !nearPoint(got.to ?? [NaN, NaN], point(want.to)) + ) { + say(`${label}: vertex ${got.vertex}, from ${got.from}, to ${got.to}`); + } + // The leading CAD app keeps a point of the arc of its own choosing. + if (by === "tsdraft" && !nearPoint(got.at, point(want.at))) + say(`${label}: arc at ${got.at}`); + if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { + say(`${label}: text ${JSON.stringify(got.text)}`); + } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { + say(`${label}: text below ${JSON.stringify(got.textBelow)}`); + } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; + const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); + const picture = dimensionPicture(want, style, font); + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { + say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); + } + const degrees = (dimensionMeasure(want).measurement * 180) / Math.PI; + if (got.measurement === undefined || Math.abs(got.measurement - degrees) > 1e-9 * degrees) { + say(`${label}: measures ${got.measurement}, expected ${degrees}`); + } + return; + } case "leader": { if (!kind("multileader") || got.kind !== "multileader") return; const style = findLeaderStyle(drawing, want.style); diff --git a/test/read.test.ts b/test/read.test.ts index b4445c4..7dcfb54 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -1012,7 +1012,7 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only [ [0, "DIMENSION"], [8, "A"], - [70, 34], + [70, 38], ], [ [0, "MULTILEADER"], @@ -1064,7 +1064,7 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only ); assert.deepEqual(Object.keys(plain(plainLine) as object).sort(), ["from", "kind", "layer", "to"]); assert.deepEqual(plain(read.model.other), { - "DIMENSION angular": 1, + "DIMENSION ordinate": 1, "MULTILEADER in 3D": 1, }); assert.deepEqual(plain(read.unread.malformed), { "LINE with a number that is not finite": 1 }); diff --git a/test/shape.test.ts b/test/shape.test.ts index 37b2331..3162b03 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -217,6 +217,18 @@ const kinds: { textBelow: "CURB", id: "h-j", }, + "angular-dimension": { + kind: "angular-dimension", + layer: "0", + style: "ARCH", + vertex: [0, 0], + from: [10, 0], + to: [0, 10], + at: [7, 7], + text: "<> TYP", + textBelow: "MIN.", + id: "h-a", + }, }; /** A polyline of one width, with every field the polyline of `kinds` leaves out. */ @@ -311,6 +323,9 @@ const full: Required & { extensionLineweight: 0.25, radialText: "horizontal", jogAngle: 30, + angleUnits: "degrees-minutes-seconds", + anglePrecision: 4, + suppressAngleZeros: "leading", }, { name: "ARCH", @@ -336,6 +351,9 @@ const full: Required & { extensionLineweight: 0.18, radialText: "aligned", jogAngle: 45, + angleUnits: "degrees", + anglePrecision: 0, + suppressAngleZeros: "both", }, ], leaderStyles: [ @@ -623,7 +641,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #14: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #15: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ From f18c2bf360e7aa8220eb4a6a8120277b40f11a4b Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 11:12:47 -0500 Subject: [PATCH 12/35] Solid fills, wipeouts and masks: written, read and plotted as CAD programs draw them Solid fills, wipeouts and masks, in R2018 drawings. - `d.hatch(boundary)` fills the area inside one outline, or inside a list of loops `{ points, bulges? }`, solid in its layer's color. The area inside an odd number of loops is filled, so a loop inside another is a hole and one inside a hole fills again, whichever way each runs. CAD programs fill one the same way. - `d.wipeout(points)` draws a polygon in the paper's color, which hides what is drawn before it. Its frame is drawn in its pen unless `Drawing.wipeoutFrame` is `false`. - A paragraph's `mask` hides what is drawn before it behind its box, grown by `offsetFactor`. A dimension style's `textMask` masks every dimension's text, its box grown by a quarter of the text's height. `LeaderMask` is now `TextMask`, which a leader's and a paragraph's mask share. - Both writers write each as CAD programs hold it, and `toSVG` and `toPDF` draw it where it plots. `lint` and the builder refuse a hatch with no loop, a loop of fewer than 3 points (or 2 joined by an arc), a wipeout of fewer than 3 points, on one line or with sides that cross, a mask of another shape, and a mask on a paragraph in columns, which tsdraft does not yet draw. - `readDXF` reads a hatch: its loops of polylines, or of lines and arcs as points and bulges, its pattern and its island style. It also reads a wipeout, an `MTEXT`'s background mask, a dimension style's `textFill`, the order a file's sort table draws a space or a block in (`drawOrder`), and whether wipeouts' frames show (`header.wipeoutFrame`). - The example sheet's north arrow has its east half filled. [Fills, wipeouts and masks](docs/fills.md) describes them all. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 7 + CHANGELOG.md | 17 ++ GUIDE.md | 5 + README.md | 32 +++- docs/assets/outdoor-kitchen-dark.svg | 82 +++++--- docs/assets/outdoor-kitchen-light.svg | 82 +++++--- docs/assets/plan-set-A-101-dark.svg | 44 +++-- docs/assets/plan-set-A-101-light.svg | 44 +++-- docs/assets/plan-set-A-201-dark.svg | 128 ++++++++----- docs/assets/plan-set-A-201-light.svg | 128 ++++++++----- docs/assets/site-plan-dark.svg | 20 +- docs/assets/site-plan-light.svg | 20 +- docs/fills.md | 131 +++++++++++++ docs/format.md | 7 + docs/plotting.md | 3 + docs/reading.md | 20 ++ docs/rules.md | 7 + examples/site-plan.ts | 16 +- src/drawing.ts | 171 ++++++++++++++++- src/dxf-r2018.ts | 141 +++++++++++++- src/extents.ts | 62 ++++++- src/fills.ts | 258 ++++++++++++++++++++++++++ src/index.ts | 21 ++- src/leaders.ts | 26 +-- src/lint.ts | 93 +++++++++- src/pdf.ts | 29 ++- src/read/check.ts | 22 +++ src/read/dxf.ts | 130 ++++++++++++- src/read/entities.ts | 168 +++++++++++++++++ src/read/model.ts | 79 +++++++- src/rules.ts | 65 ++++++- src/shape.ts | 13 ++ src/svg.ts | 122 +++++++++++- test/bounded.test.ts | 51 +++++ test/dimensions.test.ts | 28 +++ test/drawing.test.ts | 39 +++- test/format.test.ts | 2 +- test/read-fuzz.ts | 4 + test/read.test.ts | 6 +- test/shape.test.ts | 34 +++- 40 files changed, 2105 insertions(+), 252 deletions(-) create mode 100644 docs/fills.md create mode 100644 src/fills.ts diff --git a/AGENTS.md b/AGENTS.md index 807c350..6fdb709 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -372,6 +372,13 @@ as it is and marks the `` `data-opaque`, which `toPDF` reads. That is the one place the preview and the plot part. A PNG the plot must decode and cannot is drawn by neither, as a file not given. +- `src/fills.ts` is the one place of what a hatch, a wipeout and a text's mask draw: a hatch's loops + and their sides, filled by parity, which the writers make the leading CAD app's rule too by island + style normal and polyline loops; a wipeout's square picture of one pixel and its clip; a mask's box + and factor, a paragraph's and a dimension style's. The writers, `toSVG`, the extents, `lint` and + the readers take them from it. The wipeout frame is the dictionary variable `WIPEOUTFRAME`, which is + what that app reads, beside `WIPEOUTVARIABLES`, which it does not. A hatch is drawn as one path + with `fill-rule="evenodd"`, which `toPDF` writes as `f*`. - `src/pdf.ts` plots layouts to PDF from the pictures `toSVG` draws of them, and decides nothing about a drawing: every rule of what a sheet plots stays in `toSVG`, so the preview and the plot cannot part. It reads the closed set of elements and attributes `toSVG` writes diff --git a/CHANGELOG.md b/CHANGELOG.md index cad0ec5..c524604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- Solid fills, wipeouts and masks, in R2018 drawings. `d.hatch(boundary)` fills the area inside + one outline, or inside a list of loops `{ points, bulges? }`, solid in its layer's color: the + area inside an odd number of loops is filled, so a loop inside another is a hole, whichever + way each runs, as CAD programs fill one. `d.wipeout(points)` draws a polygon in the paper's + color, which hides what is drawn before it, with its frame in its pen unless + `Drawing.wipeoutFrame` is `false`. A paragraph's `mask` hides what is drawn before it behind its + box grown by `offsetFactor`, and a dimension style's `textMask` masks every dimension's text, its + box grown by a quarter of the text's height. Both writers write each as CAD programs hold it, and + `toSVG` and `toPDF` draw it where it plots. `lint` and the builder refuse a hatch with no loop + or a loop of fewer than 3 points, or 2 joined by an arc; a wipeout of fewer than 3 points, on + one line or with sides that cross; and a mask of another shape. `LeaderMask` is now + `TextMask`, which a leader's and a paragraph's mask share. +- `readDXF` and `readDWG` read a hatch, its loops of polylines or of lines and arcs as points and + bulges, its pattern and its island style; a wipeout; an `MTEXT`'s background mask; the order a + file's sort table draws a space or a block in, `drawOrder`; and whether wipeouts' frames show, + `header.wipeoutFrame`. + - Leaders' notes, as CAD programs draw them. A note is laid out as paragraph text is, each line set by the ink of its letters, so its lines move where they plot by up to a quarter of their height from where earlier versions drew them. `attachment` takes every place CAD programs diff --git a/GUIDE.md b/GUIDE.md index 429d53d..5777a45 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -67,6 +67,11 @@ inside it, and `donut` a filled ring or dot. [docs/polylines.md](docs/polylines. `rasterSize` reads, and an optional `clip`; the command reads the file from the drawing file's folder for the pictures, and warns of one that is missing. [docs/images.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/images.md) has them. +`hatch` fills one outline, or a list of loops `{ points, bulges? }` where a loop inside another is +a hole, solid in the layer's color; `wipeout` hides what is drawn before it behind a polygon; and +a paragraph's `mask: true` hides what is drawn before it behind its text. Draw a fill before the +lines over it. +[docs/fills.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/fills.md) has them. Give an entity an `id` when you will want to find it again: 1 to 64 letters, digits, `.`, `-` and `_`, each used once in a drawing. A diagnostic about the entity carries the id. diff --git a/README.md b/README.md index c30c4e4..88437d6 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,34 @@ toPDF(drawing, { images: { "aerial.png": readFileSync("aerial.png") } }); [Images](docs/images.md) has clips, frames and transparency, and what `lint` refuses. +A hatch fills the area inside its loops solid, a loop inside another a hole. A wipeout hides what +is drawn before it, and a paragraph's mask hides it behind the text: + +```ts +d.hatch([ + { + points: [ + [0, 0], + [96, 0], + [96, 8], + [0, 8], + ], + }, + { + points: [ + [36, 0], + [72, 0], + [72, 8], + [36, 8], + ], + }, +]); +d.paragraph("VERIFY IN FIELD", { at: [40, 20], height: 3, mask: true }); +``` + +[Fills, wipeouts and masks](docs/fills.md) has holes and arcs, wipeouts' frames, a dimension +style's mask and the draw order. + A dimension measures between two points and writes what it measures. In the file it is a dimension, which a CAD program measures again when its points move, and a dimension style says how it is drawn: @@ -274,7 +302,7 @@ feet and inches with stacked fractions, words below the line and text on a leade layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have overlines in paragraph text, ellipses, splines or points, hatches, solid fills or masks, images, tables, color or transparency set on one +It does not yet have overlines in paragraph text, ellipses, splines or points, hatch patterns or gradients, tables, color or transparency set on one entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit @@ -380,6 +408,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, transparency, how the plot draws one, and what `lint` refuses. +- [Fills, wipeouts and masks](docs/fills.md) covers solid hatches with holes, wipeouts, the + masks of paragraphs, leaders and dimensions, the draw order, and what `lint` refuses. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. - [Xrefs](docs/xrefs.md) covers references to DWG files: the path, units, a diff --git a/docs/assets/outdoor-kitchen-dark.svg b/docs/assets/outdoor-kitchen-dark.svg index afb5891..9f83572 100644 --- a/docs/assets/outdoor-kitchen-dark.svg +++ b/docs/assets/outdoor-kitchen-dark.svg @@ -1,12 +1,12 @@ - - + + - + - + @@ -30,7 +30,7 @@ - + @@ -144,7 +144,7 @@ - + @@ -204,7 +204,7 @@ - + @@ -3247,90 +3247,110 @@ - STUCCO FINISH, - PAINTED + + STUCCO FINISH, + PAINTED + - FLOATING - SHELVES + + FLOATING + SHELVES + - 36" BUILT-IN - GAS GRILL + + 36" BUILT-IN + GAS GRILL + - TILE BACKSPLASH + + TILE BACKSPLASH + - STONE COUNTERTOP + + STONE COUNTERTOP + - 24" UNDERCOUNTER - REFRIGERATOR + + 24" UNDERCOUNTER + REFRIGERATOR + + STAINLESS VENT HOOD + + ALUMINUM WINDOW + + UNDERMOUNT SINK + + 3" FILLER, TYP. + 2 - + 1 - + OUTDOOR KITCHEN ELEVATION 3/8" = 1'-0" - + @@ -3345,7 +3365,7 @@ - + @@ -4078,7 +4098,7 @@ - + @@ -4131,60 +4151,74 @@ + R-30 BATT INSULATION + + 8" DUCT TO ROOF CAP + + STAINLESS VENT HOOD + + STUCCO ON 8" CMU W/ #5 VERT. @ 48" O.C. + + STAINLESS ACCESS DOOR + + 4" CONCRETE PATIO SLAB + + 20"x20" FOOTING W/ (2) #5 CONT. - + + 2 - + diff --git a/docs/assets/outdoor-kitchen-light.svg b/docs/assets/outdoor-kitchen-light.svg index 7b7e449..522d594 100644 --- a/docs/assets/outdoor-kitchen-light.svg +++ b/docs/assets/outdoor-kitchen-light.svg @@ -1,12 +1,12 @@ - - + + - + - + @@ -30,7 +30,7 @@ - + @@ -144,7 +144,7 @@ - + @@ -204,7 +204,7 @@ - + @@ -3247,90 +3247,110 @@ - STUCCO FINISH, - PAINTED + + STUCCO FINISH, + PAINTED + - FLOATING - SHELVES + + FLOATING + SHELVES + - 36" BUILT-IN - GAS GRILL + + 36" BUILT-IN + GAS GRILL + - TILE BACKSPLASH + + TILE BACKSPLASH + - STONE COUNTERTOP + + STONE COUNTERTOP + - 24" UNDERCOUNTER - REFRIGERATOR + + 24" UNDERCOUNTER + REFRIGERATOR + + STAINLESS VENT HOOD + + ALUMINUM WINDOW + + UNDERMOUNT SINK + + 3" FILLER, TYP. + 2 - + 1 - + OUTDOOR KITCHEN ELEVATION 3/8" = 1'-0" - + @@ -3345,7 +3365,7 @@ - + @@ -4078,7 +4098,7 @@ - + @@ -4131,60 +4151,74 @@ + R-30 BATT INSULATION + + 8" DUCT TO ROOF CAP + + STAINLESS VENT HOOD + + STUCCO ON 8" CMU W/ #5 VERT. @ 48" O.C. + + STAINLESS ACCESS DOOR + + 4" CONCRETE PATIO SLAB + + 20"x20" FOOTING W/ (2) #5 CONT. - + + 2 - + diff --git a/docs/assets/plan-set-A-101-dark.svg b/docs/assets/plan-set-A-101-dark.svg index 28c9161..0034712 100644 --- a/docs/assets/plan-set-A-101-dark.svg +++ b/docs/assets/plan-set-A-101-dark.svg @@ -655,51 +655,65 @@ - 16'-0" X 8'-0" IMPACT RATED - OVERHEAD DOOR, SEE A-601 + + 16'-0" X 8'-0" IMPACT RATED + OVERHEAD DOOR, SEE A-601 + - RAISED LANAI SLAB EL. 10.67' NAVD, - ON STEM WALLS PER S-101, 36" GUARD + + RAISED LANAI SLAB EL. 10.67' NAVD, + ON STEM WALLS PER S-101, 36" GUARD + - ENTRY PORCH SLAB EL. 10.67' NAVD, - 4" STEP DOWN FROM DOOR 101, - 36" GUARD AT OPEN EDGE + + ENTRY PORCH SLAB EL. 10.67' NAVD, + 4" STEP DOWN FROM DOOR 101, + 36" GUARD AT OPEN EDGE + - 5R DN TO WALK AT 8.00', - HANDRAILS BOTH SIDES + + 5R DN TO WALK AT 8.00', + HANDRAILS BOTH SIDES + - 4R DN TO GARAGE SLAB, - HANDRAIL, 36" LANDING + + 4R DN TO GARAGE SLAB, + HANDRAIL, 36" LANDING + - 4R DN TO POOL DECK - AT 8.40' NAVD + + 4R DN TO POOL DECK + AT 8.40' NAVD + - FLOOD VENT, TYP. OF 4, - SEE S-101 + + FLOOD VENT, TYP. OF 4, + SEE S-101 + diff --git a/docs/assets/plan-set-A-101-light.svg b/docs/assets/plan-set-A-101-light.svg index b5d5ffd..c914a84 100644 --- a/docs/assets/plan-set-A-101-light.svg +++ b/docs/assets/plan-set-A-101-light.svg @@ -655,51 +655,65 @@ - 16'-0" X 8'-0" IMPACT RATED - OVERHEAD DOOR, SEE A-601 + + 16'-0" X 8'-0" IMPACT RATED + OVERHEAD DOOR, SEE A-601 + - RAISED LANAI SLAB EL. 10.67' NAVD, - ON STEM WALLS PER S-101, 36" GUARD + + RAISED LANAI SLAB EL. 10.67' NAVD, + ON STEM WALLS PER S-101, 36" GUARD + - ENTRY PORCH SLAB EL. 10.67' NAVD, - 4" STEP DOWN FROM DOOR 101, - 36" GUARD AT OPEN EDGE + + ENTRY PORCH SLAB EL. 10.67' NAVD, + 4" STEP DOWN FROM DOOR 101, + 36" GUARD AT OPEN EDGE + - 5R DN TO WALK AT 8.00', - HANDRAILS BOTH SIDES + + 5R DN TO WALK AT 8.00', + HANDRAILS BOTH SIDES + - 4R DN TO GARAGE SLAB, - HANDRAIL, 36" LANDING + + 4R DN TO GARAGE SLAB, + HANDRAIL, 36" LANDING + - 4R DN TO POOL DECK - AT 8.40' NAVD + + 4R DN TO POOL DECK + AT 8.40' NAVD + - FLOOD VENT, TYP. OF 4, - SEE S-101 + + FLOOD VENT, TYP. OF 4, + SEE S-101 + diff --git a/docs/assets/plan-set-A-201-dark.svg b/docs/assets/plan-set-A-201-dark.svg index eb40735..85d50e7 100644 --- a/docs/assets/plan-set-A-201-dark.svg +++ b/docs/assets/plan-set-A-201-dark.svg @@ -293,77 +293,99 @@ - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + - IMPACT RATED WINDOW, - SEE A-601 + + IMPACT RATED WINDOW, + SEE A-601 + - 5/8" STUCCO ON 8" CMU + + 5/8" STUCCO ON 8" CMU + - 36" GUARD AT PORCH EDGE, - 4" SPHERE MAX. OPENING (R312.1) + + 36" GUARD AT PORCH EDGE, + 4" SPHERE MAX. OPENING (R312.1) + - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + - 16'-0" X 8'-0" IMPACT - OVERHEAD DOOR, SEE A-601 + + 16'-0" X 8'-0" IMPACT + OVERHEAD DOOR, SEE A-601 + - ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS - AT 11", HANDRAILS BOTH SIDES AT 34"-38" + + ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS + AT 11", HANDRAILS BOTH SIDES AT 34"-38" + - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + @@ -720,77 +742,99 @@ - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + - LANAI ROOF, STANDING SEAM - METAL AT 3:12, SEE S-102 + + LANAI ROOF, STANDING SEAM + METAL AT 3:12, SEE S-102 + - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + - IMPACT RATED WINDOW, - SEE A-601 + + IMPACT RATED WINDOW, + SEE A-601 + - 5/8" STUCCO ON 8" CMU + + 5/8" STUCCO ON 8" CMU + - 36" GUARD AT LANAI, 3 SIDES, - 4" SPHERE MAX. OPENING (R312.1) + + 36" GUARD AT LANAI, 3 SIDES, + 4" SPHERE MAX. OPENING (R312.1) + - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + - LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, - HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' + + LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, + HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' + - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + diff --git a/docs/assets/plan-set-A-201-light.svg b/docs/assets/plan-set-A-201-light.svg index d17c420..f75f89f 100644 --- a/docs/assets/plan-set-A-201-light.svg +++ b/docs/assets/plan-set-A-201-light.svg @@ -293,77 +293,99 @@ - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + - IMPACT RATED WINDOW, - SEE A-601 + + IMPACT RATED WINDOW, + SEE A-601 + - 5/8" STUCCO ON 8" CMU + + 5/8" STUCCO ON 8" CMU + - 36" GUARD AT PORCH EDGE, - 4" SPHERE MAX. OPENING (R312.1) + + 36" GUARD AT PORCH EDGE, + 4" SPHERE MAX. OPENING (R312.1) + - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + - 16'-0" X 8'-0" IMPACT - OVERHEAD DOOR, SEE A-601 + + 16'-0" X 8'-0" IMPACT + OVERHEAD DOOR, SEE A-601 + - ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS - AT 11", HANDRAILS BOTH SIDES AT 34"-38" + + ENTRY STAIR: 5 RISERS AT 6.4", 4 TREADS + AT 11", HANDRAILS BOTH SIDES AT 34"-38" + - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + @@ -720,77 +742,99 @@ - STANDING SEAM METAL ROOFING, 24 GA., - 6:12, ON SELF-ADHERED UNDERLAYMENT + + STANDING SEAM METAL ROOFING, 24 GA., + 6:12, ON SELF-ADHERED UNDERLAYMENT + - ALUMINUM FASCIA AND - VENTED ALUMINUM SOFFIT + + ALUMINUM FASCIA AND + VENTED ALUMINUM SOFFIT + - STUCCO ON LATH OVER 7/16" OSB - ON 2X6 STUDS AT 16" O.C. + + STUCCO ON LATH OVER 7/16" OSB + ON 2X6 STUDS AT 16" O.C. + - LANAI ROOF, STANDING SEAM - METAL AT 3:12, SEE S-102 + + LANAI ROOF, STANDING SEAM + METAL AT 3:12, SEE S-102 + - STUCCO BAND AT FLOOR LINE, - CONTROL JOINT TOP AND BOTTOM + + STUCCO BAND AT FLOOR LINE, + CONTROL JOINT TOP AND BOTTOM + - IMPACT RATED WINDOW, - SEE A-601 + + IMPACT RATED WINDOW, + SEE A-601 + - 5/8" STUCCO ON 8" CMU + + 5/8" STUCCO ON 8" CMU + - 36" GUARD AT LANAI, 3 SIDES, - 4" SPHERE MAX. OPENING (R312.1) + + 36" GUARD AT LANAI, 3 SIDES, + 4" SPHERE MAX. OPENING (R312.1) + - STUCCO ON CMU STEM WALL, - COMPACTED FILL BELOW SLAB + + STUCCO ON CMU STEM WALL, + COMPACTED FILL BELOW SLAB + - LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, - HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' + + LANAI STEPS: 4 RISERS AT 6.8", 11" TREADS, + HANDRAILS BOTH SIDES, TO POOL DECK EL. 8.40' + - FINISH GRADE EL. 8.00' NAVD, SLOPE - AWAY 6" IN 10'-0" (FBC-R R401.3) + + FINISH GRADE EL. 8.00' NAVD, SLOPE + AWAY 6" IN 10'-0" (FBC-R R401.3) + diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index 7ab1b83..ed4b149 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -169,14 +169,18 @@ - EXISTING TREE TO REMAIN, TYP. + + EXISTING TREE TO REMAIN, TYP. + - EXISTING OAK - TO REMAIN + + EXISTING OAK + TO REMAIN + @@ -267,14 +271,16 @@ N - - + + + N - - + + + diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index 4626cab..aa25144 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -169,14 +169,18 @@ - EXISTING TREE TO REMAIN, TYP. + + EXISTING TREE TO REMAIN, TYP. + - EXISTING OAK - TO REMAIN + + EXISTING OAK + TO REMAIN + @@ -267,14 +271,16 @@ N - - + + + N - - + + + diff --git a/docs/fills.md b/docs/fills.md new file mode 100644 index 0000000..4220eca --- /dev/null +++ b/docs/fills.md @@ -0,0 +1,131 @@ +# Fills, wipeouts and masks + +A solid fill is a hatch: an area filled in its pen's color, which CAD programs hold as one entity a +drafter selects, edits and measures as one. Wall poché, filled arrowheads, bar dots and the filled +parts of symbols are hatches. A wipeout is a polygon filled with the paper's color, which hides +what is drawn before it. A mask hides what is drawn before a text, behind the text's box: a +paragraph, a leader's note and a dimension's text each take one. + +Hatches, wipeouts and masks are R2018 only. The builder and `lint` refuse one in an R12 drawing. + +## Hatches + +`d.hatch(boundary)` fills the area inside one outline, or inside a list of loops. A loop is +`{ points, bulges? }`: its points in order, closed back to the first, and a bulge for each side, +as a closed polyline's are, so a side can be an arc. The area inside an odd number of loops is +filled. A loop inside another is a hole, and a loop inside a hole fills again: + +```ts +const d = createDrawing({ units: "in" }); +d.layer("A-WALL-PATT", { color: 8 }, () => { + // A wall 8 inches thick with a window cut out of it. + d.hatch([ + { + points: [ + [0, 0], + [96, 0], + [96, 8], + [0, 8], + ], + }, + { + points: [ + [36, 0], + [72, 0], + [72, 8], + [36, 8], + ], + }, + ]); + // A dot, a circle of two half-circle sides. + d.hatch([ + { + points: [ + [100, 4], + [101, 4], + ], + bulges: [1, 1], + }, + ]); +}); +``` + +The loops may come in any order and run either way round, and they may cross: CAD programs fill +by the parity of the loops around each point, and tsdraft writes every hatch so that they do. +Two loops that overlap leave their overlap empty, and the same loop twice fills nothing. + +A loop needs at least 3 points, or 2 joined by an arc. `lint` refuses a hatch with no loop, a +loop of fewer points, and a list of bulges that does not have one for each side. + +A hatch is filled in its layer's color, with no outline whatever its lineweight. Draw its boundary +as a polyline of its own where the sheet shows one. In a block, an insert's scale and rotation place a hatch as they place the rest of the +block, and a negative scale mirrors it. + +Hatch patterns, a firm's own pattern file and gradients come later. A hatch today is solid. + +## Wipeouts + +`d.wipeout(points)` draws a polygon of three or more corners in the paper's color, which hides +what is drawn before it and is hidden by what is drawn after: + +```ts +d.layer("A-ANNO-WIPE", { color: 7 }, () => + d.wipeout([ + [2, 2], + [5, 2], + [5, 3], + [2, 3], + ]), +); +``` + +Its frame, the polygon drawn in its pen, shows and plots unless `Drawing.wipeoutFrame` is `false`. +It is one setting for every wipeout of the drawing, as CAD programs hold it. A sheet whose +wipeouts are masks behind notes wants it `false`. + +`lint` refuses a wipeout of fewer than 3 points, one whose points lie on one line once rounded to +the 6 decimals tsdraft writes, and one whose sides cross: CAD programs hide nothing behind one of +those. The points may end with the first again. + +## Masks + +A paragraph's `mask` and a leader's `mask` are a `TextMask`: `true` for the drawing's background, +or `{ color?, offsetFactor? }` for a color index of its own, 1 to 256, where 256 is the layer's, +and the factor of the text height the box grows by. A mask is the text's box grown by the factor +less one times the text's height on each side, 1.5 unless given, from 1 to 5. A paragraph in +columns takes no mask yet. Here a note hides the lines behind it: + +```ts +d.paragraph("VERIFY ALL DIMENSIONS IN THE FIELD", { + at: [1, 6], + width: 2.5, + height: 0.1, + mask: true, +}); +``` + +A paragraph's box is as wide as its width, or its widest line where a word reaches past the +width, and as high as its lines. A leader's mask covers its note's box. + +A dimension style's `textMask` masks the text of every dimension in the style: `true` for the +drawing's background, or `{ color }`. Its box grows by a quarter of the text's height each side, +as CAD programs grow a dimension's. + +A mask hides what is drawn before its text and nothing drawn after it. The preview draws a mask +in the background's color in white and marks it `data-mask="background"`. + +## Draw order + +What a drawing draws later is drawn over what it draws earlier: entities draw in the order of +their list, model space's, a layout's or a block's. So draw a fill before the lines over it, and +a wipeout after what it hides and before the note on it. A file a CAD program saved may hold a +sort table that draws its entities in another order: [reading](reading.md) has the order it +gives, `drawOrder`. + +## In the file + +A hatch is a `HATCH` of the pattern `SOLID`, with island detection normal and each loop a +polyline path. A wipeout is a `WIPEOUT`, a square picture of one pixel clipped by its polygon, and +the drawing holds `WIPEOUTVARIABLES` and the dictionary variable `WIPEOUTFRAME`, which is what CAD +programs read of whether frames show. A mask is the background of an `MTEXT`, and a dimension +style's is its `DIMTFILL` and `DIMTFILLCLR` and the background of the `MTEXT` of its picture. diff --git a/docs/format.md b/docs/format.md index 0a2f6ee..e4e36d6 100644 --- a/docs/format.md +++ b/docs/format.md @@ -96,6 +96,13 @@ entity, which its frame is drawn in. `imageFrame: false` on the drawing hides ev A drawing with no image has the JSON it had before images existed. [Images](images.md) describes them. +A hatch is an entity of kind `"hatch"`, with its `layer` and its `loops`, each `{ points }` and +where a side is an arc its `bulges`, one for each side, and the `linetype` and `lineweight` of +every entity. A wipeout is an entity of kind `"wipeout"`, with its `layer` and its `points`. +`wipeoutFrame: false` on the drawing hides every wipeout's frame. A paragraph's `mask` and a +dimension style's `textMask` are written where they are set. A drawing with none of them has the +JSON it had before they existed. [Fills, wipeouts and masks](fills.md) describes them. + A drawing written by hand needs `format: 0` too. `lint` reports a drawing without it, or with another version, under the rule `format`, and `toDXF` refuses to write it. `lint` takes any plain data and never throws: a list that is not an array, an entity of an unknown `kind`, a diff --git a/docs/plotting.md b/docs/plotting.md index 5705a23..57f5c24 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -65,6 +65,9 @@ preview shows it: dashes as [How it plots](polylines.md#how-it-plots) says. - An image is drawn from its file's bytes, given as `images`, clipped to its clip, with its frame in its pen, and the PDF holds each file once, as [Plotting](images.md#plotting) says. +- A hatch is filled by the parity of its loops, a wipeout and a mask in the paper's white or a + mask's color, each over what is drawn before it, as [Fills, wipeouts and + masks](fills.md) says. - Each layer is a layer of the PDF too, by the name the picture gives it, `XREF|LAYER` for a layer of an xref, so a PDF viewer lists the layers and can hide one. - Each page has a bookmark and a page label with its layout's name. diff --git a/docs/reading.md b/docs/reading.md index 61de4bf..a08a1d1 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -160,6 +160,26 @@ leader: file says not to show and `unclipped` for one it says not to clip say so, and `brightness`, `contrast` and `fade` are left out at 50, 50 and 0. An image out of the plane is counted under `other`. +- `hatch`: its `pattern`, such as `SOLID` or `ANSI31`, whether it is `solid`, its island `style`, + `normal`, `outer` or `ignore`, `associative` where the file ties it to what it bounds, and its + `loops`, each its `points`, its `bulges` where a side is an arc, and its `flags` as the file + holds them: 1 external, 2 a polyline, 4 derived, 8 a text's box, 16 outermost. A loop of lines + and arcs is read as points and bulges, a whole circle as two half circles. CAD programs fill a + hatch of style `normal` by the parity of all its loops, one of style `outer` by the parity of + those marked external or outermost, and one of style `ignore` by the external ones. A hatch + bounded by an ellipse or a spline is counted under `other`, as is one out of the plane. +- `wipeout`: its `points` in the world's coordinates, without the first again at the end. +- An `mtext` with a background holds `mask`: its `offsetFactor`, and its `color` or `trueColor` + where it is not in the drawing's background. + +`header.wipeoutFrame` is the file's dictionary variable `WIPEOUTFRAME`, which CAD programs read of +whether wipeouts' frames show: 0 neither shown nor plotted, 1 both, 2 shown and not plotted. A +file without it shows and plots them. + +With `geometry`, a space, a layout or a block whose file holds a sort table has `drawOrder`: the +handles of its entities in the order CAD programs draw them, by each one's sort handle, or its own +handle where the table gives none. Without a sort table they draw in the order of the file, the +order of `entities`. Each keeps the pen it sets for itself, each part left out when it is ByLayer: `color`, an index with 0 for ByBlock, `trueColor` as `0xRRGGBB`, `linetype`, `lineweight` in hundredths of a diff --git a/docs/rules.md b/docs/rules.md index f5f0504..72f97c0 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -54,6 +54,13 @@ it would take `1e+100` for `1e+10` and report nothing. two corners of a rectangle of some width and height along the image's sides, or a polygon of 3 points that differ, at most 10,000 in all, and `invertClip` needs a clip. [Images](images.md#what-lint-refuses) has the rest. +- A hatch and a wipeout are R2018 only. A hatch has at least one loop, and each loop at least 3 + points, or 2 joined by an arc, with a bulge for each side where it has bulges. A wipeout has at + least 3 points, which do not lie on one line as written, and sides that do not cross. + `wipeoutFrame` is `true` or `false`. A paragraph's mask is `true`, `false` or + `{ color?, offsetFactor? }`, a color from 1 to 256 and a factor from 1 to 5, as a leader's is, + on a paragraph without columns, and a dimension style's `textMask` is `true`, `false` or `{ color }`. + [Fills, wipeouts and masks](fills.md) has the rest. - Arc angles are stored from 0 up to 360, so -90 becomes 270. An arc cannot come within 0.000001 degrees of a full turn, because its two angles would be written the same and the leading CAD app holds such an arc as having no length. Draw a diff --git a/examples/site-plan.ts b/examples/site-plan.ts index b0d0ae4..f0df955 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -291,17 +291,13 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee // North is up the block. Its base point is the middle of the circle. d.text([0, arrowRadius + gap], "N", { role: "heading", align: "center" }); d.circle([0, 0], arrowRadius); - d.line([0, -arrowRadius], [0, arrowRadius * 0.4]); - // The arrowhead is one polyline from the tip, where it has no width, to its base. + d.line([0, -arrowRadius], [0, arrowRadius * 0.2]); + // The arrowhead: its outline from the tip, notched at the shaft, and its east half filled. const head = arrowRadius * 0.9; - d.polyline( - [ - [0, arrowRadius], - [0, arrowRadius - head], - ], - false, - { widths: [[0, head / 3]] }, - ); + const tip: Point = [0, arrowRadius]; + const notch: Point = [0, arrowRadius - head * 0.8]; + d.polyline([tip, [-head / 3, arrowRadius - head], notch, [head / 3, arrowRadius - head]], true); + d.hatch([tip, notch, [head / 3, arrowRadius - head]]); }); // The view title: the title over a line and the scale under it. Its base point is the left // end of the line. The line has one fixed length, long enough for the sheet's view title, diff --git a/src/drawing.ts b/src/drawing.ts index deebdc2..476fb3e 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -57,6 +57,7 @@ import { } from "./papers.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; import { arcsAlong, cloud, donut, MAX_CLOUD_ARCS, rounded } from "./polylines.ts"; +import { onOneLine, polygonCrosses } from "./fills.ts"; import { imageVectors } from "./images.ts"; import { canonical } from "./json.ts"; import { DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; @@ -211,6 +212,13 @@ import { type LEADER_SHAFT_KINDS, type LEADER_SIDES, type LEADER_VERTICAL_ATTACHMENTS, + HATCH_LOOP_POINTS, + HATCH_NO_LOOPS, + textMaskProblem, + PARAGRAPH_MASK_COLUMNS, + WIPEOUT_CROSSES, + WIPEOUT_FLAT, + WIPEOUT_POINTS, } from "./rules.ts"; import type { Standard, @@ -497,6 +505,8 @@ export interface Paragraph extends EntityBase { readonly lineSpacingStyle?: LineSpacingStyle; /** Columns its lines flow through, each `width` wide. Missing, one column. */ readonly columns?: ParagraphColumns; + /** A mask behind it, over its box: as wide as its width, or its widest line where that is wider. */ + readonly mask?: TextMask; } /** @@ -666,11 +676,11 @@ export type LeaderBlockConnection = (typeof LEADER_BLOCK_CONNECTIONS)[number]; export type LeaderVerticalAttachment = (typeof LEADER_VERTICAL_ATTACHMENTS)[number]; /** - * A mask behind a leader's note, which hides what is drawn before the leader there: `true` for - * the drawing's background, or a color index of its own, over the note's box grown by - * `offsetFactor` times its text height less one, 1.5 unless given. + * A mask behind a text, which hides what is drawn before it there: `true` for the drawing's + * background, or a color index of its own, over the text's box grown by `offsetFactor` times its + * text height less one, from 1 to 5 and 1.5 unless given. */ -export type LeaderMask = boolean | { readonly color?: number; readonly offsetFactor?: number }; +export type TextMask = boolean | { readonly color?: number; readonly offsetFactor?: number }; /** * A leader: a note joined to what it names by one or more shafts. The leading CAD app holds it as @@ -715,7 +725,7 @@ export interface Leader extends Placed { /** True for a frame around the note. Defaults to its style's. */ readonly frame?: boolean; /** A mask behind the note. */ - readonly mask?: LeaderMask; + readonly mask?: TextMask; /** How its shafts run through their points. Defaults to its style's. */ readonly shaft?: LeaderShaftKind; /** @@ -771,6 +781,38 @@ export interface Image extends EntityBase { readonly transparent?: boolean; } +/** + * A closed outline of a hatch: from each point to the next and from the last back to the first, + * each side straight or an arc by its bulge, as a closed `Polyline`'s sides are. + */ +export interface HatchLoop { + readonly points: readonly Point[]; + /** The bulge of each side, one for each, as `Polyline.bulges`. Defaults to every side straight. */ + readonly bulges?: readonly number[]; +} + +/** + * A hatch: an area filled solid in its pen's color, which the leading CAD app holds as one entity + * a drafter edits and measures as one. The area inside an odd number of its loops is filled, so + * a loop inside another is a hole, and a loop inside a hole fills again. R2018 only. + */ +export interface Hatch extends EntityBase { + readonly kind: "hatch"; + /** Its loops, in any order and either way round. */ + readonly loops: readonly HatchLoop[]; +} + +/** + * A wipeout: a polygon filled with the paper's color, which hides what is drawn before it, such + * as the lines behind a note. Its frame, the polygon drawn in its pen, shows as + * `Drawing.wipeoutFrame` says. R2018 only. + */ +export interface Wipeout extends EntityBase { + readonly kind: "wipeout"; + /** Its corners, three or more, in order. It closes back to the first. */ + readonly points: readonly Point[]; +} + export type Entity = | Line | Polyline @@ -786,7 +828,9 @@ export type Entity = | JoggedRadiusDimension | AngularDimension | Leader - | Image; + | Image + | Hatch + | Wipeout; /** * A leader style: how the leaders that name it are drawn. Its sizes are the sizes its leaders @@ -944,6 +988,11 @@ export interface DimensionStyle { readonly anglePrecision?: number; /** The zeros an angle leaves out, as `suppressZeros` does for a length. */ readonly suppressAngleZeros?: "leading" | "trailing" | "both"; + /** + * A mask behind the text: `true` for the drawing's background, or a color index of its own, over + * the text's box grown by a quarter of its height. Defaults to none. + */ + readonly textMask?: boolean | { readonly color: number }; } /** @@ -1096,6 +1145,11 @@ export interface Drawing { * to true, as the leading CAD app has it. A sheet with a logo or an aerial wants false. */ readonly imageFrame?: boolean; + /** + * Whether each wipeout's frame shows and plots: its polygon, in its pen. Defaults to true, as + * the leading CAD app has it. A mask behind notes wants false. + */ + readonly wipeoutFrame?: boolean; } /** @@ -1574,6 +1628,12 @@ interface ParagraphPlacement { /** True for a frame around the note. Defaults to its style's. */ readonly frame?: boolean; /** A mask behind the note: `true` for the drawing's background, or `{ color, offsetFactor }`. */ - readonly mask?: LeaderMask; + readonly mask?: TextMask; /** How its shafts run through their points. Defaults to its style's. */ readonly shaft?: LeaderShaftKind; /** @@ -2890,6 +2955,83 @@ export class DrawingBuilder< }); } + /** + * A hatch, filled solid in the current layer's color: one outline's points, or a list of loops. + * The area inside an odd number of loops is filled, so a loop inside another is a hole and one + * inside a hole fills again, whichever way each runs. A loop's `bulges` make its sides arcs, as + * a polyline's do. R2018 only. + * + * ```ts + * d.hatch([ + * { points: [[0, 0], [8, 0], [8, 0.5], [0, 0.5]] }, + * { points: [[3, 0], [3.5, 0], [3.5, 0.5]] }, + * ]); + * ``` + */ + hatch< + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + >( + boundary: readonly Point[] | readonly HatchLoop[], + options: EntityOptions = {}, + ): this { + return this.#add(DrawingBuilder.prototype.hatch, options, () => { + if (this.dxf === "R12") refuse("hatch", R12_ONLY.hatches); + if (!Array.isArray(boundary)) + refuse("geometry", "A hatch's boundary is a list of points or of loops"); + const first: unknown = boundary[0]; + const outline = Array.isArray(first) || first === undefined; + const given = (outline ? [{ points: boundary }] : boundary) as readonly HatchLoop[]; + if (given.length === 0 || (outline && boundary.length === 0)) + refuse("geometry", capitalized(HATCH_NO_LOOPS)); + const loops = given.map((loop, k): HatchLoop => { + if (typeof loop !== "object" || loop === null || !Array.isArray(loop.points)) + return refuse("geometry", `Loop ${k} must be { points, bulges? }`); + const points = loop.points.map(pt); + const bulges = loop.bulges; + const problem = + polylineSidesProblems(points.length, bulges, undefined, undefined)[0] ?? + (points.length < 2 || + (points.length === 2 && !(bulges ?? []).some((b) => written(b) !== 0)) + ? HATCH_LOOP_POINTS + : undefined); + if (problem) refuse("geometry", `Loop ${k}: ${problem}`); + return { points, ...(bulges === undefined ? {} : { bulges: [...bulges] }) }; + }); + return { kind: "hatch", layer: this.#current, loops }; + }); + } + + /** + * A wipeout: a polygon filled with the paper's color, which hides what is drawn before it, such + * as the lines behind a note. Its frame shows as `Drawing.wipeoutFrame` says. R2018 only. + * + * ```ts + * d.wipeout([[2, 2], [5, 2], [5, 3], [2, 3]]); + * ``` + */ + wipeout< + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + >(points: readonly Point[], options: EntityOptions = {}): this { + return this.#add(DrawingBuilder.prototype.wipeout, options, () => { + if (this.dxf === "R12") refuse("wipeout", R12_ONLY.hatches); + if (!Array.isArray(points) || points.length < 3) + refuse("geometry", capitalized(WIPEOUT_POINTS)); + const corners = points.map(pt); + if (onOneLine(corners)) refuse("geometry", capitalized(WIPEOUT_FLAT)); + if (corners.length <= 4096 && polygonCrosses(corners)) + refuse("wipeout", capitalized(WIPEOUT_CROSSES)); + return { kind: "wipeout", layer: this.#current, points: corners }; + }); + } + /** * A raster image: the PNG or JPEG file at `path`, from the folder of this drawing's file, with * its lower-left corner at `at`, `width` drawing units wide. `pixels` are the file's own, which @@ -3212,6 +3354,14 @@ export class DrawingBuilder< ...(c.gutter !== undefined && { gutter: c.gutter }), } as ParagraphColumns; } + const mask: unknown = (o as { mask?: unknown }).mask; + if (mask !== undefined) { + const maskProblem = textMaskProblem(mask); + if (maskProblem) refuse("paragraph", maskProblem); + if (mask !== false && paragraph.columns !== undefined) + refuse("paragraph", capitalized(PARAGRAPH_MASK_COLUMNS)); + if (mask !== false) paragraph.mask = mask === true ? true : { ...(mask as object) }; + } return paragraph as Paragraph; } @@ -3651,7 +3801,7 @@ export class DrawingBuilder< if (block !== undefined) this.#arrowheadBlocks.add(block); const { prefix, suffix, suppressZeros, feetInchZeros } = definition; const { fraction, fractionScale, textPlacement, textFit } = definition; - const { dimensionLineweight, extensionLineweight, radialText, jogAngle } = definition; + const { dimensionLineweight, extensionLineweight, radialText, jogAngle, textMask } = definition; const { angleUnits, anglePrecision, suppressAngleZeros } = definition; const units = definition.units ?? "decimal"; const scale = definition.scale ?? 1; @@ -3684,6 +3834,9 @@ export class DrawingBuilder< ...(angleUnits === undefined || angleUnits === "degrees" ? {} : { angleUnits }), ...(anglePrecision === undefined || anglePrecision === 0 ? {} : { anglePrecision }), ...(suppressAngleZeros === undefined ? {} : { suppressAngleZeros }), + ...(textMask === undefined || textMask === false + ? {} + : { textMask: textMask === true ? true : { color: textMask.color } }), }); this.#dimensionStylesAudited.set(layerAuditKey(named), named); } @@ -4297,7 +4450,7 @@ export class DrawingBuilder< ...(o.gap === undefined ? {} : { gap: o.gap as number }), ...(o.width === undefined ? {} : { width: o.width as number }), ...(o.frame === undefined ? {} : { frame: o.frame as boolean }), - ...(o.mask === undefined ? {} : { mask: o.mask as LeaderMask }), + ...(o.mask === undefined ? {} : { mask: o.mask as TextMask }), ...(o.shaft === undefined ? {} : { shaft: o.shaft as LeaderShaftKind }), ...(far === undefined ? {} diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index fe4ec88..57653d8 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -52,6 +52,19 @@ import type { Viewport, } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; +import { + dimensionMask, + loopBulged, + maskOf, + type Mask, + variableDictionaryHandle, + WIPEOUT_APPLICATION, + wipeoutClip, + wipeoutCount, + wipeoutFrameVariableHandle, + wipeoutPicture, + wipeoutVariablesHandle, +} from "./fills.ts"; import { drawingImages, IMAGE_DICTIONARY, @@ -226,6 +239,21 @@ export function toDXFR2018( entity: true, }); } + const wipeouts = wipeoutCount(drawing); + if (wipeouts > 0) { + writeClass(g, "WIPEOUT", "AcDbWipeout", WIPEOUT_APPLICATION, 2175, { + count: wipeouts, + entity: true, + }); + writeClass(g, "WIPEOUTVARIABLES", "AcDbWipeoutVariables", WIPEOUT_APPLICATION, 0, { + count: 1, + entity: false, + }); + writeClass(g, "DICTIONARYVAR", "AcDbDictionaryVar", "ObjectDBX Classes", 0, { + count: 1, + entity: false, + }); + } // The leading CAD app draws nothing of an image whose class it holds no count of. if (images.length > 0) { const count = (n: number, entity = false) => ({ count: n, entity }); @@ -408,6 +436,7 @@ export function toDXFR2018( }), layer: entity.layer, textStyle: styleOf(style.textStyle)?.name ?? STANDARD_TEXT_STYLE, + mask: dimensionMask(style), }); }); }); @@ -712,6 +741,12 @@ export function toDXFR2018( } g(3, "ACAD_PLOTSTYLENAME"); g(350, plotStyleDictionary); + if (wipeouts > 0) { + g(3, "ACAD_WIPEOUT_VARS"); + g(350, wipeoutVariablesHandle()); + g(3, "AcDbVariableDictionary"); + g(350, variableDictionaryHandle()); + } g(0, "DICTIONARY"); ownedBy(g, groupDictionary, rootDictionary); g(100, "AcDbDictionary"); @@ -753,6 +788,7 @@ export function toDXFR2018( if (images.length > 0) { writeImageObjects(g, definitions, reactors, rootDictionary, drawing); } + if (wipeouts > 0) writeWipeoutObjects(g, rootDictionary, drawing); if (sheets.length > 0) { g(0, "DICTIONARY"); ownedBy(g, layoutDictionary, rootDictionary); @@ -828,6 +864,7 @@ export function toDXFR2018( dimensionStyles.length > 0 || leaderStyles.length > 0 || images.length > 0 || + wipeoutCount(drawing) > 0 || drawing.entities.some((entity) => entity.id !== undefined); h(5, named ? ID_HANDLE_SEED : handle()); h(0, "ENDSEC"); @@ -1141,6 +1178,7 @@ function writeEntity( } g(73, lineSpacingStyleCode(e)); g(44, e.lineSpacing ?? 1); + writeMask(g, maskOf(e.mask)); if (columns) { g(101, "Embedded Object"); g(70, attachment); @@ -1165,6 +1203,62 @@ function writeEntity( } return; } + case "hatch": { + begin("HATCH", "AcDbHatch"); + point(g, 10, 0, 0); + point3(g, 210, 0, 0, 1); + g(2, "SOLID"); + g(70, 1); // solid + g(71, 0); // no boundary objects + const loops = e.loops; + g(91, loops.length); + for (const loop of loops) { + const points = loop.points; + const bulged = loopBulged(loop); + g(92, 2); // a polyline + g(72, bulged ? 1 : 0); + g(73, 1); // closed + g(93, points.length); + points.forEach(([x, y], i) => { + g(10, x); + g(20, y); + if (bulged) g(42, loop.bulges?.[i] ?? 0); + }); + g(97, 0); + } + g(75, 0); // normal: the parity of the loops around a point + g(76, 1); // predefined + g(98, 1); + g(10, 0); + g(20, 0); + return; + } + case "wipeout": { + begin("WIPEOUT", "AcDbWipeout"); + g(90, 0); // the class's version + const { corner, side } = wipeoutPicture(e.points); + point(g, 10, ...corner); + point(g, 11, side, 0); + point(g, 12, 0, side); + g(13, 1); + g(23, 1); + g(340, "0"); // no definition + g(70, 7); // shown, shown when not square to the screen, clipped + g(280, 1); + g(281, 50); + g(282, 50); + g(283, 0); + g(290, 0); + g(360, "0"); + g(71, 2); // a polygon + const clip = wipeoutClip(e.points); + g(91, clip.length); + for (const [x, y] of clip) { + g(14, fifteenDigits(x)); + g(24, fifteenDigits(y)); + } + return; + } case "text": begin("TEXT", "AcDbText"); writeTextFields(g, e, style, undefined); @@ -1178,6 +1272,18 @@ function writeEntity( } } +/** + * A text's mask, after the line spacing of its MTEXT: on and in the drawing's background, or in a + * color index of its own, and the factor its box grows by. + */ +function writeMask(g: Group, mask: Mask | undefined): void { + if (mask === undefined) return; + g(90, mask.color === undefined ? 3 : 1); + g(63, mask.color ?? 256); + g(45, mask.offsetFactor); + g(441, 0); +} + /** What a dimension style's `suppressZeros` is in `DIMZIN`, group 78. */ const ZERO_SUPPRESSION_CODES = { leading: 4, trailing: 8, both: 12 } as const; @@ -1203,6 +1309,11 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) // DIMDLE: with a tick, the dimension line runs one arrow size past each extension line, // as the leading CAD app draws it whenever it turns the ticks outward. if (block !== undefined) g(46, style.arrowSize); + const mask = dimensionMask(style); + if (mask !== undefined) { + g(69, mask.color === undefined ? 1 : 2); // DIMTFILL: the background, or DIMTFILLCLR + if (mask.color !== undefined) g(70, mask.color); // DIMTFILLCLR + } g(73, 0); // DIMTIH: the text is along the dimension line g(74, 0); // DIMTOH g(77, style.textPlacement === "centered" ? 0 : 1); // DIMTAD: above the line, or in it @@ -1375,6 +1486,8 @@ interface Picture { /** The dimension's layer, which everything in the block is on. */ readonly layer: string; readonly textStyle: string; + /** The mask behind each of its texts, from its style. */ + readonly mask: Mask | undefined; } /** The most characters of a text DXF holds in one group. */ @@ -1386,7 +1499,7 @@ const TEXT_CHUNK = 250; * and lineweight of the dimension. It holds no definition points: they do not plot, and that app * works them out again when it draws the dimension anew. */ -function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Picture): void { +function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask }: Picture): void { const owner = handles.record; writeBlock(g, handles.begin, handles.end, name, owner, { paper: false, @@ -1471,6 +1584,7 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle }: Pi } g(73, 1); // line spacing at least as set g(44, 1); + writeMask(g, mask); }; text(picture.label, picture.textMiddle, handles.text, mtextOfLabel(picture.label.value)); if (picture.below) { @@ -1992,6 +2106,31 @@ function writeImageObjects( g(72, isUnits(drawing.units) ? RASTER_UNITS[drawing.units] : RASTER_UNITS.in); } +/** + * The objects of a drawing's wipeouts: WIPEOUTVARIABLES, and the variable `WIPEOUTFRAME` in the + * dictionary of the drawing's variables, which is what the leading CAD app reads of whether their + * frames show. + */ +function writeWipeoutObjects(g: Group, root: string, drawing: Drawing): void { + const frame = drawing.wipeoutFrame === false ? 0 : 1; + g(0, "WIPEOUTVARIABLES"); + ownedBy(g, wipeoutVariablesHandle(), root); + g(100, "AcDbWipeoutVariables"); + g(70, frame); + const variables = variableDictionaryHandle(); + g(0, "DICTIONARY"); + ownedBy(g, variables, root); + g(100, "AcDbDictionary"); + g(281, 1); + g(3, "WIPEOUTFRAME"); + g(350, wipeoutFrameVariableHandle()); + g(0, "DICTIONARYVAR"); + ownedBy(g, wipeoutFrameVariableHandle(), variables); + g(100, "DictionaryVariables"); + g(280, 0); + g(1, String(frame)); +} + /** A color the leading CAD app holds as ByLayer and as ByBlock, as a multileader and its style write one. */ const COLOR_BY_LAYER = -1073741824; const COLOR_BY_BLOCK = -1056964608; diff --git a/src/extents.ts b/src/extents.ts index 916c293..219b531 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -9,6 +9,7 @@ import { type Matrix, type Referenced, } from "./blocks.ts"; +import { dimensionMask, drawnLoops, loopOutline, maskOf, paragraphMaskCorners } from "./fills.ts"; import { imageCorners, imageDrawable, imageFrame } from "./images.ts"; import { dimensionArcPoints, @@ -38,6 +39,7 @@ import { measured, paragraphInStyle, paragraphMeasurer, + placer, } from "./paragraphs.ts"; import { filled } from "./shape.ts"; @@ -309,10 +311,26 @@ export function boxer( case "paragraph": { const style = e.style === undefined ? undefined : from.textStyles.get(key(e.style)); const paragraph = paragraphInStyle(e, style); - // A long value laid out again is paid for first; a box already kept is mapped alone. - const again = paragraphs.boxAgain(paragraph); + const mask = maskOf(e.mask); + if (mask === undefined) { + // A long value laid out again is paid for first; a box already kept is mapped alone. + const again = paragraphs.boxAgain(paragraph); + if (again > 0 && !spend(again)) break; + for (const [x, y] of paragraphs.box(paragraph) ?? []) add(x, y); + break; + } + // A mask reaches past the ink, and hides what is drawn before it there. Both boxes come + // from one layout, kept for a long value, whose mask's box is read once. + const again = paragraphs.again(paragraph); if (again > 0 && !spend(again)) break; - for (const [x, y] of paragraphs.box(paragraph) ?? []) add(x, y); + const layout = paragraphs.layout(paragraph); + if (layout.ink) { + const place = placer(paragraph); + const [x0, y0, x1, y1] = layout.ink; + for (const [x, y] of [place(x0, y0), place(x1, y0), place(x1, y1), place(x0, y1)]) + add(x, y); + } + for (const [x, y] of paragraphMaskCorners(e, layout, mask)) add(x, y); break; } case "linear-dimension": @@ -330,6 +348,20 @@ export function boxer( add(box[2], box[3]); break; } + case "hatch": { + const box = loopsBox(e.loops, e.layer); + if (box[0] === Infinity) break; + add(box[0], box[1]); + add(box[2], box[3]); + break; + } + case "wipeout": { + const box = pointsBox(e.points); + if (box[0] === Infinity) break; + add(box[0], box[1]); + add(box[2], box[3]); + break; + } case "image": { // The image, and the frame of a clip that reaches past it: a rectangle's four corners // along the image's sides, or a polygon's points. One the plots cannot draw has none. @@ -350,6 +382,22 @@ export function boxer( }; /** The box of a list of points, worked out once for a long list however many hold it. */ const pointBoxes = new WeakMap(); + /** The box of a hatch's list of loops, worked out once however many hatches hold the list. */ + const loopBoxes = new WeakMap(); + const loopsBox = (loops: unknown, layer: string): Bounds => { + const shared = typeof loops === "object" && loops !== null; + const known = shared ? loopBoxes.get(loops) : undefined; + if (known) return known; + const box = empty(); + for (const loop of drawnLoops(loops)) { + const found = curvedBox(loopOutline(loop, layer)) ?? pointsBox(loop.points); + if (found[0] === Infinity) continue; + include(box, found[0], found[1]); + include(box, found[2], found[3]); + } + if (shared) loopBoxes.set(loops, box); + return box; + }; /** Whether each clip an image gives can be drawn, read once however many images share it. */ const clipsChecked = new WeakMap(); const pointsBox = (points: readonly Point[]): Bounds => { @@ -425,9 +473,13 @@ export function boxer( for (const arc of picture.dimensionArcs) for (const p of dimensionArcPoints(arc)) add(p[0], p[1]); for (const arrowhead of picture.arrowheads) for (const corner of arrowhead) add(...corner); - // Each text by the box of what it draws, as its block's paragraph lays it out. + // Each text by the box of what it draws, as its block's paragraph lays it out, and by its + // mask where the style masks it. + const mask = dimensionMask(style); for (const text of pictureTexts(picture, font)) { - for (const corner of measured(text, layoutDimensionText(text)).corners ?? []) add(...corner); + const layout = layoutDimensionText(text); + for (const corner of measured(text, layout).corners ?? []) add(...corner); + if (mask) for (const corner of paragraphMaskCorners(text, layout, mask)) add(...corner); } }; /** diff --git a/src/fills.ts b/src/fills.ts new file mode 100644 index 0000000..63d245a --- /dev/null +++ b/src/fills.ts @@ -0,0 +1,258 @@ +// What a hatch, a wipeout and a text's mask draw, from the numbers as they are written: the one +// place the writers, `toSVG`, the extents and the readers take them from. +// +// The leading CAD app fills a hatch whose loops are all polylines and whose island style is normal +// by the parity of the loops around a point, whichever way each runs and in whatever order: so +// tsdraft writes every hatch that way. It holds a wipeout as a picture of one pixel, square, its +// lower-left corner the polygon's least X and Y and its side the larger of the polygon's width and +// height, clipped by the polygon in that pixel's axes, y down from its top. It plots a text's mask +// as the text's box grown by the mask's factor less one times its height, each side. +import type { Drawing, Entity, HatchLoop, Point, Polyline } from "./drawing.ts"; +import { written } from "./format.ts"; +import { keyHandle } from "./handles.ts"; +import { placer, type ParagraphLayout, type ParagraphToMeasure } from "./paragraphs.ts"; +import { polylineSides, type PolylineSide } from "./polylines.ts"; +import { filled } from "./shape.ts"; + +/** + * A hatch's loops that can be drawn: each an object up to the list's first empty slot. One of + * another shape, which `lint` refuses, draws nothing. + */ +export function drawnLoops(loops: unknown): HatchLoop[] { + const out: HatchLoop[] = []; + for (const loop of filled(loops)) { + if (typeof loop === "object" && loop !== null && !Array.isArray(loop)) + out.push(loop as HatchLoop); + } + return out; +} + +/** A loop as the closed polyline it is drawn as, which `polylineSides` and the extents read. */ +export function loopOutline(loop: HatchLoop, layer: string): Polyline { + return { + kind: "polyline", + layer, + points: loop.points, + closed: true, + ...(loop.bulges === undefined ? {} : { bulges: loop.bulges }), + }; +} + +/** The sides of a hatch's loop, as a closed polyline's. */ +export function loopSides(loop: HatchLoop): PolylineSide[] { + return polylineSides(loopOutline(loop, "")); +} + +/** True when a loop has a side with a bulge as written. */ +export function loopBulged(loop: HatchLoop): boolean { + const bulges: unknown = loop.bulges; + if (!Array.isArray(bulges)) return false; + for (let i = 0; i < bulges.length && i in bulges; i++) { + const b: unknown = bulges[i]; + if (typeof b === "number" && written(b) !== 0) return true; + } + return false; +} + +/** True when a polygon's points, as written, all lie on one line, so it closes around no area. */ +export function onOneLine(points: readonly Point[]): boolean { + const p = points.map(([x, y]): Point => [written(x), written(y)]); + const a = p[0]; + const b = p.find((q) => q[0] !== a?.[0] || q[1] !== a?.[1]); + if (a === undefined || b === undefined) return true; + return p.every((c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) === 0); +} + +/** + * True when two sides of a polygon cross or touch, other than where two sides meet at a corner, + * from its points as written: each side against each one not next to it. A point given twice in + * a row, or its first point again at its end, makes no side. + */ +export function polygonCrosses(points: readonly Point[]): boolean { + const p: Point[] = []; + for (const [x, y] of points) { + const q: Point = [written(x), written(y)]; + const last = p.at(-1); + if (last === undefined || last[0] !== q[0] || last[1] !== q[1]) p.push(q); + } + if (p.length > 1 && p[0]![0] === p.at(-1)![0] && p[0]![1] === p.at(-1)![1]) p.pop(); + const n = p.length; + const turn = (a: Point, b: Point, c: Point): number => + Math.sign((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])); + const within = (a: Point, b: Point, c: Point): boolean => + Math.min(a[0], b[0]) <= c[0] && + c[0] <= Math.max(a[0], b[0]) && + Math.min(a[1], b[1]) <= c[1] && + c[1] <= Math.max(a[1], b[1]); + for (let i = 0; i < n; i++) { + const [a, b] = [p[i]!, p[(i + 1) % n]!]; + for (let j = i + 2; j < n; j++) { + if (i === 0 && j === n - 1) continue; + const [c, d] = [p[j]!, p[(j + 1) % n]!]; + const [t1, t2, t3, t4] = [turn(a, b, c), turn(a, b, d), turn(c, d, a), turn(c, d, b)]; + if (t1 !== t2 && t3 !== t4 && t1 !== 0 && t2 !== 0 && t3 !== 0 && t4 !== 0) return true; + if ( + (t1 === 0 && within(a, b, c)) || + (t2 === 0 && within(a, b, d)) || + (t3 === 0 && within(c, d, a)) || + (t4 === 0 && within(c, d, b)) + ) + return true; + } + } + return false; +} + +/** A wipeout's picture of one pixel: its lower-left corner and its side, as written. */ +export interface WipeoutPicture { + readonly corner: Point; + readonly side: number; +} + +/** The picture a wipeout's points give, from the points as written. */ +export function wipeoutPicture(points: readonly Point[]): WipeoutPicture { + let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; + for (const [x, y] of filled(points) as readonly Point[]) { + const [wx, wy] = [written(x), written(y)]; + x0 = Math.min(x0, wx); + y0 = Math.min(y0, wy); + x1 = Math.max(x1, wx); + y1 = Math.max(y1, wy); + } + return { corner: [x0, y0], side: Math.max(x1 - x0, y1 - y0) }; +} + +/** + * A wipeout's polygon in its picture's axes, as the file holds it: x across from the left edge's + * middle and y down from the top's, each from -0.5 to 0.5, with its first point again at its end. + */ +export function wipeoutClip(points: readonly Point[]): Point[] { + const { corner, side } = wipeoutPicture(points); + const given = filled(points) as readonly Point[]; + return [...given, given[0]!].map(([x, y]): Point => [ + (written(x) - corner[0]) / side - 0.5, + 0.5 - (written(y) - corner[1]) / side, + ]); +} + +/** A mask as it is drawn: none for `false`, and for `true` or an object its color and factor. */ +export interface Mask { + /** A color index, or undefined for the drawing's background. */ + readonly color?: number; + readonly offsetFactor: number; +} + +/** A mask's factor of the text height unless given, as the leading CAD app sets one. */ +export const MASK_FACTOR = 1.5; + +/** The factor of a dimension's mask, which its style does not set. */ +export const DIMENSION_MASK_FACTOR = 1.25; + +/** + * A mask as it is drawn: none for `false`, and for `true` or an object the drawing's background or + * a color index, and its factor as written. A field the rules refuse is drawn as its default, and + * any other value as no mask. + */ +export function maskOf(mask: unknown): Mask | undefined { + if (mask === true) return { offsetFactor: MASK_FACTOR }; + if (typeof mask !== "object" || mask === null || Array.isArray(mask)) return undefined; + const { color, offsetFactor } = mask as Record; + const factor = + typeof offsetFactor === "number" && Number.isFinite(offsetFactor) + ? written(offsetFactor) + : MASK_FACTOR; + return { + ...(Number.isInteger(color) && (color as number) >= 1 && (color as number) <= 256 + ? { color: color as number } + : {}), + offsetFactor: factor, + }; +} + +/** The box of each layout's lines a mask covers, read once for a layout however often it is placed. */ +const reaches = new WeakMap(); + +/** A layout's frame, reaching to the start and the end of each line that passes it. */ +function maskReach(layout: ParagraphLayout): readonly [number, number, number, number] { + const known = reaches.get(layout); + if (known) return known; + let [left, bottom, right, top] = layout.frame; + for (const line of layout.lines) { + const first = line.runs[0]; + if (first === undefined) continue; + if (first.x < left) left = first.x; + if (line.end > right) right = line.end; + } + const reach = [left, bottom, right, top] as const; + reaches.set(layout, reach); + return reach; +} + +/** + * The box of a text's mask, `[left, bottom, right, top]` along its lines from its point: its box, + * reaching to the end of a line longer than its width, grown by its factor less one times + * `height` each side. + */ +export function maskBox( + layout: ParagraphLayout, + height: number, + mask: Mask, +): [number, number, number, number] { + const [left, bottom, right, top] = maskReach(layout); + const grow = (mask.offsetFactor - 1) * height; + return [left - grow, bottom - grow, right + grow, top + grow]; +} + +/** The corners of a paragraph's mask, its lower left first and counterclockwise. */ +export function paragraphMaskCorners( + paragraph: Pick, + layout: ParagraphLayout, + mask: Mask, +): Point[] { + const place = placer(paragraph); + const [l, b, r, t] = maskBox(layout, paragraph.height, mask); + return [place(l, b), place(r, b), place(r, t), place(l, t)]; +} + +/** How many wipeouts a drawing holds: in model space, on its layouts and in its blocks. */ +export function wipeoutCount(drawing: Drawing): number { + const lists: (readonly Entity[] | undefined)[] = [ + drawing.entities, + ...filled(drawing.layouts ?? []).map((layout) => layout.entities), + ...filled(drawing.blocks ?? []).map((block) => block.entities), + ]; + let count = 0; + for (const list of lists) for (const e of filled(list ?? [])) if (e.kind === "wipeout") count++; + return count; +} + +/** The mask of a dimension style's text, or undefined for none and for a value `lint` refuses. */ +export function dimensionMask( + style: { readonly textMask?: unknown } | undefined, +): Mask | undefined { + const mask: unknown = style?.textMask; + if (mask === true) return { offsetFactor: DIMENSION_MASK_FACTOR }; + if (typeof mask !== "object" || mask === null || Array.isArray(mask)) return undefined; + const { color } = mask as Record; + if (!Number.isInteger(color) || (color as number) < 1 || (color as number) > 256) + return undefined; + return { color: color as number, offsetFactor: DIMENSION_MASK_FACTOR }; +} + +/** The handle of WIPEOUTVARIABLES, which the dictionary `ACAD_WIPEOUT_VARS` names. */ +export function wipeoutVariablesHandle(): string { + return keyHandle("wipeout-variables:"); +} + +/** The handle of the dictionary of the drawing's variables, `AcDbVariableDictionary`. */ +export function variableDictionaryHandle(): string { + return keyHandle("dictionary:acdbvariabledictionary"); +} + +/** The handle of the variable `WIPEOUTFRAME` there, which says whether wipeouts' frames show. */ +export function wipeoutFrameVariableHandle(): string { + return keyHandle("dictionary-variable:wipeoutframe"); +} + +/** The application the classes of a wipeout and its variables name. */ +export const WIPEOUT_APPLICATION = "WipeOut"; diff --git a/src/index.ts b/src/index.ts index 8a9736e..ecb047a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -73,6 +73,8 @@ export { type DxfVersion, type Entity, type EntityOptions, + type Hatch, + type HatchLoop, type Image, type ImageOptions, type Insert, @@ -88,7 +90,6 @@ export { type Leader, type LeaderAttachment, type LeaderDirection, - type LeaderMask, type LeaderVerticalAttachment, type LeaderOptions, type LeaderSide, @@ -121,6 +122,7 @@ export { type StandardViewportOptions, type Text, type TextAlign, + type TextMask, type TextOptions, type TextStyle, type TextStyleChoice, @@ -131,6 +133,7 @@ export { type View, type Viewport, type ViewportOptions, + type Wipeout, type Xref, type Zone, } from "./drawing.ts"; @@ -158,6 +161,18 @@ export { type ImageClip, type ImageDefinition, } from "./images.ts"; +export { + dimensionMask, + loopBulged, + maskOf, + variableDictionaryHandle, + WIPEOUT_APPLICATION, + wipeoutClip, + wipeoutCount, + wipeoutFrameVariableHandle, + wipeoutPicture, + wipeoutVariablesHandle, +} from "./fills.ts"; export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; export { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; export { capHeightOf, FONTS, type Font, type FontInfo } from "./fonts.ts"; @@ -363,6 +378,8 @@ export { type ReadEntity, type ReadEntityBase, type ReadField, + type ReadHatch, + type ReadHatchLoop, type ReadHeader, type ReadImage, type ReadImageDefinition, @@ -372,6 +389,7 @@ export { type ReadLayout, type ReadLine, type ReadLinetype, + type ReadMask, type ReadMtext, type ReadMultileader, type ReadOptions, @@ -384,6 +402,7 @@ export { type ReadUnread, type ReadView, type ReadViewport, + type ReadWipeout, type ReadXref, } from "./read/model.ts"; export { toSVG, type SvgOptions } from "./svg.ts"; diff --git a/src/leaders.ts b/src/leaders.ts index 325181c..f9bfa8b 100644 --- a/src/leaders.ts +++ b/src/leaders.ts @@ -11,6 +11,7 @@ import { type LeaderArrowheadStroke, } from "./arrowheads.ts"; import { blockHandles } from "./blocks.ts"; +import { maskOf } from "./fills.ts"; import { arrowheadEntityHandle } from "./dimensions.ts"; import type { Block, @@ -453,8 +454,6 @@ const RADIANS = Math.PI / 180; const UNDERLINE = 0.2; /** How far below the top of the note the first line's underline runs, in text heights. */ const FIRST_UNDERLINE = 1.2; -/** A mask's factor of the text height unless given, as the leading CAD app sets one. */ -const MASK_FACTOR = 1.5; /** A block's own outline, as a block in place of a leader's note is placed by it. */ interface Outline { @@ -750,29 +749,6 @@ export function leaderVerticalAttachment( return leader.verticalAttachment ?? style.verticalAttachment ?? "center"; } -/** - * A leader's mask as it is drawn: none for `false`, and for `true` or an object the drawing's - * background or a color index, and its factor as written. A field the rules refuse is drawn as - * its default, and any other value as no mask. - */ -export function maskOf( - mask: unknown, -): { readonly color?: number; readonly offsetFactor: number } | undefined { - if (mask === true) return { offsetFactor: MASK_FACTOR }; - if (typeof mask !== "object" || mask === null || Array.isArray(mask)) return undefined; - const { color, offsetFactor } = mask as Record; - const factor = - typeof offsetFactor === "number" && Number.isFinite(offsetFactor) - ? written(offsetFactor) - : MASK_FACTOR; - return { - ...(Number.isInteger(color) && (color as number) >= 1 && (color as number) <= 256 - ? { color: color as number } - : {}), - offsetFactor: factor, - }; -} - /** * The block a leader holds in place of a note: its own, or its style's for a leader with no note * of its own, or undefined for a leader whose content is its note. diff --git a/src/lint.ts b/src/lint.ts index 78f9bec..7db14b5 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -174,7 +174,16 @@ import { xrefFieldProblem, xrefPathProblem, xrefTwinProblem, + HATCH_LOOP_POINTS, + HATCH_NO_LOOPS, + textMaskProblem, + PARAGRAPH_MASK_COLUMNS, + WIPEOUT_CROSSES, + WIPEOUT_FLAT, + WIPEOUT_FRAME, + WIPEOUT_POINTS, } from "./rules.ts"; +import { loopBulged, onOneLine, polygonCrosses } from "./fills.ts"; export type LintRule = | "format" @@ -218,6 +227,8 @@ export type LintRule = | "leader" | "paragraph" | "image" + | "hatch" + | "wipeout" | "zero-length" | "standard" | "layer-outside-standard" @@ -723,6 +734,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) item: "imageFrame", }); } + const wipeoutFrame: unknown = drawing.wipeoutFrame; + if (wipeoutFrame !== undefined && typeof wipeoutFrame !== "boolean") { + out.push({ rule: "wipeout", severity: "error", message: WIPEOUT_FRAME, item: "wipeoutFrame" }); + } // The leading CAD app compares linetype names as it compares layer names, and AUDIT reports a // twin of a built-in linetype as it reports any other. @@ -1595,16 +1610,30 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // again for each, and paid for. if ( isObject(entity) && - (entity.kind === "polyline" || entity.kind === "image" || entity.kind === "paragraph") + (entity.kind === "polyline" || + entity.kind === "image" || + entity.kind === "paragraph" || + entity.kind === "hatch" || + entity.kind === "wipeout") ) { let cost = 0; const columns: unknown = entity.kind === "paragraph" ? entity.columns : undefined; + const loops = entity.kind === "hatch" ? filled(entity.loops as unknown) : []; const lists = entity.kind === "image" ? [entity.clip] : entity.kind === "paragraph" ? [isObject(columns) ? columns.heights : undefined] - : [entity.points, entity.bulges, entity.widths]; + : entity.kind === "wipeout" + ? [entity.points] + : entity.kind === "hatch" + ? [ + entity.loops, + ...loops.flatMap((loop) => + isObject(loop) ? [loop.points, loop.bulges] : [], + ), + ] + : [entity.points, entity.bulges, entity.widths]; for (const list of lists) { if (Array.isArray(list) && list.length >= FREE && again(list)) cost += Math.floor(list.length / 8); @@ -1764,6 +1793,19 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } lintImage(entity, add, problems.length === 0, named, here); } + if (entity.kind === "hatch" || entity.kind === "wipeout") { + if (r12) { + add(entity.kind, "error", R12_ONLY.hatches); + return; + } + // Each side against each other one, paid for by the pairs past the first 4,096. + if (entity.kind === "wipeout" && entity.points.length > 3 && problems.length === 0) { + const n = entity.points.length; + const pairs = Math.floor((n * n) / 2); + if (pairs > 4096 && !spend(Math.floor(pairs / 64), here)) return; + if (polygonCrosses(entity.points)) add("wipeout", "error", WIPEOUT_CROSSES); + } + } if (isDimension(entity)) { lintDimension(entity, add, problems.length === 0, block !== undefined, here); // The block of its picture takes handles from its id, or else from its place. @@ -1847,6 +1889,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } const spacing = lineSpacing === undefined ? undefined : lineSpacingProblem(lineSpacing); if (spacing) add("paragraph", "error", spacing); + const mask = entity.mask === undefined ? undefined : textMaskProblem(entity.mask); + if (mask) add("paragraph", "error", mask); + else if (entity.mask !== undefined && entity.mask !== false && entity.columns !== undefined) + add("paragraph", "error", PARAGRAPH_MASK_COLUMNS); const styled = entity.style === undefined ? {} : { style: entity.style }; for (const [rule, found] of textProblems(styled)) add(rule, "error", found); } @@ -2400,6 +2446,49 @@ function geometryProblems(e: Entity): string[] { size("width", e.width); size("height", e.height); break; + case "hatch": { + if (e.loops.length === 0) out.push(HATCH_NO_LOOPS); + // One message of each kind for the hatch, with the first loop it is about. + const found = new Set(); + e.loops.forEach((loop, k) => { + const say = (problem: string) => { + if (found.has(problem)) return; + found.add(problem); + out.push(`loop ${k}: ${problem}`); + }; + const n = loop.points.length; + if (!loop.points.every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) { + say("its points must be finite numbers"); + return; + } + for (const [x, y] of loop.points) { + const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (problem) { + say(`its points: ${problem}`); + break; + } + } + if (n >= 2) + for (const problem of polylineSidesProblems(n, loop.bulges, undefined, undefined)) + say(problem); + if (n < 2 || (n === 2 && !loopBulged(loop))) say(HATCH_LOOP_POINTS); + }); + break; + } + case "wipeout": + if (e.points.length < 3) out.push(WIPEOUT_POINTS); + if (!e.points.every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) { + out.push("its points must be finite numbers"); + break; + } + for (const [x, y] of e.points) { + const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (!problem) continue; + out.push(`its points: ${problem}`); + return out; + } + if (e.points.length >= 3 && onOneLine(e.points)) out.push(WIPEOUT_FLAT); + break; } return out; } diff --git a/src/pdf.ts b/src/pdf.ts index f83508d..ee7f8d5 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -292,6 +292,7 @@ const ATTRIBUTES = new Set([ "href", "preserveAspectRatio", "clip-rule", + "fill-rule", ]); /** @@ -844,6 +845,7 @@ function pathPieces(d: string, where: string, scale: number): Piece[] { const tokens = d.trim().split(/[\s,]+/); const pieces: Piece[] = []; let at: [number, number] = [0, 0]; + let start: [number, number] = [0, 0]; let i = 0; const numbers = (count: number): number[] => { const out = tokens.slice(i, i + count).map(Number); @@ -856,7 +858,12 @@ function pathPieces(d: string, where: string, scale: number): Piece[] { if (command === "M" || command === "L") { const [x, y] = numbers(2) as [number, number]; at = [x, y]; + if (command === "M") start = at; pieces.push({ kind: command === "M" ? "move" : "line", to: at }); + } else if (command === "Z") { + // A hatch's loop closes back to where it started. + pieces.push({ kind: "close" }); + at = start; } else if (command === "A") { const [rx, ry, turn, large, sweep, x, y] = numbers(7) as number[]; const to: [number, number] = [x!, y!]; @@ -1191,7 +1198,12 @@ class PdfWriter { const paint = ( pieces: readonly Piece[], m: Matrix, - state: { stroke: string | undefined; fill: string | undefined; width: number }, + state: { + stroke: string | undefined; + fill: string | undefined; + width: number; + evenOdd?: boolean; + }, ): void => { if (state.stroke === undefined && state.fill === undefined) return; if (state.stroke !== undefined && state.stroke !== pen.stroke) { @@ -1218,7 +1230,10 @@ class PdfWriter { content.add(`${p(piece.c1)} ${p(piece.c2)} ${p(piece.to)} c`); } else content.add("h"); } - content.add(state.fill === undefined ? "S" : state.stroke === undefined ? "f" : "B"); + const rule = state.evenOdd ? "*" : ""; + content.add( + state.fill === undefined ? "S" : state.stroke === undefined ? `f${rule}` : `B${rule}`, + ); }; // Sticky, so each match starts where the last ended: what it cannot read is refused, never @@ -1497,7 +1512,15 @@ class PdfWriter { const fill = colorOf(inherited.fill, where(tag)); // The thinnest line, which `toSVG` marks, plots 0 wide: the thinnest the printer draws. const thinnest = element["data-thinnest"] !== undefined; - const state = { stroke, fill, width: thinnest ? 0 : width * scaleOf(inherited.matrix) }; + const state = { + stroke, + fill, + width: thinnest ? 0 : width * scaleOf(inherited.matrix), + evenOdd: element["fill-rule"] === "evenodd", + }; + if (element["fill-rule"] !== undefined && element["fill-rule"] !== "evenodd") { + throw refuse(`the fill rule ${JSON.stringify(element["fill-rule"])}`, where(tag)); + } mark(inherited.layer); let pieces: Piece[]; switch (tag) { diff --git a/src/read/check.ts b/src/read/check.ts index b28d9e2..e9625e8 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -161,6 +161,9 @@ const ENTITY: Readonly> = { ], named: "{ height, count?, gutter? } or { heights, gutter? }", }, + "mask?": { + fields: { "color?": "number", "trueColor?": "number", offsetFactor: "number" }, + }, }, dimension: { ...BASE, @@ -282,12 +285,27 @@ const ENTITY: Readonly> = { "contrast?": "number", "fade?": "number", }, + hatch: { + ...BASE, + kind: { oneOf: ["hatch"] }, + pattern: "string", + solid: "boolean", + style: { oneOf: ["normal", "outer", "ignore"] }, + "associative?": "boolean", + loops: { + list: { + fields: { points: { list: "point" }, "bulges?": { list: "number" }, flags: "number" }, + }, + }, + }, + wipeout: { ...BASE, kind: { oneOf: ["wipeout"] }, points: { list: "point" } }, }; const SPACE: Fields = { census: { fields: CENSUS }, "entities?": { list: "entity" }, "other?": counts, + "drawOrder?": strings, }; const DRAWING_READ: Fields = { @@ -307,6 +325,7 @@ const DRAWING_READ: Fields = { "dimscale?": "number", "dimstyle?": "string", "textstyle?": "string", + "wipeoutFrame?": "number", }, }, layers: { @@ -375,6 +394,8 @@ const DRAWING_READ: Fields = { "dimensionLineweight?": "number", "extensionLineweight?": "number", "arrowheadBlock?": "string", + "textFill?": "number", + "textFillColor?": "number", }, }, }, @@ -400,6 +421,7 @@ const DRAWING_READ: Fields = { }, }, entities: { list: "entity" }, + "drawOrder?": strings, other: counts, }, }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index ff95dcd..04501af 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -186,6 +186,7 @@ const BLOCK_READS = new Set([ "ATTRIB", "CIRCLE", "DIMENSION", + "HATCH", "IMAGE", "INSERT", "LARGE_RADIAL_DIMENSION", @@ -200,6 +201,7 @@ const BLOCK_READS = new Set([ "TEXT", "VERTEX", "VIEWPORT", + "WIPEOUT", ]); /** The kinds a space reads whole without `geometry`. */ const SPACE_READS = new Set([ @@ -215,6 +217,33 @@ const SPACE_READS = new Set([ "VIEWPORT", ]); +const HANDLE = /^[0-9A-Fa-f]{1,16}$/; + +/** Two handles' order as numbers: by their digits once leading zeros are left out. */ +function handleOrder(a: string, b: string): number { + const [x, y] = [a.replace(/^0+/, ""), b.replace(/^0+/, "")]; + return x.length - y.length || (x < y ? -1 : x > y ? 1 : 0); +} + +/** + * The handles of a space's entities in the order the leading CAD app draws them by its sort table: + * by each one's sort handle, or its own where the table gives none, and in the order of the file + * between two of one sort handle. + */ +function sortedOrder( + entities: readonly ReadEntity[], + table: ReadonlyMap, +): readonly string[] { + const keyed: { handle: string; sort: string; at: number }[] = []; + entities.forEach((e, at) => { + if (e.handle === undefined) return; + const own = e.handle.toUpperCase(); + keyed.push({ handle: e.handle, sort: table.get(own) ?? own, at }); + }); + keyed.sort((a, b) => handleOrder(a.sort, b.sort) || a.at - b.at); + return keyed.map((k) => k.handle); +} + /** Object kinds every file holds and that say nothing the read model keeps. */ const HOUSEKEEPING = new Set([ "ACDBDETAILVIEWSTYLE", @@ -512,6 +541,17 @@ class DxfReader { readonly #imageUses = new Map(); /** The handle of the dictionary of image definitions, from the root dictionary. */ #imageDictionary: string | undefined; + /** The dictionary of the drawing's variables, and the variable WIPEOUTFRAME's handle in it. */ + #variableDictionary: string | undefined; + #wipeoutFrameVariable: string | undefined; + /** The value of each DICTIONARYVAR read, by its handle, up to the census's limit. */ + readonly #variables = new Map(); + /** + * Each sort table, by the handle of the block record it orders, with each entity's sort + * handle, up to as many entries as the geometry's items. + */ + readonly #sortTables = new Map>(); + #sortEntries = 0; /** The dictionary's entries, in its order: each definition's name and handle. */ readonly #imageEntries: (readonly [name: string, handle: string])[] = []; /** Each image definition, by its handle. */ @@ -595,7 +635,12 @@ class DxfReader { case "TABLES": return ALL; case "OBJECTS": - return type === "DICTIONARY" || type === "FIELD" || type === "LAYOUT" || type === "IMAGEDEF" + return type === "DICTIONARY" || + type === "FIELD" || + type === "LAYOUT" || + type === "IMAGEDEF" || + type === "DICTIONARYVAR" || + type === "SORTENTSTABLE" ? ALL : NOTHING; case "BLOCKS": @@ -731,6 +776,15 @@ class DxfReader { if (textStyle !== undefined) style.textStyleHandle = textStyle; const arrowhead = handleAt(r, 342); if (arrowhead !== undefined) style.arrowheadHandle = arrowhead; + // DIMTFILL, and DIMTFILLCLR after it, a 70 of its own past the record's flags. + const fill = r.codes.indexOf(69); + if (fill >= 0) { + const n = Number(r.values[fill]); + if (Number.isFinite(n) && n !== 0) style.textFill = n; + const color = r.codes.indexOf(70, fill); + const index = color < 0 ? NaN : Number(r.values[color]); + if (n === 2 && Number.isFinite(index)) style.textFillColor = index; + } this.dimensionStyles.push(style as unknown as ReadDimensionStyle); return; } @@ -1221,6 +1275,9 @@ class DxfReader { entries[key] = value; } else if (key === "ACAD_MLEADERSTYLE") this.#leaderStyleDictionary ??= value; else if (key === "ACAD_IMAGE_DICT") this.#imageDictionary ??= value; + else if (key === "AcDbVariableDictionary") this.#variableDictionary ??= value; + else if (handle === this.#variableDictionary && key === "WIPEOUTFRAME") + this.#wipeoutFrameVariable ??= value; else if ( handle === this.#imageDictionary && key.length <= LONGEST_NAME && @@ -1236,6 +1293,42 @@ class DxfReader { } return; } + case "DICTIONARYVAR": { + const handle = handleAt(r, 5); + const value = first(inSubclass(r, "DictionaryVariables"), 1); + if (handle === undefined || value === undefined) return; + if (this.#variables.size < this.#limits.census) this.#variables.set(handle, value); + return; + } + case "SORTENTSTABLE": { + // The block record it orders, the 330 after its subclass. + const table = inSubclass(r, "AcDbSortentsTable"); + const at = table.codes.indexOf(330); + const named = at < 0 ? undefined : table.values[at]!.trim(); + const owner = named !== undefined && HANDLE.test(named) ? named.toUpperCase() : undefined; + // One no block record of the file holds is not read, and counted, as readDWG counts it. + if ( + owner === undefined || + !(this.blockRecords.has(owner) || this.blockRecords.has(named!)) + ) { + add(this.unread.objects, r.type); + return; + } + let entries = this.#sortTables.get(owner); + if (entries === undefined) { + if (this.#sortTables.size >= this.#limits.census) return; + this.#sortTables.set(owner, (entries = new Map())); + } + for (let i = 0; i + 1 < table.codes.length; i++) { + if (table.codes[i] !== 331 || table.codes[i + 1] !== 5) continue; + const [entity, sort] = [table.values[i]!.trim(), table.values[i + 1]!.trim()]; + if (!HANDLE.test(entity) || !HANDLE.test(sort)) continue; + if (this.#sortEntries >= this.#limits.geometryItems) break; + this.#sortEntries++; + entries.set(entity.toUpperCase(), sort.toUpperCase()); + } + return; + } case "IMAGEDEF": { const handle = handleAt(r, 5); if (handle === undefined || this.#imageDefinitions.size >= this.#limits.census) return; @@ -1310,6 +1403,11 @@ class DxfReader { } if (h.$DIMSTYLE !== undefined) header.dimstyle = unescaped(h.$DIMSTYLE); if (h.$TEXTSTYLE !== undefined) header.textstyle = unescaped(h.$TEXTSTYLE); + const frame = + this.#wipeoutFrameVariable === undefined + ? undefined + : Number(this.#variables.get(this.#wipeoutFrameVariable)); + if (frame !== undefined && Number.isInteger(frame)) header.wipeoutFrame = frame; const layerNames = new Map(); for (const layer of this.layers) { @@ -1354,6 +1452,31 @@ class DxfReader { ? "" : (this.blockRecords.get(draft.blockRecord) ?? "") ).toUpperCase(); + // The handle of each block's record by its name in capitals, and the order of what a space + // or a block draws, when the file holds a sort table for it. + const recordOf = new Map(); + for (const [handle, recordName] of this.blockRecords) { + if (recordName.length <= LONGEST_NAME && !recordOf.has(recordName.toUpperCase())) + recordOf.set(recordName.toUpperCase(), handle.toUpperCase()); + } + // A block's entities are read with geometry and without, and a space's with it alone. + const order = ( + entities: readonly ReadEntity[] | undefined, + recordName: string, + ): readonly string[] | undefined => { + if (entities === undefined) return undefined; + const record = recordOf.get(recordName.toUpperCase()); + const table = record === undefined ? undefined : this.#sortTables.get(record); + return table === undefined ? undefined : sortedOrder(entities, table); + }; + /** A space's draw order as a field of its read, which a read without geometry leaves out. */ + const ordered = ( + entities: readonly ReadEntity[] | undefined, + recordName: string, + ): { drawOrder?: readonly string[] } => { + const sorted = this.#geometry ? order(entities, recordName) : undefined; + return sorted === undefined ? {} : { drawOrder: sorted }; + }; const layouts: ReadLayout[] = []; for (const draft of this.layouts.toSorted((a, b) => a.tab - b.tab)) { const recordName = spaceOf(draft); @@ -1377,6 +1500,7 @@ class DxfReader { entities: space?.entities ?? [], other: space?.other ?? map(), }), + ...ordered(space?.entities, recordName), }); } // The first layout of each space, by the space's block in capitals. @@ -1500,7 +1624,8 @@ class DxfReader { dimensionStyles, blocks: this.blocks.map((draft): ReadBlock => { const { block: _, ...block } = draft; - return block; + const sorted = order(block.entities, block.name); + return sorted === undefined ? block : { ...block, drawOrder: sorted }; }), xrefs: this.xrefs, model: { @@ -1509,6 +1634,7 @@ class DxfReader { entities: model?.entities ?? [], other: model?.other ?? map(), }), + ...ordered(model?.entities, MODEL), }, layouts, fields, diff --git a/src/read/entities.ts b/src/read/entities.ts index ee48829..da31357 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -11,6 +11,7 @@ import type { ReadAngularDimension, ReadEntity, ReadEntityBase, + ReadHatchLoop, ReadImage, ReadMtext, ReadMultileader, @@ -234,6 +235,10 @@ export function readingOf( return leader(r, base, face); case "IMAGE": return image(r, base); + case "HATCH": + return hatch(r, base, face); + case "WIPEOUT": + return wipeout(r, base); case "SOLID": { if (face === 0) return { other: "SOLID in 3D" }; const corner = (code: number): Point => @@ -306,6 +311,148 @@ function image(r: Rec, base: ReadEntityBase): Reading { }; } +/** What a hatch's island style 75 reads as. */ +const HATCH_STYLES = ["normal", "outer", "ignore"] as const; + +/** The bulge of an arc that turns through `sweep` degrees, counterclockwise when above 0. */ +const bulgeOf = (sweep: number): number => Math.tan((sweep * Math.PI) / 720); + +/** + * A hatch: its pattern, its style and its loops, each a polyline, or a loop of lines and arcs + * read as one, as points and the bulge of each side. One with an ellipse or a spline in a loop, + * which `ReadHatchLoop` does not hold, is counted. + */ +function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { + if (face === 0) return { other: "HATCH in 3D" }; + const s = inSubclass(r, "AcDbHatch"); + const { codes, values } = s; + let i = codes.indexOf(91); + if (i < 0) return { malformed: "HATCH with no count of loops" }; + const value = (k: number) => Number(values[k]); + // The next group of a code from `i` on, read by the order of the loop's groups. + const take = (code: number): number | undefined => { + if (codes[i] !== code) return undefined; + return value(i++); + }; + const count = value(i++); + const loops: ReadHatchLoop[] = []; + const mirror = (p: Point): Point => placed(p, face); + for (let loop = 0; loop < count && i < codes.length; loop++) { + const flags = take(92); + if (flags === undefined) return { malformed: "HATCH whose loops do not follow its count" }; + const points: Point[] = []; + const bulges: number[] = []; + if ((flags & 2) !== 0) { + const bulged = take(72) === 1; + take(73); + const n = take(93) ?? 0; + for (let k = 0; k < n && codes[i] === 10; k++) { + const x = value(i++); + const y = take(20) ?? 0; + points.push(mirror([x, y])); + const bulge = bulged ? (take(42) ?? 0) : 0; + bulges.push(face === -1 ? -bulge : bulge); + } + } else { + const n = take(93) ?? 0; + for (let k = 0; k < n && codes[i] === 72; k++) { + const type = take(72); + if (type === 1) { + const [x0, y0] = [take(10) ?? 0, take(20) ?? 0]; + take(11); + take(21); + points.push(mirror([x0, y0])); + bulges.push(0); + } else if (type === 2) { + const [cx, cy] = [take(10) ?? 0, take(20) ?? 0]; + const radius = take(40) ?? 0; + const [start, end] = [take(50) ?? 0, take(51) ?? 0]; + const ccw = take(73) !== 0; + // A clockwise arc holds its angles as they turn clockwise: the world's are less 360. + const [a0, a1] = ccw ? [start, end] : [360 - start, 360 - end]; + let sweep = ccw ? a1 - a0 : -(a0 - a1); + if (ccw && sweep <= 0) sweep += 360; + if (!ccw && sweep >= 0) sweep -= 360; + const at = (angle: number): Point => + mirror([ + cx + radius * Math.cos((angle * Math.PI) / 180), + cy + radius * Math.sin((angle * Math.PI) / 180), + ]); + const sign = face === -1 ? -1 : 1; + // A whole circle is two halves, since one side cannot end where it starts. + if (Math.abs(sweep) >= 360 - 1e-9) { + points.push(at(a0), at(a0 + sweep / 2)); + bulges.push(sign * bulgeOf(sweep / 2), sign * bulgeOf(sweep / 2)); + } else { + points.push(at(a0)); + bulges.push(sign * bulgeOf(sweep)); + } + } else if (type === 3 || type === 4) { + return { other: "HATCH bounded by an ellipse or a spline" }; + } else return { malformed: "HATCH with an edge of no known kind" }; + } + } + // The handles of the entities it bounds, which the read model does not hold. + const objects = take(97) ?? 0; + for (let k = 0; k < objects && codes[i] === 330; k++) i++; + loops.push({ + points, + ...(bulges.some((b) => b !== 0) && { bulges: bulges.map((b) => b + 0) }), + flags, + }); + } + const style = HATCH_STYLES[num(s, 75) ?? 0] ?? "normal"; + return { + entity: { + ...base, + kind: "hatch", + pattern: name(s, 2) ?? "", + solid: num(s, 70) === 1, + style, + ...(num(s, 71) === 1 && { associative: true as const }), + loops, + }, + }; +} + +/** + * A wipeout: its clip, which the file holds in the axes of its picture of one pixel, in the + * world's coordinates, a polygon without its first point again at its end, or a rectangle's four + * corners. One whose vectors leave the plane is counted. + */ +function wipeout(r: Rec, base: ReadEntityBase): Reading { + const s = inSubclass(r, "AcDbWipeout"); + if ([31, 32, 30].some((code) => Math.abs(num(s, code) ?? 0) > 1e-9)) { + return { other: "WIPEOUT in 3D" }; + } + const held: Point[] = []; + for (let i = 0; i < s.codes.length; i++) { + if (s.codes[i] !== 14) continue; + const y = s.codes[i + 1] === 24 ? Number(s.values[i + 1]) : 0; + held.push([Number(s.values[i]), y]); + } + const [at, u, v] = [point(s, 10), point(s, 11), point(s, 12)]; + const rectangle = (num(s, 71) ?? 2) === 1; + let corners = held; + if (rectangle && held.length === 2) { + const [[x0, y0], [x1, y1]] = held as [Point, Point]; + corners = [ + [x0, y0], + [x1, y0], + [x1, y1], + [x0, y1], + ]; + } else if (held.length > 1) { + const [head, tail] = [held[0]!, held.at(-1)!]; + if (head[0] === tail[0] && head[1] === tail[1]) corners = held.slice(0, -1); + } + const points = corners.map(([x, y]): Point => { + const [a, b] = [x + 0.5, 0.5 - y]; + return [at[0] + a * u[0] + b * v[0], at[1] + a * u[1] + b * v[1]]; + }); + return { entity: { ...base, kind: "wipeout", points } }; +} + /** * Finishes an image the reader kept: its definition's path, and its clip from its pixels into * the world's coordinates. @@ -401,6 +548,19 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { dx !== undefined && dy !== undefined && (dx !== 0 || dy !== 0) ? degrees((Math.atan2(dy, dx) * 180) / Math.PI) : degrees(num(r, 50) ?? 0); + const flags = num(r, 90) ?? 0; + const color = num(r, 63); + const trueColor = num(r, 421); + // Bit 1 turns the mask on, and bit 2 fills it with the drawing's background. + const mask = + (flags & 1) === 0 + ? undefined + : { + // A true color stands for the color, whose index is only the nearest one. + ...((flags & 2) === 0 && trueColor === undefined && color !== undefined && { color }), + ...((flags & 2) === 0 && trueColor !== undefined && { trueColor }), + offsetFactor: num(r, 45) ?? 1.5, + }; const entity: ReadMtext = { ...base, kind: "mtext", @@ -413,6 +573,7 @@ function mtext(record: Rec, base: ReadEntityBase): Reading { value: textOnce(value), lineSpacing: num(r, 44) ?? 1, lineSpacingStyle: num(r, 73) === 2 ? "exactly" : "at-least", + ...(mask !== undefined && { mask }), }; // The embedded object's direction wins over the MTEXT's own, as the leading CAD app reads it. const embedded = embeddedDirection(record); @@ -833,5 +994,12 @@ export function costOf(e: ReadEntity): number { } case "image": return own + 4 + (e.clip?.length ?? 0) + chars(e.definition); + case "hatch": { + let points = 0; + for (const loop of e.loops) points += 1 + loop.points.length + (loop.bulges?.length ?? 0); + return own + points + chars(e.pattern); + } + case "wipeout": + return own + e.points.length; } } diff --git a/src/read/model.ts b/src/read/model.ts index b7b9fa6..1849ecf 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -99,6 +99,12 @@ export interface ReadHeader { readonly dimstyle?: string; /** `$TEXTSTYLE`, the current text style. */ readonly textstyle?: string; + /** + * The dictionary variable `WIPEOUTFRAME`, which the leading CAD app reads of whether wipeouts' + * frames show: 0 neither shown nor plotted, 1 both, 2 shown and not plotted. A file without it + * shows and plots them. + */ + readonly wipeoutFrame?: number; } /** A layer of the file's table, with its state as the file holds it. */ @@ -187,6 +193,10 @@ export interface ReadDimensionStyle { readonly extensionLineweight?: number; /** The block `DIMBLK` draws each arrowhead with, such as `_ArchTick`. Missing for closed filled. */ readonly arrowheadBlock?: string; + /** `DIMTFILL`: 0 no mask behind the text, 1 one in the drawing's background, 2 one in `textFillColor`. */ + readonly textFill?: number; + /** `DIMTFILLCLR`, the color index of the mask, for a `textFill` of 2. */ + readonly textFillColor?: number; } /** An attribute definition of a block, placed as a text is. */ @@ -357,6 +367,21 @@ export interface ReadMtext extends ReadEntityBase { * ones, and heights for dynamic ones of a height each, up to the first of 0. */ readonly columns?: ParagraphColumns; + /** + * The mask behind it, over its box grown by `offsetFactor` times its height less one: in the + * drawing's background where `color` and `trueColor` are left out, or in a color of its own. + */ + readonly mask?: ReadMask; +} + +/** A text's background mask, as an MTEXT holds it. */ +export interface ReadMask { + /** Group 63: a color index, when the mask is not in the drawing's background. */ + readonly color?: number; + /** Group 421: a true color as 0xRRGGBB, when it is not in the background. */ + readonly trueColor?: number; + /** Group 45. */ + readonly offsetFactor: number; } /** @@ -599,6 +624,46 @@ export interface ReadImage extends ReadEntityBase { readonly fade?: number; } +/** A loop of a hatch, as a closed polyline holds its points and the bulge of each side. */ +export interface ReadHatchLoop { + readonly points: readonly Point[]; + /** Left out when every side is straight. */ + readonly bulges?: readonly number[]; + /** + * Group 92, as the file holds it: 1 external, 2 a polyline, 4 derived from what it bounds, 8 a + * text's box, 16 outermost. + */ + readonly flags: number; +} + +/** + * A hatch: its loops, its pattern and how it takes islands. The leading CAD app fills one of style + * `normal` by the parity of all its loops around a point; one of style `outer` by the parity of + * its loops marked external or outermost alone, and one of style `ignore` by its external ones. + */ +export interface ReadHatch extends ReadEntityBase { + readonly kind: "hatch"; + /** Group 2, such as `SOLID` or `ANSI31`. */ + readonly pattern: string; + /** True for a solid fill, group 70. */ + readonly solid: boolean; + /** Group 75. */ + readonly style: "normal" | "outer" | "ignore"; + /** True when the file ties it to the entities it bounds, group 71. */ + readonly associative?: true; + /** + * Its loops, in the order of the file, each a polyline or a loop of lines and arcs read as one. + * A hatch with a loop of an ellipse or a spline is counted instead. + */ + readonly loops: readonly ReadHatchLoop[]; +} + +/** A wipeout: its polygon in the world's coordinates, without its first point again at its end. */ +export interface ReadWipeout extends ReadEntityBase { + readonly kind: "wipeout"; + readonly points: readonly Point[]; +} + /** What a space or a block draws, of the kinds the writers write. */ export type ReadEntity = | ReadLine @@ -614,7 +679,9 @@ export type ReadEntity = | ReadMultileader | ReadLeader | ReadSolid - | ReadImage; + | ReadImage + | ReadHatch + | ReadWipeout; export interface ReadBlock { /** The handle of the block's record, which an insert's block record points to. */ @@ -626,6 +693,8 @@ export interface ReadBlock { readonly attributeDefinitions: readonly ReadAttributeDefinition[]; /** What it draws of the kinds `ReadEntity` holds, in the order of the file. */ readonly entities: readonly ReadEntity[]; + /** The order the leading CAD app draws them in, as `ReadSpace.drawOrder` says. */ + readonly drawOrder?: readonly string[]; /** * What else it draws, counted by kind, such as `HATCH` or a polyline with an arc, and under * `past the limit` what it holds past `BLOCK_ITEMS`. @@ -706,6 +775,8 @@ export interface ReadLayout { readonly census: ReadCensus; /** With `geometry`, what it draws on its paper, as model space's are. Its viewports are above. */ readonly entities?: readonly ReadEntity[]; + /** With `geometry`, the order the leading CAD app draws them in, as `ReadSpace.drawOrder` says. */ + readonly drawOrder?: readonly string[]; readonly other?: Readonly>; } @@ -714,6 +785,12 @@ export interface ReadSpace { readonly census: ReadCensus; /** With `geometry`, what it draws, in the order of the file. */ readonly entities?: readonly ReadEntity[]; + /** + * With `geometry`, and when the file holds a sort table for the space, the handles of + * `entities` in the order the leading CAD app draws them: by each one's sort handle, its own + * handle where the table gives none. Without a table it draws them in the order of the file. + */ + readonly drawOrder?: readonly string[]; /** * With `geometry`, what it draws that `entities` leaves out, counted by kind: a kind it does not * read, such as `HATCH`, one in another plane, such as `CIRCLE in 3D`, and under `past the diff --git a/src/rules.ts b/src/rules.ts index 105345d..ba84d96 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -171,6 +171,8 @@ const R12_PARAGRAPHS = 'tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph'; const LINE_SPACING = "A paragraph's line spacing is a factor from 0.25 to 4"; const R12_IMAGES = 'tsdraft writes no images to R12 drawings. Use DXF version "R2018" for an image'; +const R12_HATCHES = + 'tsdraft writes no hatches or wipeouts to R12 drawings. Use DXF version "R2018" for a fill'; const IMAGE_PATH_EMPTY = "An image's path cannot be empty. The leading CAD app finds no file by it"; const IMAGE_PATH_ABSOLUTE = 'An image\'s path must start from the folder of the drawing\'s file, as "aerial.png" and "../images/aerial.png" do, and cannot start with /, \\ or a drive such as C:. The leading CAD app looks for the file of an absolute path in that folder alone, and on another machine finds none'; @@ -1588,8 +1590,46 @@ export const R12_ONLY = { polylines: R12_POLYLINES, paragraphs: R12_PARAGRAPHS, images: R12_IMAGES, + hatches: R12_HATCHES, } as const; +/** What is wrong with a hatch with no loop. */ +export const HATCH_NO_LOOPS = "a hatch needs at least one loop"; + +/** What is wrong with a loop of too few points. */ +export const HATCH_LOOP_POINTS = + "a loop needs at least 3 points, or 2 joined by an arc, so that it closes around an area"; + +/** What is wrong with a wipeout of too few points. */ +export const WIPEOUT_POINTS = "a wipeout needs at least 3 points"; + +/** What is wrong with a wipeout whose polygon has no area as written. */ +export const WIPEOUT_FLAT = + "a wipeout's points must not lie on one line once rounded to the 6 decimals tsdraft writes: the leading CAD app hides nothing behind it"; + +/** What is wrong with a wipeout whose sides cross. */ +export const WIPEOUT_CROSSES = + "a wipeout's sides must not cross each other: the leading CAD app hides nothing behind one that does. Give its corners in order around it"; + +/** What is wrong with a value of `wipeoutFrame`. */ +export const WIPEOUT_FRAME = "wipeoutFrame must be true or false"; + +/** What is wrong with a dimension style's mask. */ +export const DIMENSION_TEXT_MASK = + "textMask must be true, false, or { color }: a color index from 1 to 256, where 256 is the layer's"; + +/** Returns what is wrong with a dimension style's mask, or undefined. */ +export function dimensionTextMaskProblem(value: unknown): string | undefined { + if (typeof value === "boolean") return undefined; + if (typeof value !== "object" || value === null || Array.isArray(value)) + return DIMENSION_TEXT_MASK; + const m = value as Record; + for (const key of Object.keys(m)) if (key !== "color") return DIMENSION_TEXT_MASK; + return Number.isInteger(m.color) && (m.color as number) >= 1 && (m.color as number) <= 256 + ? undefined + : DIMENSION_TEXT_MASK; +} + /** What is wrong with a donut's hole, of `inside` across, or undefined. */ export function donutHoleProblem(inside: unknown): string | undefined { return notNegativeProblem(inside, DONUT_HOLE); @@ -3009,6 +3049,10 @@ export function dimensionStyleLookProblem(s: Record): string | const problem = s[field] === undefined ? undefined : problemOf(s[field]); if (problem) return problem; } + if (s.textMask !== undefined) { + const problem = dimensionTextMaskProblem(s.textMask); + if (problem) return problem; + } for (const field of ["dimensionLineweight", "extensionLineweight"] as const) { const value = s[field]; if (value === undefined) continue; @@ -3321,7 +3365,7 @@ const LEADER_SHAFT_KIND = 'shaft must be "straight" or "curved"'; const LEADER_FRAME = "frame must be true or false"; const LEADER_WIDTH = "width must be greater than 0. It is the width the note wraps at; leave it out for a note that does not wrap"; -const LEADER_MASK = +const TEXT_MASK = "mask must be true, false, or { color?, offsetFactor? }: a color index from 1 to 256, where 256 is the layer's, and a factor of the text height from 1 to 5"; /** What is wrong with a leader in a block. */ @@ -3465,18 +3509,21 @@ export function leaderShaftKindProblem(value: unknown): string | undefined { return (LEADER_SHAFT_KINDS as readonly unknown[]).includes(value) ? undefined : LEADER_SHAFT_KIND; } -/** Returns what is wrong with a leader's mask, or undefined. */ -export function leaderMaskProblem(value: unknown): string | undefined { +/** What is wrong with a mask on a paragraph in columns. */ +export const PARAGRAPH_MASK_COLUMNS = + "a paragraph in columns takes no mask yet: tsdraft would draw one mask across the columns and the gaps between them. Give the mask to a paragraph without columns"; + +/** Returns what is wrong with a mask behind a leader's note or a paragraph, or undefined. */ +export function textMaskProblem(value: unknown): string | undefined { if (typeof value === "boolean") return undefined; - if (typeof value !== "object" || value === null || Array.isArray(value)) return LEADER_MASK; + if (typeof value !== "object" || value === null || Array.isArray(value)) return TEXT_MASK; const m = value as Record; - for (const key of Object.keys(m)) - if (key !== "color" && key !== "offsetFactor") return LEADER_MASK; + for (const key of Object.keys(m)) if (key !== "color" && key !== "offsetFactor") return TEXT_MASK; if ( m.color !== undefined && !(Number.isInteger(m.color) && (m.color as number) >= 1 && (m.color as number) <= 256) ) { - return LEADER_MASK; + return TEXT_MASK; } if ( m.offsetFactor !== undefined && @@ -3486,7 +3533,7 @@ export function leaderMaskProblem(value: unknown): string | undefined { written(m.offsetFactor) <= 5 ) ) { - return LEADER_MASK; + return TEXT_MASK; } return undefined; } @@ -3738,7 +3785,7 @@ export function leaderOwnProblem(given: object, scale: number): string | undefin if (problem) return problem; } if (leader.mask !== undefined) { - const problem = leaderMaskProblem(leader.mask); + const problem = textMaskProblem(leader.mask); if (problem) return problem; } if (leader.width !== undefined) { diff --git a/src/shape.ts b/src/shape.ts index 1e25ac7..796b0c6 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -10,6 +10,8 @@ import type { DimensionStyle, Drawing, Entity, + Hatch, + HatchLoop, Image, Insert, Layer, @@ -28,6 +30,7 @@ import type { Text, TextStyle, Viewport, + Wipeout, Xref, } from "./drawing.ts"; import { shown, XREF_REFUSED_FIELDS, xrefFieldProblem } from "./rules.ts"; @@ -64,6 +67,8 @@ const KINDS = [ "aligned-dimension", "leader", "image", + "hatch", + "wipeout", ] as const satisfies readonly Entity["kind"][]; /** What is wrong with an entity whose kind tsdraft does not know. */ @@ -462,6 +467,7 @@ function shapes(all: boolean, typed = all): Shapes { }; const kind: Check = LEFT; + const loop = fields({ points: list(point) }, { bulges: list(number) }); const shared = { id: ruled(string), linetype: ruled(string), @@ -500,6 +506,8 @@ function shapes(all: boolean, typed = all): Shapes { ), ), ), + // true, false or an object: the rule reports any other. + mask: LEFT, }, ), insert: fields( @@ -597,6 +605,8 @@ function shapes(all: boolean, typed = all): Shapes { transparent: ruled(boolean), }, ), + hatch: fields({ kind, layer: string, loops: list(record(loop)) }, shared), + wipeout: fields({ kind, layer: string, points: list(point) }, shared), } satisfies Record; const entity: Check = (value, at, problems, extra) => { @@ -691,6 +701,8 @@ function shapes(all: boolean, typed = all): Shapes { angleUnits: ruled(string), anglePrecision: ruled(number), suppressAngleZeros: ruled(string), + // true, false or an object: the rule reports any other. + textMask: LEFT, }, ), ); @@ -781,6 +793,7 @@ function shapes(all: boolean, typed = all): Shapes { dimensionStyles: ruled(table(dimensionStyle)), leaderStyles: ruled(table(leaderStyle)), imageFrame: ruled(boolean), + wipeoutFrame: ruled(boolean), }, ); return { diff --git a/src/svg.ts b/src/svg.ts index 039ef1a..fbba36c 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -14,6 +14,7 @@ import { type DimensionStyle, type Drawing, type Entity, + type Hatch, type Image, type Insert, type Layer, @@ -26,7 +27,9 @@ import { type Text, type TextStyle, type Viewport, + type Wipeout, } from "./drawing.ts"; +import { dimensionMask, drawnLoops, loopSides, maskOf, paragraphMaskCorners } from "./fills.ts"; import { arcPoint, hasArcsOrWidths, @@ -718,6 +721,11 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ? imageElement(e, mark, drawnPen, look, from, matrix, room) : ""; } + if (e.kind === "hatch") return hatchToSvg(e, mark, drawnPen, matrix, room); + if (e.kind === "wipeout") { + const frame = (from?.drawing ?? drawing).wipeoutFrame !== false; + return wipeoutToSvg(e, mark, drawnPen, look, matrix, frame); + } if (!isDimension(e)) { return entityToSvg(e, mark, drawnPen, look, styleOf(e, from), matrix, room, sides); } @@ -1308,7 +1316,7 @@ function viewOf(view: SvgOptions["view"]): [number, number, number, number] | un type Drawn = Exclude; /** An entity that is one shape, with a linetype and a lineweight it may have of its own. */ -type Shape = Exclude; +type Shape = Exclude; /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ function styled(e: Drawn): Pick { @@ -1426,6 +1434,11 @@ function paragraphToSvg( }; const layout = left < 0 ? undefined : layOut(); const { widthFactor = 1, obliqueAngle = 0 } = layout ?? {}; + const mask = maskOf(e.mask); + if (mask && layout) { + const corners = paragraphMaskCorners(e, layout, mask).map(at); + add(maskToSvg(corners, mask.color, pen, look)); + } for (const line of layout?.lines ?? []) { if (left < 0) break; for (const run of line.runs) { @@ -1462,6 +1475,103 @@ function paragraphToSvg( return `${open}>\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; } +/** + * A mask: a polygon in the drawing's background, white and marked so, or in a color index of its + * own, or ByLayer for 256, with no outline. + */ +function maskToSvg( + corners: readonly Point[], + color: number | undefined, + pen: Pen, + look: Look, +): string { + const fill = color === undefined ? "#ffffff" : color === 256 ? pen.color : look.color(color); + // One in the drawing's background is marked, for a viewer whose background is not white. + const background = color === undefined ? ` data-mask="background"` : ""; + const points = corners.map(([x, y]) => `${fmt(x)},${fmt(y)}`).join(" "); + return ``; +} + +/** + * A hatch: its loops as one path, filled in its pen's color by the parity of the loops around each + * point, as the leading CAD app fills them, with no outline. Its arcs are drawn as `matrix` puts + * them, and it stops once it passes the room left in the picture. + */ +function hatchToSvg( + e: Hatch, + mark: string, + pen: Pen, + matrix: Matrix | undefined, + room: number, +): string { + const place = (x: number, y: number): string => { + const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; + return `${fmt(px)} ${fmt(py)}`; + }; + // Each loop is one string once made, and each side is paid for from the room, so that what the + // hatch holds stays near what it writes: the loop that passes the room ends there. The loops are + // added on, not joined, so that a path past the room is not copied before `write` refuses it. + let d = ""; + let left = room; + for (const loop of drawnLoops(e.loops)) { + if (left < 0) break; + const sides = loopSides(loop); + if (sides.length === 0) continue; + const parts = [`M ${place(...sides[0]!.from)}`]; + let used = parts[0]!.length; + for (const side of sides) { + if (used > left) break; + const arc = sideArc(side.from, side.to, side.bulge); + if (!arc) parts.push(`L ${place(...side.to)}`); + else { + const round = rounded(arc.radius, matrix); + const flag = arc.sweep > 0 ? round.sweep : 1 - round.sweep; + const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + // An arc of more than half a turn is drawn as two halves, so that no arc of the path ends + // where it starts, which SVG would draw as nothing. + if (Math.abs(arc.sweep) > Math.PI) { + parts.push(`${a} ${place(...arcPoint(arc, 0.5))}`); + used += parts.at(-1)!.length + 1; + } + parts.push(`${a} ${place(...side.to)}`); + } + used += parts.at(-1)!.length + 1; + } + parts.push("Z"); + const path = parts.join(" "); + d = d === "" ? path : d + " " + path; + left -= path.length + 1; + } + if (d === "") return ``; + return ``; +} + +/** + * A wipeout: its polygon in the paper's white, marked as a mask in the drawing's background, and + * its frame in its pen when the drawing shows wipeouts' frames. + */ +function wipeoutToSvg( + e: Wipeout, + mark: string, + pen: Pen, + look: Look, + matrix: Matrix | undefined, + frame: boolean, +): string { + const corners = filled(e.points).map((p) => (matrix ? mapPoint(matrix, p) : p)); + if (corners.length < 3) return ``; + const points = corners.map(([x, y]) => `${fmt(x)},${fmt(y)}`).join(" "); + const parts = [ + ``, + ]; + if (frame) { + parts.push( + ``, + ); + } + return `${parts.join("")}`; +} + /** * A dimension as a group: its extension lines, the pieces of its dimension line and the leader to * a text moved out, which take the dashes of its pen and the lineweights its style gives them, @@ -1496,6 +1606,15 @@ function dimensionToSvg( const extension = weighed(picture.lineweights.extension); const dimension = weighed(picture.lineweights.dimension); const thin = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke?.width === 0; + // A style's mask is drawn behind each text, as its picture's paragraph holds it. + const masked = dimensionMask(style); + const mask = + masked === undefined + ? undefined + : { + ...(masked.color === undefined ? {} : { color: masked.color }), + offsetFactor: masked.offsetFactor, + }; const parts = [ ...picture.extensionLines.map((ends) => line("extension-line", ends, extension)), ...picture.dimensionLines.map((ends) => line("dimension-line", ends, dimension)), @@ -1537,6 +1656,7 @@ function dimensionToSvg( rotation: text.rotation ?? 0, align: "center", valign: "middle", + ...(mask === undefined ? {} : { mask }), }, () => layoutDimensionText(text), `data-part="text"`, diff --git a/test/bounded.test.ts b/test/bounded.test.ts index d95ff2e..1b1fdb4 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -229,6 +229,12 @@ test("every walk stops at the first empty slot of a list", () => { { kind: "polyline", layer: "0", points: slots(), closed: true }, ], }, + { ...sheet, entities: [...sheet.entities, { kind: "hatch", layer: "0", loops: slots() }] }, + { + ...sheet, + entities: [...sheet.entities, { kind: "hatch", layer: "0", loops: [{ points: slots() }] }], + }, + { ...sheet, entities: [...sheet.entities, { kind: "wipeout", layer: "0", points: slots() }] }, { ...sheet, linetypes: [...sheet.linetypes!, { name: "HOLE", description: "", pattern: slots() }], @@ -2346,6 +2352,51 @@ test("polylines that share a long list of points, each with lists or a width of } }); +test("hatches that share their loops, and loops that share one list of points, are drawn in a bounded time", () => { + const points = Array.from({ length: 10_000 }, (_, k): Point => [ + 10 * Math.cos(k / 1591.5), + 10 * Math.sin(k / 1591.5), + ]); + const shared = Array.from({ length: 512 }, () => ({ + points: [ + [0, 0], + [1, 0], + [0, 1], + ] as Point[], + })); + for (const entities of [ + // One hatch whose loops all hold one long list: its picture is refused before it is held. + [{ kind: "hatch", layer: "0", loops: Array.from({ length: 20_000 }, () => ({ points })) }], + // Many hatches that hold one list of loops: its box is worked out once. + Array.from({ length: 512 }, () => ({ kind: "hatch", layer: "0", loops: shared })), + ] as Entity[][]) { + const drawing: Drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities, + }; + const found = settled(5000, () => svgWithin(drawing, {}, 50_000)); + assert.ok(typeof found === "string" || found instanceof RangeError, String(found)); + } +}); + +test("masked paragraphs that share a long value read its mask's box once", () => { + const value = Array.from({ length: 20_000 }, () => "I").join("\\P"); + const entities = Array.from({ length: 100_000 }, (_, k): Entity => ({ + kind: "paragraph", + layer: "0", + value, + at: [k, 0], + rotation: 0, + height: 1, + mask: true, + })); + const found = settled(2000, () => extents(entities)); + assert.ok(Array.isArray(found), String(found)); +}); + test("a paragraph of many lines, runs or braces, a long word and numbers past drawing stay bounded", () => { const paragraph = (fields: Record): Entity => ({ diff --git a/test/dimensions.test.ts b/test/dimensions.test.ts index 630aeb5..a2f3a70 100644 --- a/test/dimensions.test.ts +++ b/test/dimensions.test.ts @@ -1236,3 +1236,31 @@ test("an angular dimension is refused where the leading CAD app would draw what /anglePrecision must be a whole number from 0 to 8/, ); }); + +test("a style's text mask is kept by the builder, written, plotted and boxed", () => { + const masked = (textMask?: boolean | { color: number }) => { + const d = createDrawing({ units: "ft" }); + d.textStyle({ name: "NOTES", font: "Arial" }); + d.dimensionStyle({ ...sizes, name: "MASKED", ...(textMask === undefined ? {} : { textMask }) }); + d.linearDimension([0, 0], [100, 0], [50, 20], { style: "MASKED" }); + return d.build(); + }; + assert.deepEqual(masked(true).dimensionStyles?.[0]?.textMask, true); + assert.deepEqual(masked({ color: 3 }).dimensionStyles?.[0]?.textMask, { color: 3 }); + assert.equal(masked(false).dimensionStyles?.[0]?.textMask, undefined); + assert.match(toDXF(masked(true)), /\r\n *69\r\n *1\r\n/); + assert.match(toSVG(masked(true)), /data-part="mask"/); + assert.doesNotMatch(toSVG(masked()), /data-part="mask"/); + // The mask grows the text's box by a quarter of its height each side, past the dimension's top. + const top = (drawing: Drawing) => + extents( + drawing.entities, + drawing.textStyles, + [], + undefined, + undefined, + undefined, + drawing.dimensionStyles, + )[3]; + assert.ok(top(masked(true)) > top(masked()), `${top(masked(true))} ${top(masked())}`); +}); diff --git a/test/drawing.test.ts b/test/drawing.test.ts index c923e0e..8213a5f 100644 --- a/test/drawing.test.ts +++ b/test/drawing.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { createDrawing, sweep } from "../src/index.ts"; +import { createDrawing, lint, sweep, type Drawing } from "../src/index.ts"; +import { extents } from "../src/extents.ts"; test("layer() scopes entities and restores the previous layer", () => { const d = createDrawing().layer("A-WALL", { color: 1 }).build(); @@ -75,3 +76,39 @@ test("sweep() measures counterclockwise", () => { assert.equal(sweep(270, 90), 180); assert.equal(sweep(90, 0), 270); }); + +test("a paragraph's mask counts in its box, and a paragraph in columns takes none", () => { + const d = createDrawing({ units: "in" }); + assert.throws( + () => + d.paragraph("ONE\\NTWO", { + at: [0, 5], + width: 2, + height: 0.125, + columns: { count: 2, height: 1, gutter: 1 }, + mask: true, + }), + /in columns takes no mask/, + ); + d.paragraph("I", { at: [0, 0], height: 1, mask: { offsetFactor: 5 } }); + const [left, bottom] = extents(d.build().entities); + // The mask reaches 4 heights past the letter's box. + assert.ok(left < -3 && bottom < -3, `${left} ${bottom}`); + const columns = { + ...d.build(), + entities: [ + { + kind: "paragraph", + layer: "0", + value: "ONE", + at: [0, 0], + rotation: 0, + height: 0.125, + width: 2, + columns: { count: 2, height: 1 }, + mask: true, + }, + ], + } as unknown as Drawing; + assert.ok(lint(columns).some((found) => /in columns takes no mask/.test(found.message))); +}); diff --git a/test/format.test.ts b/test/format.test.ts index 85cde93..13dad38 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -39,7 +39,7 @@ function refusal(value: unknown): readonly Diagnostic[] { return assert.fail("fromJSON took the value"); } -const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader" or "image"`; +const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader", "image", "hatch" or "wipeout"`; test("a drawing goes to JSON and back unchanged", () => { const drawing = sample(); diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index bf99141..4812716 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -407,6 +407,10 @@ export function mutate(bytes: Uint8Array, next: () => number): Uint8Array { "DIMENSION", "MULTILEADER", "LEADER", + "HATCH", + "WIPEOUT", + "SORTENTSTABLE", + "DICTIONARYVAR", "SECTION", "ENDSEC", "BLOCK", diff --git a/test/read.test.ts b/test/read.test.ts index 7dcfb54..551eb95 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -232,7 +232,7 @@ function fieldsFile(): string { [1, "%<\\_FldIdx 0>%"], ], [ - [0, "HATCH"], + [0, "SPLINE"], [5, "A2"], [8, "NOTES"], ], @@ -297,13 +297,13 @@ test("readDXF keeps fields, the heights MTEXT sets, and counts what it does not const [text] = read.model.census.texts; assert.deepEqual(text?.inlineHeights, [0.2, 0.30000000000000004]); assert.deepEqual(plain(read.model.census.layers.NOTES), { - kinds: { MTEXT: 1, HATCH: 1, OLE2FRAME: 1 }, + kinds: { MTEXT: 1, SPLINE: 1, OLE2FRAME: 1 }, ownColor: 1, ownLinetype: 0, ownLineweight: 1, lineweights: { "35": 1 }, }); - assert.deepEqual(plain(read.unread.entities), { HATCH: 1, OLE2FRAME: 1 }); + assert.deepEqual(plain(read.unread.entities), { SPLINE: 1, OLE2FRAME: 1 }); assert.deepEqual(plain(read.unread.objects), { ACAD_PROXY_OBJECT: 1 }); // No text value of model space is kept. assert.ok(!JSON.stringify(read).includes("big")); diff --git a/test/shape.test.ts b/test/shape.test.ts index 3162b03..0e4c939 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -100,6 +100,8 @@ const kinds: { lineSpacing: 1.5, lineSpacingStyle: "exactly", columns: { height: 4, count: 2, gutter: 0.5 }, + // A paragraph in columns takes no mask; a leader's note has one of every field. + mask: false, id: "k", ...styled, }, @@ -183,6 +185,33 @@ const kinds: { id: "m", ...styled, }, + hatch: { + kind: "hatch", + layer: "0", + loops: [ + { + points: [ + [70, 0], + [80, 0], + [80, 10], + ], + bulges: [0, 0.5, 0], + }, + ], + id: "w1", + ...styled, + }, + wipeout: { + kind: "wipeout", + layer: "0", + points: [ + [90, 0], + [95, 0], + [92, 4], + ], + id: "w2", + ...styled, + }, "radius-dimension": { kind: "radius-dimension", layer: "0", @@ -298,6 +327,7 @@ const full: Required & { dxf: "R2018", linetypeScale: 2, imageFrame: false, + wipeoutFrame: false, linetypes: [{ name: "DD", description: "Dash dot", pattern: [0.5, -0.25, 0, -0.25] }], textStyles: [{ name: "NOTES", font: "Arial", widthFactor: 0.9, obliqueAngle: 10 }], dimensionStyles: [ @@ -326,6 +356,7 @@ const full: Required & { angleUnits: "degrees-minutes-seconds", anglePrecision: 4, suppressAngleZeros: "leading", + textMask: { color: 3 }, }, { name: "ARCH", @@ -354,6 +385,7 @@ const full: Required & { angleUnits: "degrees", anglePrecision: 0, suppressAngleZeros: "both", + textMask: true, }, ], leaderStyles: [ @@ -641,7 +673,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #15: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #17: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ From f4aca1f95253c635a7d6d40d13c74ec7815a019d Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 12:18:08 -0500 Subject: [PATCH 13/35] Paragraph text lays out the codes that change the characters after them Paragraph text lays out the codes that change the characters after them, as the leading CAD app does. - A paragraph's value may hold `\H` for a height, in drawing units or with `x` times the height before it; `\W` for a width factor and `\Q` for an oblique angle from -85 to 85, each in the place of the style's; `\A0;`, `\A1;` and `\A2;` for characters on the baseline, centered on the line's tallest run, or at its top; and `\C` for a color by its index, 0 to 257. - `layoutParagraph` lays each run out at its own height, width factor and lean: a line's spacing grows with its tallest run, a run after a leaned run starts further by its lean, and a line that holds spaces or a tab in a format of their own is placed by its first point. Each run of a line gives its `widthFactor`, `obliqueAngle` and `color`, and the preview and `toPDF` draw each run in them. `RunFormat` gains `height`, `widthFactor`, `obliqueAngle` and `color`. - `lint`, the builder and a literal value's type refuse a number a code does not take, with one grammar for each, and name it. `\T`, the spacing of the characters, `\c`, a true color, and `\O`, an overline, are still refused as not laid out. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 10 ++ GUIDE.md | 8 +- docs/paragraphs.md | 29 +++- docs/rules.md | 13 +- src/paragraph-codes.ts | 106 +++++++++--- src/paragraphs.ts | 346 ++++++++++++++++++++++++++++++++++------ src/rules.ts | 125 +++++++++++++-- src/svg.ts | 18 ++- test/bounded.test.ts | 4 + test/paragraphs.test.ts | 113 ++++++++++++- test/rules.test.ts | 17 +- 11 files changed, 671 insertions(+), 118 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c524604..a0f0ae9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,16 @@ block in place of its note with its attributes; and the old `LEADER`, as the read model's `leader`. +- Paragraph text lays out the codes that change the characters after them, as the leading CAD + app does: `\H` a height in drawing units or, with `x`, times the last; `\W` a width factor and + `\Q` an oblique angle, each in the place of the style's; `\A` the characters on the baseline, + centered on the line's tallest run, or at its top; and `\C` a color by its index, which moves + nothing. A line's spacing grows with its tallest run. `lint`, the builder and a literal value's + type refuse a number a code does not take, with one grammar for each. Each run of a laid-out + line gives its `widthFactor`, `obliqueAngle` and `color`, which the preview draws it in, and + `RunFormat` gains `height`, `widthFactor`, `obliqueAngle` and `color`. `\T`, the spacing of the + characters, `\c`, a true color, and `\O`, an overline, are still refused. + - Raster images, in R2018 drawings: `d.image(path, at, { pixels, width })` draws a PNG or a JPEG with its lower-left corner at `at`, `width` drawing units wide, and `height`, `rotation`, `clip`, `invertClip` and `transparent` where given; its height defaults to the file's diff --git a/GUIDE.md b/GUIDE.md index 5777a45..7917810 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -256,8 +256,9 @@ tab stops, justification and spacing. `columns: { count: 2, height: 6 }` flows t columns side by side, each `width` wide. `measureParagraph` gives its lines and its box, from the widths `measureText` uses, and `inspectText` checks each line as a text. `underline`, `bold`, `stack`, `superscript` and `subscript` write the codes for what they name, and `plain(text)` -escapes text from elsewhere. `lint` refuses a code tsdraft does not lay out, such as a change of -height, and names it. +escapes text from elsewhere. The codes `\H`, `\W`, `\Q`, `\A` and `\C` change the height, width, +slant, place and color of the characters after them, and `lint` refuses a code tsdraft does not +lay out, such as `\T`, and names it. [docs/paragraphs.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/paragraphs.md) has the codes. @@ -627,8 +628,7 @@ writeFileSync("plan.dxf", toDXF(drawing)); viewport is a locked rectangle that shows every layer at one scale. - A paper outside the list in the section on layouts, a paper in portrait, and a page setup for another plotter. -- The codes that change the height, width, slant, spacing or color of characters inside a - paragraph. +- The spacing of characters inside a paragraph, `\T`, and an overline, `\O`. - Ellipses and splines. - A color on a single entity. Color comes from the layer. - DWG files. tsdraft writes DXF. diff --git a/docs/paragraphs.md b/docs/paragraphs.md index af2bf81..26c6728 100644 --- a/docs/paragraphs.md +++ b/docs/paragraphs.md @@ -78,6 +78,11 @@ these: | `{` and `}` | A group: what a code sets inside it ends at its `}`, 16 groups deep at most | | `\L` and `\l` | Underline on and off | | `\K` and `\k` | Strike-through on and off | +| `\H0.2;`, `\H2x;` | The height of the characters after it, in drawing units or times the last | +| `\W0.8;` | Their width factor, in the place of the style's | +| `\Q15;` | Their oblique angle in degrees, -85 to 85, in the place of the style's | +| `\A0;` to `\A2;` | Where they sit on the line: on the baseline, centered or at the top | +| `\C1;` | A color by its index, which moves nothing and which the preview draws | | `\fArial\|b1;` | A TrueType font of `FONTS`, in bold with `b1`: `i0`, `c` and `p` pass | | `\Fromans.shx;` | An SHX font of `FONTS` | | `\S1/2;` | A fraction stacked over a level bar | @@ -176,11 +181,15 @@ message names the code. - In `\p`, an option it does not know, a tab stop that aligns text by its right, its center or a decimal point, `tr`, `tc` and `td`, and spacing at least a size, `sa`, which tsdraft does not lay out. -- The codes tsdraft does not lay out yet: `\H` the height, `\W` the width - factor, `\Q` the oblique angle, `\T` the spacing and `\A` the alignment of the characters after - it; `\C` and `\c` color; `\O`, an overline, which sits at a TrueType font's ascent, which - tsdraft's tables do not hold; `\X`, which only a dimension's text holds; and `\M+NXXXX`, a - character of a code page. A paragraph that held one would plot otherwise than tsdraft draws it. +- A code of the table above whose number is not one it takes: a height or width factor of 0 or + of more than 15 digits before its point, an oblique angle past 85, `\A` other than 0, 1 or 2, a + color number past 257. +- The codes tsdraft does not lay out yet: `\T` the spacing of the characters after it, which the + leading CAD app plots as a spacing of its own between characters; `\c`, a true color, which + the preview cannot draw as the plot does yet; `\O`, an overline, which sits + at a TrueType font's ascent, which tsdraft's tables do not hold; `\X`, which only a dimension's + text holds; and `\M+NXXXX`, a character of a code page. A paragraph that held one would plot + otherwise than tsdraft draws it. - A stacked part that holds other characters than those above, such as `\Sx/y;`, since where it stands depends on the top of its letters, which tsdraft's tables hold only for digits and capitals; and a stack in underlined or struck-through characters, which is laid out otherwise. @@ -252,6 +261,13 @@ from the widths and the ink of each character that `FONT_METRICS` holds: alike, every line, and stands centered without a width. A grown line draws each word and space, or each letter, as a run of its own. A line wider than its room is not grown, and a distributed one is centered. +- A run of the codes above is laid out at its own height, width factor and oblique angle: its + advances scale with them, and a line's A is its tallest run's top, and its D a third of that + run's height, with the third of the paragraph's height after it. `\A1;` centers the runs after + it on the line's tallest run, and `\A2;` sets them at its top. A run after a leaned one starts + further by how far the lean takes the last capital's top. A line that holds spaces or a tab in + a format of their own, or ends in one of another format than the spaces dropped after it, is + placed by its first point and not by its ink. - In columns, a line starts the next column when its box reaches below its column's height: its ink with `"at-least"` spacing, `h/3` below its baseline with `"exactly"`, and the box of the paragraph's own spacing. It stands at the column's top as a first line does, and the next column @@ -322,7 +338,6 @@ when the font is not the style's own or the value holds a code tsdraft does not ## Not yet -The codes that change the height, width, slant, spacing, alignment or color of the characters -after them, an overline, stacked parts in lower case, tab stops that align text by its right, its +The spacing of the characters, `\T`, an overline, stacked parts in lower case, tab stops that align text by its right, its center or a decimal point, columns that flow from right to left, and attributes of more than one line. diff --git a/docs/rules.md b/docs/rules.md index 72f97c0..369e1f5 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -40,12 +40,13 @@ it would take `1e+100` for `1e+10` and report nothing. written, its line spacing is a factor from 0.25 to 4 as written, and its value holds only the codes tsdraft lays out: its braces close, each code is one tsdraft knows and ends with its `;` where it takes one, a font is one of `FONTS`, in bold only for a TrueType font and never in - italic, and braces nest at most 16 deep. The codes of the height, width, slant, spacing, - alignment and color of characters, and an overline, are refused until tsdraft lays them out, - since a paragraph that held one would plot otherwise than tsdraft draws it. Its columns are a - count and a height, a height, or heights, with a width to be as wide as, and a `\N` without - them is a warning. So are a stacked part of other characters than digits and capitals with `.`, `,`, `+` or - `-`, or spaces, and a stack in underlined or struck-through characters. + italic, and braces nest at most 16 deep. The codes of the height, width, slant, place and color of + characters take the numbers the leading CAD app does, and the spacing of characters and an + overline are refused until tsdraft lays them out, since a paragraph that held one would plot + otherwise than tsdraft draws it. So are a stacked part of other characters than digits and + capitals with `.`, `,`, `+` or `-`, or spaces, and a stack in underlined or struck-through + characters. Its columns are a count and a height, a height, or heights, with a width to be as wide + as, and a `\N` without them is a warning. [Paragraphs](paragraphs.md#what-lint-refuses) has the rest. - An image is R2018 only. Its path is not empty, starts from the folder of the drawing's file and holds no `* ? < > | : "`, since the leading CAD app finds the file of an absolute path only diff --git a/src/paragraph-codes.ts b/src/paragraph-codes.ts index 25f57fd..9d3c81d 100644 --- a/src/paragraph-codes.ts +++ b/src/paragraph-codes.ts @@ -32,12 +32,7 @@ export const PARAGRAPH_STACK_PART = /** What each code a paragraph may hold but tsdraft does not lay out yet does. */ export const PARAGRAPH_NOT_LAID_OUT = { - H: "sets the height of the characters after it", - W: "sets the width factor of the characters after it", - Q: "sets the oblique angle of the characters after it", T: "sets the spacing of the characters after it", - A: "sets where the characters after it sit up and down the line", - C: "sets the color of the characters after it", c: "sets the true color of the characters after it", X: "starts the part of a dimension's text below its line", M: "holds a character of a code page", @@ -124,10 +119,21 @@ export interface RunFormat { readonly bold: boolean; /** The font of `FONTS` a `\f` or `\F` code set, or undefined for the paragraph's own. */ readonly font: Font | undefined; - /** The height as a share of the paragraph's, which `\H` sets in a dimension's text. */ + /** The height as a share of the paragraph's, which `\H` with an `x` sets. */ readonly size: number; - /** Where a stack sits up and down the line, which `\A` sets in a dimension's text: 0 on it, 1 centered. */ + /** + * The height in drawing units a `\H` without an `x` set, times what each `\H` with one after it + * gives, or undefined where none did, for the paragraph's times `size`. + */ + readonly height: number | undefined; + /** The width factor `\W` sets, or undefined for the style's. */ + readonly widthFactor: number | undefined; + /** The oblique angle in degrees `\Q` sets, or undefined for the style's. */ + readonly obliqueAngle: number | undefined; + /** Where the characters and stacks sit up and down the line, `\A`: 0 on it, 1 centered, 2 at its top. */ readonly align: 0 | 1 | 2; + /** The color by its index, 0 to 257, that a `\C` code sets, or undefined for the entity's. */ + readonly color: number | undefined; } /** How a paragraph's lines stand across its box, as a `\pq` code sets it. */ @@ -208,7 +214,11 @@ const PLAIN: RunFormat = { bold: false, font: undefined, size: 1, + height: undefined, + widthFactor: undefined, + obliqueAngle: undefined, align: 0, + color: undefined, }; /** @@ -237,6 +247,59 @@ const TOGGLES: Readonly> = { /** The codes tsdraft does not lay out that end with a `;`. */ const ENDED = new Set(["H", "W", "Q", "T", "A", "C", "c"]); +/** + * The argument each code before a `;` takes, as its type in `src/rules.ts` reads it: a number of + * at most 15 digits before its point and 64 after it, above 0, for `\H`, which may end in `x`, + * and `\W`; an angle from -85 to 85 for `\Q`; 0, 1 or 2 for `\A`; and 0 to 257 for `\C`. + */ +const ARGUMENTS: Readonly> = { + H: /^\d{1,15}(?:\.\d{1,64})?x?$/, + W: /^\d{1,15}(?:\.\d{1,64})?$/, + Q: /^-?(?:(?:\d|[1-7]\d|8[0-4])(?:\.\d{1,64})?|85(?:\.0{1,64})?)$/, + A: /^[012]$/, + C: /^(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-7])$/, +}; + +/** + * What each code before a `;` sets of the characters after it, from an argument it takes. `\C` + * sets a color, which moves nothing but starts a run. A height or width factor of 0 is no argument. + */ +const CODE_SETS: Readonly< + Record RunFormat | undefined> +> = { + H: (argument, format) => { + const times = argument.endsWith("x"); + const n = Number(times ? argument.slice(0, -1) : argument); + if (!(n > 0)) return undefined; + if (!times) return { ...format, height: n, size: 1 }; + return format.height === undefined + ? { ...format, size: format.size * n } + : { ...format, height: format.height * n }; + }, + W: (argument, format) => + Number(argument) > 0 ? { ...format, widthFactor: Number(argument) } : undefined, + Q: (argument, format) => ({ ...format, obliqueAngle: Number(argument) }), + A: (argument, format) => ({ ...format, align: Number(argument) as 0 | 1 | 2 }), + C: (argument, format) => ({ ...format, color: Number(argument) }), +}; + +/** The codes before a `;` that take an argument, and what each takes. */ +export const PARAGRAPH_CODE_ARGUMENTS = { + H: "a height above 0, in drawing units, or with an x after it a factor of the height before it", + W: "a width factor above 0", + Q: "an oblique angle in degrees, from -85 to 85", + A: "0, 1 or 2: on the baseline, centered or at the top", + C: "a color number from 0 to 257", +} as const; + +export type ArgumentCode = keyof typeof PARAGRAPH_CODE_ARGUMENTS; + +export function paragraphCodeArgument( + code: C, +): `The paragraph code \\${C} takes ${(typeof PARAGRAPH_CODE_ARGUMENTS)[C]}, and a ; after it` { + return `The paragraph code \\${code} takes ${PARAGRAPH_CODE_ARGUMENTS[code]}, and a ; after it`; +} + function isHex(code: number): boolean { return (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102); } @@ -267,7 +330,11 @@ function sameFormat(a: RunFormat, b: RunFormat): boolean { a.bold === b.bold && a.font === b.font && a.size === b.size && - a.align === b.align + a.height === b.height && + a.widthFactor === b.widthFactor && + a.obliqueAngle === b.obliqueAngle && + a.align === b.align && + a.color === b.color ); } @@ -275,10 +342,9 @@ function sameFormat(a: RunFormat, b: RunFormat): boolean { * Reads a paragraph's value in one pass, in time and memory in proportion to its length, with a * stack of its own for its braces that holds at most `PARAGRAPH_NESTING` formats: a brace past * that is counted and changes nothing. It never throws, and reads any string: what it refuses - * is `problem`, the first it met. With `dimension`, as for the text of a dimension's picture, it - * also reads `\A0;` to `\A2;` and `\H` with a factor, such as `\H0.75x;`. + * is `problem`, the first it met. The text of a dimension's picture is read alike. */ -export function parseParagraph(value: string, dimension = false): ParsedParagraph { +export function parseParagraph(value: string): ParsedParagraph { const pieces: ParagraphPiece[] = []; let problem: string | undefined; const fail = (message: string): void => { @@ -431,18 +497,16 @@ export function parseParagraph(value: string, dimension = false): ParsedParagrap fail(paragraphNoSemicolon(letter)); return n; } - // The text of a dimension's picture centers its stacks and sizes its fractions. - const argument = value.slice(at + 1, end); - if (dimension && letter === "A" && /^[012]$/.test(argument)) { - set({ ...format, align: Number(argument) as 0 | 1 | 2 }); - return end + 1; - } - const times = dimension && letter === "H" ? /^(\d+(?:\.\d+)?)x$/.exec(argument) : null; - if (times !== null && Number(times[1]) > 0) { - set({ ...format, size: format.size * Number(times[1]) }); + if (letter === "T" || letter === "c") { + fail(paragraphNotLaidOut(letter)); return end + 1; } - fail(paragraphNotLaidOut(letter as NotLaidOutCode)); + const argument = value.slice(at + 1, end); + const set1 = ARGUMENTS[letter]!.test(argument) + ? CODE_SETS[letter]!(argument, format) + : undefined; + if (set1 === undefined) fail(paragraphCodeArgument(letter as ArgumentCode)); + else set(set1); return end + 1; } fail(paragraphUnknownCode(letter)); diff --git a/src/paragraphs.ts b/src/paragraphs.ts index 1707a3f..b1155a1 100644 --- a/src/paragraphs.ts +++ b/src/paragraphs.ts @@ -87,6 +87,11 @@ import { Strings } from "./shape.ts"; // size below its line's top and each next line 5/3 of it below, and the box ends 2/3 of it // below the last baseline, less 4/3 of what it passes the height by. // - A tab's underline runs from the pen to its stop. +// - A run of `\H`, `\W` or `\Q` is laid out at its own height, width factor and lean. A line's A is +// its tallest run's top, its D a third of that run's height, and the slot adds a third of the +// paragraph's height. `\A1;` centers the runs after it on the line's tallest run, `\A2;` sets +// them at its top. A run after a leaned one starts further by its last character's lean. A line +// holding spaces or a tab in a format of their own is placed by its first point. // - Columns, each the width wide and the gutter apart: a line whose box reaches below its column's // height, where at-least spacing ends it at its ink, starts the next, as does the first line // after a `\N`. It starts the column as a first line does, with the room its paragraph leaves @@ -259,6 +264,12 @@ export interface ParagraphRun { readonly font: string; /** True for a run in its font's bold face. */ readonly bold: boolean; + /** What scales its characters along the line, the style's width factor or a `\W` code's. */ + readonly widthFactor: number; + /** Its oblique angle in degrees: the style's, or a `\Q` code's. */ + readonly obliqueAngle: number; + /** The color by its index a `\C` code sets, or undefined for the entity's. */ + readonly color: number | undefined; /** How far its characters' advances take it along the line from its first point. */ readonly advance: number; /** Where it starts and ends to draw along the line from `at`, as `layoutText` gives a text. */ @@ -583,6 +594,12 @@ interface Built { lastIndex: number; top: number; bottom: number; + /** Its height, what scales its characters along the line, and its lean, from its format. */ + readonly size: number; + readonly along: number; + readonly lean: number; + /** How far `\A` raises it from the line's baseline, once the line is measured. */ + rise: number; } /** A stack a line holds, at its first point `x`. */ @@ -592,6 +609,7 @@ interface Stacked { readonly shape: StackShape; readonly face: Face; readonly value: string; + readonly format: RunFormat; } /** Where a tab of a line takes the pen, from `from` to `to`, in the format it is in. */ @@ -606,7 +624,11 @@ interface Tabbed { /** What a line holds as it is built, in drawing units from its first point. */ interface Line { readonly items: (Built | Stacked | Tabbed)[]; - /** True when it ends in a stack and the spaces after the stack were dropped. */ + /** + * True when it is placed by its first point and not by its first character's ink: when it ends + * in a stack or a run of another format than the spaces dropped after it, or holds spaces or a + * tab in a format of their own. + */ spaced: boolean; /** The paragraph it is in, by its index in the properties `resolve` gives. */ readonly paragraph: number; @@ -631,6 +653,8 @@ interface Pen { key: string | undefined; /** Where the last character's ink ends. */ ink: number; + /** How far the last character's lean takes its top or its foot past its ink. */ + leaned: number; /** A tab the next character ends, which goes to a stop once that character is known. */ tab: PendingTab | undefined; /** @@ -668,6 +692,7 @@ type WordPart = readonly shape: StackShape; readonly face: Face; readonly value: string; + readonly format: RunFormat; }; /** The parts of a word or of the spaces before it, kept from word to word to be used again. */ @@ -780,10 +805,7 @@ export function layoutParagraph(paragraph: ParagraphToMeasure): ParagraphLayout * a fraction. */ export function layoutDimensionText(paragraph: ParagraphToMeasure): ParagraphLayout { - return layOut( - { ...settingsOf(paragraph), dimension: true }, - parseParagraph(paragraph.value, true), - ); + return layOut({ ...settingsOf(paragraph), dimension: true }, parseParagraph(paragraph.value)); } /** The text of a dimension's picture where it plots, as `measureParagraph` gives a paragraph. */ @@ -910,6 +932,20 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const given = settings.width; const tangent = Math.tan((obliqueAngle * Math.PI) / 180); const lean = Number.isFinite(tangent) ? tangent : 0; + /** A run's height, held to the most and least a number may be, which a chain of factors can pass. */ + const sizeOf = (format: RunFormat): number => { + const tall = format.height ?? height * format.size; + if (tall > 0 && tall < PROPERTY_MOST) return tall; + approximate = true; + return tall >= PROPERTY_MOST ? PROPERTY_MOST : Number.MIN_VALUE; + }; + const alongOf = (format: RunFormat): number => + sizeOf(format) * (format.widthFactor ?? widthFactor); + const leanOf = (format: RunFormat): number => { + if (format.obliqueAngle === undefined) return lean; + const turned = Math.tan((format.obliqueAngle * Math.PI) / 180); + return Number.isFinite(turned) ? turned : 0; + }; let approximate = settings.font === undefined || parsed.problem !== undefined; const properties = resolve(parsed.pieces, height); // Spacing outside what a paragraph's own may be, indents and room below nothing, numbers held @@ -949,7 +985,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { return face; }; const keyOf = (format: RunFormat, face: Face): string => - `${face.font}|${face.bold}|${format.underline}|${format.overline}|${format.strikeThrough}`; + `${face.font}|${face.bold}|${format.underline}|${format.overline}|${format.strikeThrough}|${format.size}|${format.height}|${format.widthFactor}|${format.obliqueAngle}|${format.align}|${format.color}`; /** Where a line of a paragraph starts from the left of the box: none without a width. */ const originOf = (p: Resolved, first: boolean): number => @@ -983,6 +1019,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { x: 0, key: undefined, ink: 0, + leaned: 0, tab: undefined, gap: 0, started: false, @@ -1030,7 +1067,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { * of the first of them, or the last stack's ink; spaces have no part in it. */ const place = (parts: Parts, pen: Pen, into?: Line): number => { - let { x, key, ink } = pen; + let { x, key, ink, leaned } = pen; let reach = x; let left: number | undefined; /** Where the line's first point stands from the left of the box. */ @@ -1055,6 +1092,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { }); } ink = x; + leaned = 0; pen.tab = undefined; pen.tabbed = true; }; @@ -1071,10 +1109,12 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { shape: part.shape, face: part.face, value: part.value, + format: part.format, }); } reach = x + part.shape.ink + pen.gap; ink = x + part.shape.ink; + leaned = 0; pen.started = true; x += part.shape.advance; key = undefined; @@ -1083,6 +1123,8 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { } const { face } = part; const { source: value, to } = part; + const along = alongOf(part.format); + const size = sizeOf(part.format); let run: Built | undefined; if (into && key === part.key) { const last = into.items[into.items.length - 1]; @@ -1105,14 +1147,24 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const lefts = code === 32 ? 0 : face.lefts[index]! * along; if (at === undefined) { // The first character of a line: its ink, or a space's first point, starts the line. - at = line.origin - (code === 32 ? 0 : lefts + lean * face.bottoms[index]! * height); + // Leaned right, its ink starts at its foot; leaned left, at its top, and never right of + // its first point. + const leaning = leanOf(part.format); + at = + line.origin - + (code === 32 + ? 0 + : leaning < 0 + ? Math.max(0, lefts + leaning * face.tops[index]! * size) + : lefts + leaning * face.bottoms[index]! * size); } // The first character after a tab: its ink starts at the stop. if (pen.tab) toStop(lefts); pen.started = true; if (key !== part.key) { - // A new run starts where the last one's advances end, or its ink where that is further. - if (key !== undefined && ink > x) x = ink; + // A new run starts where the last one's advances end, or its ink where that is further, + // and further by how far the last one's lean took its last character. + if (key !== undefined) x = Math.max(x, ink) + leaned; key = part.key; if (into) { into.at ??= at; @@ -1130,6 +1182,10 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { lastIndex: 0, top: 0, bottom: 0, + size, + along, + lean: leanOf(part.format), + rise: 0, }; into.items.push(run); } @@ -1139,6 +1195,9 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { left ??= lefts; reach = ink - left + pen.gap; } + // The next run starts further by how far this character's lean takes its top or its foot. + const leaning = run?.lean ?? leanOf(part.format); + leaned = Math.max(0, leaning * face.tops[index]!, leaning * face.bottoms[index]!) * size; if (run) { if (run.source !== value || run.to !== k) { if (run.to > run.from) (run.head ??= []).push(run.source.slice(run.from, run.to)); @@ -1164,12 +1223,23 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { pen.x = x; pen.key = key; pen.ink = ink; + pen.leaned = leaned; return reach + line.origin; }; /** Drops the spaces a line ends with. */ const endLine = (): void => { - if (spaces.count > 0 && line.items[line.items.length - 1]?.kind === "stack") line.spaced = true; + const last = line.items[line.items.length - 1]; + const dropped = spaces.count > 0 ? spaces.items[0] : undefined; + if ( + dropped && + (last?.kind === "stack" || + (last?.kind === "run" && + dropped.kind === "characters" && + dropped.key !== keyOf(last.format, last.face))) + ) { + line.spaced = true; + } spaces.count = 0; }; const restart = (first: boolean): void => { @@ -1177,6 +1247,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { pen.x = 0; pen.key = undefined; pen.ink = 0; + pen.leaned = 0; pen.tab = undefined; pen.gap = 0; pen.started = false; @@ -1192,6 +1263,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { x: 0, key: undefined, ink: 0, + leaned: 0, tab: undefined, gap: 0, started: false, @@ -1202,6 +1274,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { trial.x = pen.x; trial.key = pen.key; trial.ink = pen.ink; + trial.leaned = pen.leaned; trial.tab = pen.tab; trial.gap = pen.gap; trial.started = pen.started; @@ -1260,6 +1333,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { pen.x = 0; pen.key = undefined; pen.ink = 0; + pen.leaned = 0; pen.tab = undefined; pen.gap = 0; pen.started = false; @@ -1294,13 +1368,17 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { if ((blank(top) && top.ink > bottom.ink) || (blank(bottom) && bottom.ink > top.ink)) { approximate = true; } + // A stack under a width factor or a lean of its own is laid out in them, unmeasured. + if (piece.format.widthFactor !== undefined || piece.format.obliqueAngle !== undefined) { + approximate = true; + } const stacked = stackShape( top, bottom, piece.separator, face, - height * piece.format.size, - widthFactor, + sizeOf(piece.format), + piece.format.widthFactor ?? widthFactor, ); // A centered stack's bar, or the middle of its slash, is half a height above the line. let shape = stacked; @@ -1311,12 +1389,14 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { } else approximate = true; } const value = `${piece.top}${piece.separator}${piece.bottom}`; - word.items[word.count++] = { kind: "stack", shape, face, value }; + word.items[word.count++] = { kind: "stack", shape, face, value, format: piece.format }; return; } if (face.shx && piece.diameter) approximate = true; - // Characters at a size of their own are not laid out yet. - if (piece.format.size !== 1) approximate = true; + // An SHX font leaned by a `\Q` code is not measured, as one a style leans is not. + if (face.shx && piece.format.obliqueAngle !== undefined && piece.format.obliqueAngle !== 0) { + approximate = true; + } const { format } = piece; const key = keyOf(format, face); let from = 0; @@ -1345,6 +1425,36 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { if (lean !== 0 && [...faces.values()].some((face) => face.shx)) approximate = true; + /** True for a line that holds spaces, or a tab, in a format of their own. */ + const holdsLoneSpace = (built: Line): boolean => { + const items = built.items; + for (let i = 0; i < items.length; i++) { + const item = items[i]!; + if (item.kind === "tab") { + const before = items[i - 1]; + if ( + before?.kind === "run" && + keyOf(before.format, before.face) !== keyOf(item.format, item.face) + ) + return true; + continue; + } + if (item.kind !== "run") continue; + const before = items[i - 1]; + const after = items[i + 1]; + const apart = + (before?.kind === "run" && + keyOf(before.format, before.face) !== keyOf(item.format, item.face)) || + (after?.kind === "run" && + keyOf(after.format, after.face) !== keyOf(item.format, item.face)); + if (!apart) continue; + let blank = item.to > item.from || item.head !== undefined; + for (let k = item.from; blank && k < item.to; k++) blank = item.source.charCodeAt(k) === 32; + if (blank && item.head?.some((part) => part.trim() !== "")) blank = false; + if (blank) return true; + } + return false; + }; // Each line's ink along it, upright and leaned, and how far it reaches up and down. const measured = lines.map((built) => { let up = 0; @@ -1359,6 +1469,10 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { // and how far below the line a stack sets its lowest part's baseline. let runDown = 0; let drop = 0; + /** The height of the line's tallest run, which `\A` sets the others by and D is a third of. */ + let tallest = 0; + let lastLean = lean; + for (const item of built.items) if (item.kind === "run") tallest = Math.max(tallest, item.size); for (const item of built.items) { if (item.kind === "tab") { start ??= 0; @@ -1374,13 +1488,20 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { continue; } const run = item; - up = Math.max(up, (run.format.overline ? Math.max(run.top, OVERLINE) : run.top) * height); - down = Math.min(down, run.bottom * height); + const size = run.size; + // Centered on the tallest run, or at its top. + run.rise = + run.format.align === 1 ? (tallest - size) / 2 : run.format.align === 2 ? tallest - size : 0; + up = Math.max( + up, + (run.format.overline ? Math.max(run.top, OVERLINE) : run.top) * size + run.rise, + ); + down = Math.min(down, run.bottom * size + run.rise); runDown = Math.min( runDown, - run.bottom * height, + run.bottom * size, settings.dimension && !run.face.shx && valueOf(run).includes(" ") - ? -run.face.unit * height + ? -run.face.unit * size : 0, ); if (start === undefined) { @@ -1388,10 +1509,13 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { (run.head?.[0] ?? run.source.slice(run.from, run.to)).codePointAt(0) ?? 32, ); if (index < 0) index = UNKNOWN; - start = run.x + run.face.lefts[index]! * along; - startLean = lean * run.face.bottoms[index]! * height; + start = run.x + run.face.lefts[index]! * run.along; + startLean = + (run.lean < 0 ? run.lean * run.face.tops[index]! : run.lean * run.face.bottoms[index]!) * + size; } - end = run.last + run.face.rights[run.lastIndex]! * along; + end = run.last + run.face.rights[run.lastIndex]! * run.along; + lastLean = run.lean; drawn = true; } const empty = !drawn; @@ -1400,18 +1524,19 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { // A line that ends in a stack and dropped spaces after it is placed by its first point and // not by its ink: the left of its first character's ink further on, at any attachment. const first = built.items[0]; - const shift = built.spaced && first?.kind === "run" ? (start ?? 0) - first.x : 0; + const shift = + (built.spaced || holdsLoneSpace(built)) && first?.kind === "run" ? (start ?? 0) - first.x : 0; return { built, top, - below: stackUp > up ? 0 : AT_LEAST_BELOW * height, + below: stackUp > up ? 0 : AT_LEAST_BELOW * Math.max(tallest, height * (empty ? 1 : 0)), // A dimension's box reaches where a stack sets its lowest part only when the stack reaches highest. down: settings.dimension ? runDown - (stackUp > up ? drop : 0) : down, start: start ?? 0, end, shift, leanedStart: (start ?? 0) + startLean - shift, - leanedEnd: empty ? 0 : end + lean * top - shift, + leanedEnd: empty ? 0 : end + lastLean * top - shift, empty, }; }); @@ -1539,8 +1664,22 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { else if (value === "") value = part; else values = [value, part]; }; - /** Adds a run of `value` in `face` at its first point `x`, of `size`, with its baseline at `base`. */ - const run = (value: string, x: number, base: number, size: number, face: Face, top: number) => { + /** + * Adds a run of `value` in `face` at its first point `x`, of `size`, with its baseline at `base`, + * its characters scaled along the line by `factor` and leaning by `leaning`. + */ + const run = ( + value: string, + x: number, + base: number, + size: number, + face: Face, + top: number, + factor: number = widthFactor, + leaning: number = lean, + angle: number = obliqueAngle, + color: number | undefined = undefined, + ) => { if (value === "") return undefined; let advance = 0; let head: number | undefined; @@ -1552,7 +1691,9 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { advance += face.advances[index]!; tail = face.tails?.[index] ?? 0; } - const scale = size * widthFactor; + // A run too small for the writers' decimals draws nothing in the preview. + if (!(written(size) > 0)) approximate = true; + const scale = size * factor; const drawn: ParagraphRun = { value, x, @@ -1563,28 +1704,42 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { advance: advance * scale, start: x + (head ?? 0) * scale, end: x + (advance + tail) * scale, + widthFactor: factor, + obliqueAngle: angle, + color, }; runs.push(drawn); const below = face.below * size; const reach = Math.max(top, 1) * size; const from = Math.min(drawn.start, x); const to = Math.max(drawn.end, x + drawn.advance); - include(from - lean * below, base - below); - include(to + lean * reach, base + reach); - include(from + lean * reach, base + reach); - include(to - lean * below, base - below); + include(from - leaning * below, base - below); + include(to + leaning * reach, base + reach); + include(from + leaning * reach, base + reach); + include(to - leaning * below, base - below); return drawn; }; - /** The underline, overline and strike-through of `format` from `x0` to `x1` on the line. */ - const lined = (format: RunFormat, face: Face, x0: number, x1: number): void => { + /** + * The underline, overline and strike-through of `format` from `x0` to `x1` on the line, of + * characters `size` high on a baseline `rise` above the line's. + */ + const lined = ( + format: RunFormat, + face: Face, + x0: number, + x1: number, + size: number = height, + rise = 0, + ): void => { + const base = baseline + rise; if (format.underline) { - const up = baseline - face.underline * height; + const up = base - face.underline * size; stroke("underline", [x0, up], [x1, up]); } if (format.overline) - stroke("overline", [x0, baseline + OVERLINE * height], [x1, baseline + OVERLINE * height]); + stroke("overline", [x0, base + OVERLINE * size], [x1, base + OVERLINE * size]); if (format.strikeThrough) { - const up = baseline + STRIKE_THROUGH * height; + const up = base + STRIKE_THROUGH * size; stroke("strike-through", [x0, up], [x1, up]); } }; @@ -1622,7 +1777,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { let across = 0; if (!m.empty && given > 0 && (style === "justified" || style === "distributed")) { // A line wider than its room is not squeezed: it stands as one with no gaps would. - gaps = to < inkTo ? NO_GAPS : gapsOf(built, style === "distributed", along); + gaps = to < inkTo ? NO_GAPS : gapsOf(built, style === "distributed"); after = lastTabOf(built); if (gaps.length > 0) stretch = (to - inkTo) / gaps.length; } @@ -1648,8 +1803,20 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { if (item.kind === "stack") { add(item.value); const x = item.x + offset + (i > after ? grow(item.x) : 0); + const f = item.format; for (const part of item.shape.parts) { - run(part.value, x + part.x, baseline + part.up, item.shape.size, item.face, part.top); + run( + part.value, + x + part.x, + baseline + part.up, + item.shape.size, + item.face, + part.top, + f.widthFactor ?? widthFactor, + leanOf(f), + f.obliqueAngle ?? obliqueAngle, + f.color, + ); } const drawnStroke = item.shape.stroke; if (drawnStroke) { @@ -1660,10 +1827,22 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { } const drawn = valueOf(item); add(drawn); + const factor = item.format.widthFactor ?? widthFactor; if (i <= after || gaps.length === 0) { const x = item.x + offset; - run(drawn, x, baseline, height, item.face, item.top); - lined(item.format, item.face, x, x + item.advance); + run( + drawn, + x, + baseline + item.rise, + item.size, + item.face, + item.top, + factor, + item.lean, + item.format.obliqueAngle ?? obliqueAngle, + item.format.color, + ); + lined(item.format, item.face, x, x + item.advance, item.size, item.rise); continue; } // A stretched line draws each word and each space, or each character, on its own: the @@ -1677,12 +1856,18 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { const placed = run( drawn.slice(start, end), pieceX + offset + grow(pieceX), - baseline, - height, + baseline + item.rise, + item.size, item.face, item.top, + factor, + item.lean, + item.format.obliqueAngle ?? obliqueAngle, + item.format.color, ); - if (placed) lined(item.format, item.face, placed.x, placed.x + placed.advance); + if (placed) { + lined(item.format, item.face, placed.x, placed.x + placed.advance, item.size, item.rise); + } start = end; pieceX = x; }; @@ -1693,7 +1878,7 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { afterSpace = space; let index = tableIndex(drawn.codePointAt(c)!); if (index < 0) index = UNKNOWN; - x += item.face.advances[index]! * along; + x += item.face.advances[index]! * item.along; // A pair of surrogates is one character. if (code >= 0xd800 && code <= 0xdbff && drawn.charCodeAt(c + 1) >= 0xdc00) c++; } @@ -1750,7 +1935,7 @@ function lastTabOf(line: Line): number { * what it lacks: after each space that follows a character since its last tab. A distributed line * grows before each character and stack since its last tab but the first. */ -function gapsOf(line: Line, distributed: boolean, along: number): number[] { +function gapsOf(line: Line, distributed: boolean): number[] { const out: number[] = []; let seen = false; const items = line.items; @@ -1766,7 +1951,7 @@ function gapsOf(line: Line, distributed: boolean, along: number): number[] { for (const character of valueOf(item)) { let index = indexOf(character); if (index < 0) index = UNKNOWN; - const advance = item.face.advances[index]! * along; + const advance = item.face.advances[index]! * item.along; const space = character === " "; if (distributed ? seen : space && seen) out.push(distributed ? x : x + advance); if (distributed || !space) seen = true; @@ -1784,6 +1969,61 @@ function corners( return [place(x0, y0), place(x1, y0), place(x1, y1), place(x0, y1)]; } +/** + * Where a line's box reaches along it, on its baseline and at its top, left and right, so that it + * holds each run leaned by its own angle up to its own top. A run's top is its capitals' height, + * scaled so that the tallest reaches the line's top, and a run of spaces holds nothing. The left + * side leans from the line's start on its baseline, its first point, past every run's corners. + * The right side stands upright or leans as the line's last run does, whichever leaves the less + * room, pushed out past every run's corners. + */ +function sides( + line: ParagraphLine, +): [lowLeft: number, lowRight: number, highRight: number, highLeft: number] { + const { runs, top, start, end } = line; + let tallest = 0; + let first = -1; + let last = -1; + for (let i = 0; i < runs.length; i++) { + const run = runs[i]!; + tallest = Math.max(tallest, run.baseline - line.baseline + run.height); + if (/\S/.test(run.value)) { + if (first < 0) first = i; + last = i; + } + } + if (!(top > 0) || !(tallest > 0) || first < 0) return [start, end, end, start]; + const tangent = (run: ParagraphRun): number => { + const turned = Math.tan((run.obliqueAngle * Math.PI) / 180); + return Number.isFinite(turned) ? turned : 0; + }; + const lean = tangent(runs[last]!); + let left = Infinity; + let upright = end; + let leaning = end; + for (let i = first; i <= last; i++) { + const run = runs[i]!; + if (!/\S/.test(run.value)) continue; + const slant = tangent(run); + const foot = run.baseline - line.baseline; + const head = Math.min(top, Math.max(foot, ((foot + run.height) * top) / tallest)); + if (head <= 0) continue; + const from = i === first ? start : Math.max(start, run.start); + const to = i === last ? end : Math.min(end, run.end); + for (const y of [Math.max(foot, 0), head]) { + const x = to + slant * (y - foot); + upright = Math.max(upright, x); + leaning = Math.max(leaning, x - lean * y); + if (y > 0) left = Math.min(left, (from + slant * (y - foot) - start) / y); + } + } + const highLeft = start + (Number.isFinite(left) ? left : 0) * top; + // Halfway up, the upright side stands at `upright` and the leaning one at leaning + lean * top / 2. + return upright <= leaning + (lean * top) / 2 + ? [start, upright, upright, highLeft] + : [start, leaning, leaning + lean * top, highLeft]; +} + /** A paragraph's measure from its layout, in time in proportion to its lines. */ export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout): ParagraphMeasure { const place = placer(paragraph); @@ -1791,14 +2031,14 @@ export function measured(paragraph: ParagraphToMeasure, layout: ParagraphLayout) const lines: { value: string; corners: [Point, Point, Point, Point]; column: number }[] = []; for (const line of layout.lines) { if (line.runs.length === 0) continue; - const lean = layout.lean * line.top; + const [lowLeft, lowRight, highRight, highLeft] = sides(line); lines.push({ value: line.value, corners: [ - place(line.start, line.baseline), - place(line.end, line.baseline), - place(line.end + lean, line.baseline + line.top), - place(line.start + lean, line.baseline + line.top), + place(lowLeft, line.baseline), + place(lowRight, line.baseline), + place(highRight, line.baseline + line.top), + place(highLeft, line.baseline + line.top), ], column: line.column, }); diff --git a/src/rules.ts b/src/rules.ts index ba84d96..ed05722 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -54,6 +54,7 @@ import { type paragraphItalic, type paragraphNoSemicolon, type paragraphNotLaidOut, + type paragraphCodeArgument, type paragraphPropertyUnknown, type paragraphShxBold, type paragraphUnknownCode, @@ -1025,8 +1026,96 @@ type ParagraphPercent = S extends `${string}%${infer R}` ? ["% /** The codes of a paragraph that draw a character, and need nothing after them. */ type ParagraphPlainCode = "P" | "N" | "~" | "\\" | "{" | "}" | "o"; -/** The codes tsdraft does not lay out that end with a `;`. */ -type ParagraphEndedCode = "H" | "W" | "Q" | "T" | "A" | "C" | "c"; +/** The codes that set what the characters after them are and end with a `;`. */ +type ParagraphEndedCode = "H" | "W" | "Q" | "A" | "C"; + +/** True for all zeros. */ +type AllZeros = S extends `0${infer R}` + ? R extends "" + ? true + : AllZeros + : false; + +/** True for one to `M` digits, as many as `Most` holds. */ +type FewDigits< + S extends string, + Most extends 0[], + K extends 0[] = [0], +> = S extends `${Digit}${infer R}` + ? R extends "" + ? true + : K["length"] extends Most["length"] + ? false + : FewDigits + : false; + +type Fifteen = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; +type SixtyFour = [...Fifteen, ...Fifteen, ...Fifteen, ...Fifteen, 0, 0, 0, 0]; + +/** True for nothing, or a point and digits. */ +type Fraction = S extends "" + ? true + : S extends `.${infer F}` + ? AllDigits + : false; + +/** True for a number of at most 15 digits before its point and 64 after, above 0, as `\H` and `\W` take. */ +type CodeAmount = S extends `${infer I}.${infer F}` + ? FewDigits extends true + ? FewDigits extends true + ? AllZeros<`${I}${F}`> extends true + ? false + : true + : false + : false + : FewDigits extends true + ? AllZeros extends true + ? false + : true + : false; + +type Below85 = + | Digit + | `${"1" | "2" | "3" | "4" | "5" | "6" | "7"}${Digit}` + | `8${"0" | "1" | "2" | "3" | "4"}`; + +/** True for an angle from -85 to 85, as `\Q` takes. */ +type CodeOblique = S extends `-${infer R}` ? CodeOblique85 : CodeOblique85; +type CodeOblique85 = S extends `${infer I}.${infer F}` + ? FewDigits extends true + ? I extends Below85 + ? true + : I extends "85" + ? AllZeros + : false + : false + : S extends Below85 | "85" + ? true + : false; + +type Below258 = + | Digit + | `${"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"}${Digit}` + | `1${Digit}${Digit}` + | `2${"0" | "1" | "2" | "3" | "4"}${Digit}` + | `25${"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7"}`; + +/** True for the argument code `C` takes, as `ARGUMENTS` in `src/paragraph-codes.ts` reads it. */ +type CodeArgument = C extends "H" + ? S extends `${infer A}x` + ? CodeAmount + : CodeAmount + : C extends "W" + ? CodeAmount + : C extends "Q" + ? CodeOblique + : C extends "A" + ? S extends "0" | "1" | "2" + ? true + : false + : S extends Below258 + ? true + : false; /** * Whether the characters are underlined, `L`, struck through, `K`, both or neither, as the codes @@ -1155,25 +1244,31 @@ type ParagraphCode< [...N, 0] > : ReturnType> - : C extends ParagraphEndedCode + : C extends "T" | "c" ? After extends `${string};${string}` ? ReturnType> : ReturnType> - : C extends "X" | "O" - ? ReturnType> - : C extends "U" | "u" - ? After extends `+${infer H1}${infer H2}${infer H3}${infer H4}${infer Next}` - ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] - ? ParagraphUnicode, Next, D, N, F> - : ReturnType> - : ReturnType> - : C extends "M" | "m" - ? After extends `+${"1" | "2" | "3" | "4" | "5"}${infer H1}${infer H2}${infer H3}${infer H4}${string}` + : C extends ParagraphEndedCode + ? After extends `${infer Argument};${infer Next}` + ? CodeArgument extends true + ? ParagraphCodes + : ReturnType> + : ReturnType> + : C extends "X" | "O" + ? ReturnType> + : C extends "U" | "u" + ? After extends `+${infer H1}${infer H2}${infer H3}${infer H4}${infer Next}` ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] - ? ReturnType> + ? ParagraphUnicode, Next, D, N, F> + : ReturnType> + : ReturnType> + : C extends "M" | "m" + ? After extends `+${"1" | "2" | "3" | "4" | "5"}${infer H1}${infer H2}${infer H3}${infer H4}${string}` + ? [H1, H2, H3, H4] extends [HexDigit, HexDigit, HexDigit, HexDigit] + ? ReturnType> + : ReturnType> : ReturnType> : ReturnType> - : ReturnType> : typeof PARAGRAPH_TRAILING; /** diff --git a/src/svg.ts b/src/svg.ts index fbba36c..b59566a 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -1433,7 +1433,6 @@ function paragraphToSvg( left -= part.length; }; const layout = left < 0 ? undefined : layOut(); - const { widthFactor = 1, obliqueAngle = 0 } = layout ?? {}; const mask = maskOf(e.mask); if (mask && layout) { const corners = paragraphMaskCorners(e, layout, mask).map(at); @@ -1443,6 +1442,9 @@ function paragraphToSvg( if (left < 0) break; for (const run of line.runs) { if (left < 0) break; + // A run too small to write, which a `\H` factor can make of a small paragraph, draws + // nothing, and its layout says it is approximate. + if (!(written(run.height) > 0)) continue; const text: Text = { kind: "text", layer: e.layer, @@ -1451,7 +1453,13 @@ function paragraphToSvg( value: run.value, rotation: paragraphTurn(e.rotation), }; - const style: TextStyle = { name: "", font: run.font, widthFactor, obliqueAngle }; + // Each run in its own width factor and oblique angle, the style's or a code's. + const style: TextStyle = { + name: "", + font: run.font, + widthFactor: run.widthFactor, + obliqueAngle: run.obliqueAngle, + }; // The run is drawn in its own face, from its first point. const drawn = { start: run.start - run.x, @@ -1459,7 +1467,11 @@ function paragraphToSvg( advance: run.advance, bold: run.bold, }; - add(textToSvg(text, style, pen, `data-part="text"`, matrix, false, drawn)); + // A run a `\C` code colors is drawn in that color, as a layer's is: by block, by layer and + // by entity leave it the entity's. + const own = run.color !== undefined && run.color >= 1 && run.color <= 255; + const runPen = own ? { ...pen, color: look.color(run.color!) } : pen; + add(textToSvg(text, style, runPen, `data-part="text"`, matrix, false, drawn)); } } for (const { kind, from, to } of layout?.strokes ?? []) { diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 1b1fdb4..16344e8 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2444,6 +2444,10 @@ test("a paragraph of many lines, runs or braces, a long word and numbers past dr }), paragraph({ value: "A B ".repeat(50_000), width: 1e99, columns: { height: 1e99, gutter: -1 } }), paragraph({ value: "A B ".repeat(50_000), width: 1, columns: null }), + // The codes of the characters: heights past drawing, a run each, and nested groups of them. + paragraph({ value: "\\H999999999999999;W ".repeat(20_000), width: 1 }), + paragraph({ value: "{\\H0.5x;\\W3;\\Q-85;\\A2;\\C7;A}".repeat(20_000), width: 2 }), + paragraph({ value: `${"{\\H2x;".repeat(16)}A${"}".repeat(16)} B`.repeat(5_000), width: 1 }), // Heights many paragraphs share, under a value long enough to be kept. paragraph({ value: "X".repeat(256), diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index 8aceda5..ceb6413 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -20,6 +20,8 @@ import { subscript, superscript, svgToPDF, + inspectText, + toPDF, toDXF, toSVG, checkDrawingRead, @@ -29,6 +31,7 @@ import { type Entity, type Paragraph, type ParagraphLayout, + type Point, } from "../src/index.ts"; import { paragraphMeasurer } from "../src/paragraphs.ts"; import { readProblems } from "./read-agreement.ts"; @@ -71,7 +74,11 @@ test("a paragraph's codes draw what the DXF Reference gives them", () => { bold: false, font: undefined, size: 1, + height: undefined, + widthFactor: undefined, + obliqueAngle: undefined, align: 0, + color: undefined, }; assert.deepEqual(formats, [ ["U", { ...plainFormat, underline: true }], @@ -95,12 +102,13 @@ test("what tsdraft does not lay out is refused, and named", () => { const refused: [string, RegExp][] = [ ["{A", /never closed/], ["A}", /closes no \{/], - ["\\H2;A", /code \\H, which sets the height/], - ["\\W0.8;A", /code \\W/], - ["\\Q15;A", /code \\Q/], - ["\\T2;A", /code \\T/], - ["\\A1;A", /code \\A/], - ["\\C1;A", /code \\C, which sets the color/], + ["\\H0;A", /code \\H takes a height above 0/], + ["\\H2.;A", /code \\H takes a height above 0/], + ["\\W-1;A", /code \\W takes a width factor above 0/], + ["\\Q86;A", /code \\Q takes an oblique angle in degrees, from -85 to 85/], + ["\\T2;A", /code \\T, which sets the spacing/], + ["\\A3;A", /code \\A takes 0, 1 or 2/], + ["\\C258;A", /code \\C takes a color number from 0 to 257/], ["\\c255;A", /code \\c, which sets the true color/], ["\\ptr3;A", /aligns text by its right/], ["\\psa1.2;A", /at least a size apart/], @@ -438,6 +446,97 @@ test("columns take a paragraph's lines in turn, where the leading CAD app sets t near(wide.lines[0]!.runs[0]!.x, -0.1589); }); +test("the codes that change the characters after them set them where the leading CAD app does", () => { + const lay = (value: string, more: object = {}) => + layoutParagraph({ value, height: 0.25, font: "Arial", ...more }); + const runs = (value: string, more: object = {}) => + lay(value, more).lines.flatMap((line) => + line.runs.map((run) => [run.value, +run.x.toFixed(4), +run.baseline.toFixed(4), run.height]), + ); + // A height drawn in drawing units or as a factor, the line set by its tallest run. + assert.deepEqual(runs("HH\\H2x;HH"), [ + ["HH", -0.028, -0.5, 0.25], + ["HH", 0.4765, -0.5, 0.5], + ]); + // A line's D is a third of its tallest run. + assert.deepEqual( + lay("HH\\P{\\H2x;HH}\\PHH").lines.map((line) => +line.baseline.toFixed(4)), + [-0.25, -0.9167, -1.4167], + ); + assert.deepEqual( + runs("\\H0.4;HH\\PHH").map((run) => run[3]), + [0.4, 0.4], + ); + // A width factor and an oblique angle of their own, not the style's. + const wide = lay("HH\\W2;HH", { widthFactor: 0.8 }).lines[0]!.runs.map((run) => run.widthFactor); + assert.deepEqual(wide, [0.8, 2]); + // A run after a leaned run starts further by the lean of its last capital's top. + assert.deepEqual( + runs("HH\\Q0;HH{\\Q30;HH}", { obliqueAngle: 15 }).map((run) => run[1]), + [-0.028, 0.5435, 1.0479], + ); + // Centered on the tallest run, from where \\A stands. + assert.deepEqual( + runs("H{\\H2x;H}\\A1;H{\\H0.5x;H}").map((run) => run[2]), + [-0.5, -0.5, -0.375, -0.3125], + ); + // A color starts a run and moves nothing; spaces of their own size place the line by its + // first point. + assert.deepEqual( + runs("\\C1;RED\\C3;GREEN").map((run) => run[0]), + ["RED", "GREEN"], + ); + // The preview draws a run in the color its code sets. + const colored = createDrawing({ units: "in" }); + colored.paragraph("{\\C1;RED} BLACK", { at: [0, 0] }); + const fills = toSVG(colored.build()) + .match(/]*>/g)! + .map((t) => /fill="([^"]*)"/.exec(t)![1]); + assert.deepEqual(fills, ["#ff0000", "currentColor"]); + assert.equal(runs("HH {\\H3x; } HH")[0]![1], 0); + // A stack under a width factor or a lean of its own is laid out and drawn in them, unmeasured. + const squeezed = lay('\\W2;1\\S1/2;" GYP'); + assert.ok(squeezed.approximate); + assert.deepEqual([...new Set(squeezed.lines[0]!.runs.map((run) => run.widthFactor))], [2]); + // A run leaned by a code leans its line's box, which inspectText reads. + const leaned = createDrawing({ units: "in" }); + leaned.rect([0, 0], 1.1, 1.1); + leaned.paragraph("\\Q45;H", { at: [0.05, 1], height: 1, style: { name: "A", font: "Arial" } }); + assert.ok(inspectText(leaned.build()).some((d) => d.rule === "text-leaves-boundary")); + // Each run leans the box by its own angle, up to its own top. + const leaves = (value: string, width: number, high = 1.4, at: Point = [0.2, 1.3]) => { + const d = createDrawing({ units: "in" }); + d.rect([0, 0], width, high); + d.paragraph(value, { at, height: 1, style: { name: "A", font: "Arial" } }); + return inspectText(d.build()).some((w) => w.rule === "text-leaves-boundary"); + }; + assert.equal(leaves("I{\\Q-40;H}I", 4), true); + assert.equal(leaves("H{\\H0.25x;\\Q45;H}", 1.7), false); + assert.equal(leaves("{\\Q85;T}{\\H9x;.}", 40, 40, [10, 30]), false); + // An upright line that starts with a stack is boxed by its ink, as before the codes. + const scale = createDrawing({ units: "in" }); + const value = '\\S1/16;" = 1\'-0"'; + const style = { name: "A", font: "Arial" } as const; + const line = layoutParagraph({ value, height: 1, font: "Arial" }).lines[0]!; + scale.paragraph(value, { at: [10, 2.8], height: 1, style }); + scale.text([10 + line.start - 0.1, 2.8 + line.baseline], "SCALE:", { + height: 1, + style: "A", + align: "right", + }); + assert.deepEqual(inspectText(scale.build()), []); + // A run a factor makes too small to write draws nothing, and the plot goes on. + const small = createDrawing({ units: "m" }); + small.paragraph("{\\H0.4x;NOTE}", { at: [0, 0.000004], height: 0.000001 }); + small.layout("A", { paper: "ANSI A" }, (page) => + page.viewport([1, 1], 4, 4, { center: [0, 0], ratio: 0.0001 }), + ); + assert.ok(toPDF(small.build()).length > 0); + // A chain of factors past what a number holds is held, and approximate. + const tall = lay(`${"\\H999999999999999x;".repeat(21)}A`); + assert.ok(tall.approximate && Number.isFinite(tall.lines[0]!.runs[0]!.height)); +}); + test("what the tables cannot lay out exactly is approximate, or refused", () => { const approximate = (value: string, font: string, obliqueAngle = 0) => layoutParagraph({ value, height: 1, font, obliqueAngle }).approximate; @@ -484,7 +583,7 @@ test("lint refuses a paragraph built as data that the leading CAD app would not ]); const refused: [Record, RegExp][] = [ [{ value: "A\nB" }, /^paragraph: .*control characters/], - [{ value: "\\H2;A" }, /^paragraph: .*code \\H/], + [{ value: "\\H0;A" }, /^paragraph: .*code \\H takes/], [{ lineSpacing: 5 }, /^paragraph: .*from 0.25 to 4/], [ { lineSpacingStyle: "loose" }, diff --git a/test/rules.test.ts b/test/rules.test.ts index c153c31..cc47482 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -1278,8 +1278,21 @@ test("a paragraph's height, width, line spacing and codes are checked twice", () assert.throws(() => d.paragraph("{\\LNOTE", { at }), /never closed/); // @ts-expect-error: a brace closes nothing. assert.throws(() => d.paragraph("NOTE}", { at }), /closes no \{/); - // @ts-expect-error: a height inside the value is not laid out yet. - assert.throws(() => d.paragraph("\\H2x;NOTE", { at }), /code \\H, which sets the height/); + d.paragraph("\\H2x;NOTE\\W0.8;\\Q15;\\A1;\\C1;", { at }); + // @ts-expect-error: a true color is not drawn yet. + assert.throws(() => d.paragraph("\\c255;NOTE", { at }), /code \\c, which sets the true color/); + assert.throws( + () => + // @ts-expect-error: more than 64 digits after the point. + d.paragraph("\\W1.00000000000000000000000000000000000000000000000000000000000000001;NOTE", { + at, + }), + /code \\W takes a width factor above 0/, + ); + // @ts-expect-error: a height of 0. + assert.throws(() => d.paragraph("\\H0x;NOTE", { at }), /code \\H takes a height above 0/); + // @ts-expect-error: the spacing of the characters is not laid out yet. + assert.throws(() => d.paragraph("\\T1.5;NOTE", { at }), /code \\T, which sets the spacing/); d.paragraph("\\pxi-3,l3,t3;1.\tNOTE", { at }); // @ts-expect-error: a tab stop that aligns by its right is not laid out yet. assert.throws(() => d.paragraph("\\pxtr3;1.\tNOTE", { at }), /aligns text by its right/); From b6279927ddf6a1287a917fea2a995899acd1d4cf Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 13:15:10 -0500 Subject: [PATCH 14/35] Arc length dimensions Arc length dimensions, drawn as the leading CAD app draws them: - `d.arcLengthDimension(center, radius, startAngle, endAngle, at, options)` measures the length of the arc about `center` of `radius`, counterclockwise from `startAngle` to `endAngle` in degrees, as `d.arc` takes them, with its own arc through `at`. The length is written as a length is, in the style's units. - From a right angle up, its own arc runs about the center through `at`, with extension lines along radii. Under one, its extension lines run parallel to the arc's bisector, and its own arc about the center through `at`, outside the arc. The marks, the text and its break are an angular dimension's, with the text on the arc's bisector. - A dimension style's `arcSymbol` puts the arc symbol `"before"` the text (the default, a half circle as high as the text), `"above"` it, or `"none"`. A centered text leaves room for the symbol, and its break reaches past it. A standard's dimension style takes it. - `lint` refuses an arc length dimension whose radius is 0 or less, that measures no arc, whose point is its center or on the arc, or that sits inside an arc under a right angle, where the leading CAD app's own arc stops short of an extension line; words below with the arc symbol; a centered text too long for its arc; marks turned outward whose tails would meet round the back; and a length with more digits than its writing holds. - A sweep within a millionth of a radian of a right angle counts as one, as the leading CAD app takes it, so a right angle whose ends' decimals put it a hair under still draws its extension lines along radii. - Angular dimensions: ticks longer than the arc is wide, turned outward, are refused where their tails would meet, as they now are for arc lengths. - `toDXF` writes them, and `readDXF` reads them as `arc-length-dimension`, with the center, radius and angles of the arc, its point, and whether it measures part of the arc. The command's dimension summary lists them. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 6 + GUIDE.md | 3 + cli/src/state.ts | 11 +- cli/src/worker.ts | 1 + docs/dimensions.md | 31 ++- docs/reading.md | 4 + src/arrowheads.ts | 3 + src/dimensions.ts | 404 ++++++++++++++++++++++++++++++++++++++- src/drawing.ts | 80 +++++++- src/dxf-r2018.ts | 41 +++- src/extents.ts | 1 + src/index.ts | 5 + src/inspect.ts | 1 + src/lint.ts | 14 +- src/read/check.ts | 18 ++ src/read/dxf.ts | 8 +- src/read/entities.ts | 47 +++++ src/read/model.ts | 28 +++ src/rules.ts | 33 ++++ src/shape.ts | 15 ++ src/standard/document.ts | 4 + src/standard/lint.ts | 1 + src/standard/literal.ts | 17 +- src/standard/shape.ts | 8 + standard.json | 3 + standard.schema.json | 11 ++ test/bounded.test.ts | 16 ++ test/dimensions.test.ts | 134 ++++++++++++- test/read-agreement.ts | 32 ++++ test/shape.test.ts | 17 +- 30 files changed, 973 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0f0ae9..f2db539 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -93,6 +93,12 @@ coordinates, and lists the file's image definitions in `images`, with how many images name each, one that none names among them. The example sheet has a vicinity map above its key plan. [docs/images.md](docs/images.md) describes them. +- Arc length dimensions: `arcLengthDimension(center, radius, startAngle, endAngle, at, options)` + measures the length of an arc, as `arc` takes it, with its own arc through `at`, drawn as the + leading CAD app draws it: from a right angle up about the center with extension lines along radii, + and under one with extension lines parallel to the arc's bisector. A dimension style's + `arcSymbol` puts the arc symbol `"before"` the text, `"above"` it, or `"none"`. `toDXF` writes + them, and `readDXF` reads them as `arc-length-dimension`. - Angular dimensions: `angularDimension(vertex, from, to, at, options)` measures the angle at `vertex` between the lines to `from` and `to`, its arc through `at`, which picks the angle as the leading CAD app does: the one between the lines that holds `at`, or the rest of the turn. Drawn as diff --git a/GUIDE.md b/GUIDE.md index 7917810..2de5c35 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -391,6 +391,9 @@ d.linearDimension([24, 30], [76, 30], [0, 20], { style: "PLAN" }); lines to `from` and `to`, its arc through `at`, which picks the angle. A style's `angleUnits`, `anglePrecision` and `suppressAngleZeros` write it, as `37°15'30"` in `"degrees-minutes-seconds"`. +- `arcLengthDimension(center, radius, startAngle, endAngle, at, options)` dimensions the length of + an arc, as `arc` takes it, with its own arc through `at`; a style's `arcSymbol` puts the arc + symbol `"before"` the text, `"above"` it, or `"none"`. - Never draw a dimension from lines and text. [docs/dimensions.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/dimensions.md) has the rest. diff --git a/cli/src/state.ts b/cli/src/state.ts index d0b5b69..9042fd4 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -356,9 +356,16 @@ export interface DimensionSummary { readonly layer: string; /** * `linear` measures along one direction, `aligned` from point to point, `radius`, `diameter` - * and `jogged-radius` a circle or an arc, and `angular` the angle between two lines. + * and `jogged-radius` a circle or an arc, `angular` the angle between two lines, and `arc-length` the length of an arc. */ - readonly kind: "linear" | "aligned" | "radius" | "diameter" | "jogged-radius" | "angular"; + readonly kind: + | "linear" + | "aligned" + | "radius" + | "diameter" + | "jogged-radius" + | "angular" + | "arc-length"; /** The dimension style as the dimension names it. */ readonly style: string; /** diff --git a/cli/src/worker.ts b/cli/src/worker.ts index 5bff596..1d16f4d 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -1554,6 +1554,7 @@ const SUMMARY_KINDS = { "diameter-dimension": "diameter", "jogged-radius-dimension": "jogged-radius", "angular-dimension": "angular", + "arc-length-dimension": "arc-length", } as const; /** Each dimension among some entities, with what the library the drawing loaded says it reads. */ diff --git a/docs/dimensions.md b/docs/dimensions.md index 11814be..d9ed491 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -237,6 +237,34 @@ one whose centered text leaves its arc no room each side; one whose closed arrow as its arc is wide; one whose arc runs all but a whole turn, which its 6 decimals write with one angle at both ends; and words below in a style that centers its text. +### Arc length + +`d.arcLengthDimension(center, radius, startAngle, endAngle, at, options)` measures the length of the +arc about `center` of `radius`, counterclockwise from `startAngle` to `endAngle` in degrees, as +`d.arc` takes them, with its own arc through `at`. The measurement is written as a length is, in the +style's units. + +```ts +d.arc([0, 0], 10, 30, 120); +d.arcLengthDimension([0, 0], 10, 30, 120, [0, 13], { style: "DIMS" }); // ⌒15.71 +``` + +From a right angle up, its own arc runs about the center through `at`, and its extension lines run +along radii. Under one, its extension lines run parallel to the arc's bisector, and its own arc runs +about the center through `at`, which must be outside the arc. The marks, the text and its break are +an angular dimension's, with the text on the arc's bisector. + +A dimension style's `arcSymbol` says where the arc symbol goes: `"before"` the text, the default, a +half circle as high as the text; `"above"` it, an arc over the text; or `"none"`. A centered text +leaves room on its arc for the symbol before it, on both sides of the text, and its break reaches +past the symbol. + +`lint` refuses an arc length dimension that measures no arc, whose radius is 0 or less, whose point +is its center or on the arc, or that is inside an arc under a right angle, where the leading CAD +app's own arc stops short of an extension line; one whose centered text leaves its own arc no room +each side; one whose measurement takes more digits than a length's writing holds; and words below +with the arc symbol. + ## How a measurement is written A measurement is the length between the points as the file holds them, with 6 decimals, @@ -411,7 +439,8 @@ no dimension style holds nothing else for dimensions. ## What is not drawn yet -Arc length and ordinate dimensions, an angular dimension by two lines, and an angular dimension's +Ordinate dimensions, an arc length dimension of part of an arc or with a leader, or inside an arc +under a right angle, an angular dimension by two lines, and an angular dimension's level text or text a drafter placed. A radial dimension's center mark, which the leading CAD app draws only without the line to the center, and a level text placed along its line. Tolerances and alternate units, and the unit formats but decimal and feet and inches. The other fits of a text, such as diff --git a/docs/reading.md b/docs/reading.md index a08a1d1..2fa2e0e 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -126,6 +126,10 @@ leader: middle of its text, `placed` where the file holds the text where it was placed, what it measures, its text, its style and the block of its picture. A file holds a diameter's far point, and the center is halfway to the point. +- `arc-length-dimension`: an arc length dimension, with the `center`, `radius`, `startAngle` and + `endAngle` of the arc it measures, a point its own arc passes through, `at`, the middle of its + text, `placed`, `partial` where it measures part of the arc, what it measures, its text, its style + and the block of its picture. - `angular-dimension`: an angular dimension, its `type`, `"three-point"` with its `vertex` and a point of each line, `from` and `to`, or `"two-line"` with its `first` and `second` lines, each two points; a point its arc passes through, `at`, the middle of its text, `placed`, the angle it diff --git a/src/arrowheads.ts b/src/arrowheads.ts index 6e8b4eb..7df9228 100644 --- a/src/arrowheads.ts +++ b/src/arrowheads.ts @@ -220,3 +220,6 @@ export const DIMENSION_ANGLE_UNITS = [ /** The most decimals an angle takes, as `DIMADEC` holds them. */ export const MAX_ANGLE_PRECISION = 8; + +/** Where an arc length dimension draws the arc symbol: before its text, above it, or nowhere. */ +export const DIMENSION_ARC_SYMBOLS = ["before", "above", "none"] as const; diff --git a/src/dimensions.ts b/src/dimensions.ts index 98cdb6d..39b6a21 100644 --- a/src/dimensions.ts +++ b/src/dimensions.ts @@ -4,6 +4,7 @@ import type { AlignedDimension, AngularDimension, + ArcLengthDimension, DiameterDimension, DimensionStyle, Drawing, @@ -39,8 +40,14 @@ import { DIMENSION_LEADER_BELOW, dimensionMeasureProblem, ANGULAR_ARC_LOST, + ARC_LENGTH_INSIDE_SHORT, + ARC_LENGTH_NO_ARC, + ARC_LENGTH_NO_REACH, + ARC_LENGTH_ON_ARC, + ARC_LENGTH_SYMBOL_BELOW, ANGULAR_ARC_ON_LINE, ANGULAR_ARROWS_LONG, + ANGULAR_TAILS_MEET, arcProblem, ANGULAR_ARC_ON_POINT, ANGULAR_CENTERED_SHORT, @@ -69,7 +76,7 @@ export type StraightDimension = LinearDimension | AlignedDimension; export type RadialDimension = RadiusDimension | DiameterDimension | JoggedRadiusDimension; /** A dimension of any kind. */ -export type Dimension = StraightDimension | RadialDimension | AngularDimension; +export type Dimension = StraightDimension | RadialDimension | AngularDimension | ArcLengthDimension; /** Whether an entity is a dimension. */ export function isDimension( @@ -79,6 +86,7 @@ export function isDimension( entity.kind === "linear-dimension" || entity.kind === "aligned-dimension" || entity.kind === "angular-dimension" || + entity.kind === "arc-length-dimension" || isRadial(entity) ); } @@ -138,8 +146,8 @@ export interface DimensionPictureHandles { readonly leader: readonly [string, string]; /** The text below the dimension line. */ readonly belowText: string; - /** The pieces of an angular dimension's arc. */ - readonly dimensionArcs: readonly [string, string, string]; + /** The pieces of an angular or arc length dimension's arc, and an arc length one's symbol. */ + readonly dimensionArcs: readonly [string, string, string, string]; } /** Where a dimension is: its id, or else its place among the entities of its space. */ @@ -175,7 +183,7 @@ export function validDimensionPictureHandles(place: DimensionPlace): DimensionPi ], leader: [handle("leader-1"), handle("leader-2")], belowText: handle("text-below"), - dimensionArcs: [handle("arc-1"), handle("arc-2"), handle("arc-3")], + dimensionArcs: [handle("arc-1"), handle("arc-2"), handle("arc-3"), handle("arc-4")], }; } @@ -652,6 +660,10 @@ export function dimensionMeasure(dimension: Dimension): { const { start, sweep } = angularArc(dimension); return { angle: start + sweep / 2, measurement: sweep * RADIANS }; } + if (dimension.kind === "arc-length-dimension") { + const { start, sweep, radius } = arcLengthArc(dimension); + return { angle: start + sweep / 2, measurement: radius * sweep * RADIANS }; + } if (isRadial(dimension)) { const [x1, y1] = [written(dimension.center[0]), written(dimension.center[1])]; const [x2, y2] = [written(dimension.point[0]), written(dimension.point[1])]; @@ -703,6 +715,8 @@ export function dimensionPicture( ): DimensionPicture { if (isRadial(dimension)) return radialPicture(dimension, style, textStyle); if (dimension.kind === "angular-dimension") return angularPicture(dimension, style, textStyle); + if (dimension.kind === "arc-length-dimension") + return arcLengthPicture(dimension, style, textStyle); const from: Point = [written(dimension.from[0]), written(dimension.from[1])]; const to: Point = [written(dimension.to[0]), written(dimension.to[1])]; const { angle, measurement } = dimensionMeasure(dimension); @@ -1509,8 +1523,8 @@ function angularDrawnProblem( // arc holds a closed arrowhead's chord and half the text's opening. // Turned outward, the marks and their tails must stay clear of each other round the back. if (picture.dimensionArcs.length === 3) { - const tail = (2 * Math.asin(size / (2 * radius))) / RADIANS; - if (sweep + 2 * ((closed ? tail : 0) + tail) >= 360) return ANGULAR_ARROWS_LONG; + const tail = (2 * Math.asin(Math.min(1, size / (2 * radius)))) / RADIANS; + if (sweep + 2 * ((closed ? tail : 0) + tail) >= 360) return ANGULAR_TAILS_MEET; } if (style.textPlacement === "centered" && picture.dimensionArcs.length === 2) { const chord = closed && size > 0 ? (2 * Math.asin(size / (2 * radius))) / RADIANS : 0; @@ -1541,6 +1555,382 @@ function angularRoom( return { text: length > needs, marks: length > needs + arrows }; } +/** + * An arc length dimension's arc as the writers write it: its center, its two ends with the 6 + * decimals tsdraft writes, the radius to the first, and the degrees, from 0 up to 360, it runs + * counterclockwise from `start` through `sweep`; and how far its own arc's point is from the center. + */ +export function arcLengthArc(dimension: ArcLengthDimension): { + readonly center: Point; + readonly radius: number; + readonly start: number; + readonly sweep: number; + readonly first: Point; + readonly second: Point; + readonly reach: number; +} { + const center: Point = [written(dimension.center[0]), written(dimension.center[1])]; + const end = (degrees: number): Point => { + const [x, y] = direction(written(degrees)); + const r = written(dimension.radius); + return [written(center[0] + x * r), written(center[1] + y * r)]; + }; + const [first, second] = [end(dimension.startAngle), end(dimension.endAngle)]; + const angleOf = (q: Point): number => { + const a = Math.atan2(q[1] - center[1], q[0] - center[0]) / RADIANS; + return a < 0 ? a + 360 : a; + }; + const start = angleOf(first); + const at: Point = [written(dimension.at[0]), written(dimension.at[1])]; + return { + center, + radius: Math.hypot(first[0] - center[0], first[1] - center[1]), + start, + sweep: (((angleOf(second) - start) % 360) + 360) % 360, + first, + second, + reach: Math.hypot(at[0] - center[0], at[1] - center[1]), + }; +} + +/** The least sweep, in degrees, the leading CAD app takes as a right angle: a millionth of a radian under. */ +const RIGHT_ANGLE_UNDER = 90 - 1e-6 / RADIANS; + +/** + * An arc length dimension's own arc: its center and radius, and the degrees it runs between where + * the extension lines meet it, from `arcStart` through `arcSweep`. From a right angle up, as the + * leading CAD app takes a sweep within a millionth of a radian of one, it runs about the center through the + * dimension's point; under one, it runs there too outside the arc, between the extension lines + * parallel to the bisector, and inside the arc it is the arc moved along the bisector. + */ +function arcLengthOwnArc(dimension: ArcLengthDimension): { + readonly arcCenter: Point; + readonly arcRadius: number; + readonly arcStart: number; + readonly arcSweep: number; + readonly footStart: Point; + readonly footEnd: Point; +} { + const { center, radius, start, sweep, first, second, reach } = arcLengthArc(dimension); + const move = (from: Point, by: Point, distance: number): Point => [ + from[0] + by[0] * distance, + from[1] + by[1] * distance, + ]; + const bisector = direction(start + sweep / 2); + const out = reach > radius ? 1 : -1; + // The leading CAD app takes a sweep within a millionth of a radian of a right angle as one. + const parallel = sweep < RIGHT_ANGLE_UNDER; + const [arcCenter, arcRadius]: [Point, number] = + parallel && out < 0 ? [move(center, bisector, reach - radius), radius] : [center, reach]; + const angleAbout = (q: Point): number => { + const a = Math.atan2(q[1] - arcCenter[1], q[0] - arcCenter[0]) / RADIANS; + return a < 0 ? a + 360 : a; + }; + /** Where an extension line from an end of the arc meets the dimension's own arc. */ + const foot = (p: Point, degrees: number): Point => { + if (!parallel) { + const [x, y] = direction(degrees); + return [center[0] + x * reach, center[1] + y * reach]; + } + if (out < 0) return move(p, bisector, reach - radius); + // Along the bisector from the end to the circle about the center through the point. + const along = (p[0] - center[0]) * bisector[0] + (p[1] - center[1]) * bisector[1]; + const square = (p[0] - center[0]) ** 2 + (p[1] - center[1]) ** 2; + return move(p, bisector, -along + Math.sqrt(along * along - square + reach * reach)); + }; + const [footStart, footEnd] = [foot(first, start), foot(second, start + sweep)]; + const arcStart = angleAbout(footStart); + return { + arcCenter, + arcRadius, + arcStart, + arcSweep: (((angleAbout(footEnd) - arcStart) % 360) + 360) % 360, + footStart, + footEnd, + }; +} + +/** + * What the leading CAD app draws for an arc length dimension in a style. From a right angle up its + * own arc runs about the center through its point, and its extension lines along radii; under one, + * its extension lines run parallel to the arc's bisector, and its own arc runs about the center + * outside the arc, or is the arc moved along the bisector inside it. The marks, the text and its + * break are an angular dimension's; the arc symbol is a half circle before the text, or an arc over + * it. + */ +function arcLengthPicture( + dimension: ArcLengthDimension, + style: DimensionStyle, + textStyle: DimensionFont | undefined, +): DimensionPicture { + const { radius, start, sweep, first, second } = arcLengthArc(dimension); + const { arcCenter, arcRadius, arcStart, arcSweep, footStart, footEnd } = + arcLengthOwnArc(dimension); + const measurement = radius * sweep * RADIANS; + const move = (from: Point, by: Point, distance: number): Point => [ + from[0] + by[0] * distance, + from[1] + by[1] * distance, + ]; + const sizes = dimensionSizes(style); + const size = sizes.arrowSize; + const gap = sizes.textGap; + const info = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD); + const stroke = info?.stroke; + const tick = stroke !== undefined; + const middle = start + sweep / 2; + const extension = (p: Point, q: Point): readonly [Point, Point] => { + const length = Math.hypot(q[0] - p[0], q[1] - p[1]); + const way: Point = + length > 0 ? [(q[0] - p[0]) / length, (q[1] - p[1]) / length] : direction(start); + return [move(p, way, sizes.extensionOffset), move(q, way, sizes.extensionBeyond)]; + }; + const extensionLines = [extension(first, footStart), extension(second, footEnd)]; + const arcEnd = arcStart + arcSweep; + const polar = (degrees: number, distance: number): Point => { + const [x, y] = direction(degrees); + return [arcCenter[0] + x * distance, arcCenter[1] + y * distance]; + }; + + const [aboveText, belowText] = arcLengthTexts(dimension, measurement, style); + const font = textStyle?.font ?? STANDARD_FONT; + const value = belowText === undefined ? aboveText : `${aboveText}\\P${belowText}`; + const layout = layoutDimensionText({ + value: mtextOfLabel(value), + height: sizes.textHeight, + font, + widthFactor: written(textStyle?.widthFactor ?? 1), + obliqueAngle: written(textStyle?.obliqueAngle ?? 0), + align: "center", + valign: "middle", + }); + const textWidth = layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + const half = (layout.frame[3] - layout.frame[1]) / 2; + const centered = style.textPlacement === "centered"; + const symbol = style.arcSymbol ?? "before"; + + const sizeChord = size > 0 ? (2 * Math.asin(Math.min(1, size / (2 * arcRadius)))) / RADIANS : 0; + const closed = !tick && size > 0; + const chord = closed ? sizeChord : 0; + // The text and its break stand on the bisector of the arc measured. + const arcMiddle = middle; + const lineMiddle = polar(arcMiddle, arcRadius); + const rotation = readable(arcMiddle - 90); + const quarter = direction(rotation); + const above: Point = + rotation % 90 === 0 + ? [-quarter[1], quarter[0]] + : [-Math.sin(rotation * RADIANS), Math.cos(rotation * RADIANS)]; + // Along the text, the angle about its own arc grows when the text reads against the arc's way. + const against = Math.abs(((((rotation - (arcMiddle - 90)) % 360) + 540) % 360) - 180) > 90; + // A centered text and its symbol before it need the arc's room together. + const symbolWidth = (style.arcSymbol ?? "before") === "before" ? 3.6 * half : 0; + const room = angularRoom(arcRadius, arcSweep, textWidth + 2 * symbolWidth, style); + const flipped = + size > 0 && (closed ? centered || style.textFit === "leader" : centered) && !room.marks; + const arc = (from: number, to: number): DimensionArc => ({ + center: arcCenter, + radius: arcRadius, + start: ((from % 360) + 360) % 360, + end: ((to % 360) + 360) % 360, + }); + const dimensionArcs: DimensionArc[] = []; + if (flipped) { + dimensionArcs.push( + arc(arcStart - chord - sizeChord, arcStart - chord), + arc(arcEnd + chord, arcEnd + chord + sizeChord), + arc(arcStart, arcEnd), + ); + } else if (centered && belowText === undefined) { + // The break reaches a gap past the text, and past the symbol on the side it stands. + const before = symbol === "before" ? 3.6 * half : 0; + const opening = (along: number): number => Math.asin(Math.min(1, along / arcRadius)) / RADIANS; + const [left, right] = [opening(gap + textWidth / 2 + before), opening(gap + textWidth / 2)]; + const [low, high] = against ? [left, right] : [right, left]; + // The break stands about the middle of the dimension's own arc. + const breakMiddle = arcStart + arcSweep / 2; + dimensionArcs.push( + arc(arcStart + chord, breakMiddle - low), + arc(breakMiddle + high, arcEnd - chord), + ); + } else { + dimensionArcs.push(arc(arcStart + chord, arcEnd - chord)); + } + const textMiddle = + centered || belowText !== undefined ? lineMiddle : move(lineMiddle, above, gap + half); + // The arc symbol, in the text's own frame: x along it from its middle, y up it. + const inText = (x: number, y: number): Point => move(move(textMiddle, quarter, x), above, y); + if (symbol === "before") { + dimensionArcs.push({ + center: inText(-textWidth / 2 - 2 * half, -0.8 * half), + radius: 1.6 * half, + start: ((rotation % 360) + 360) % 360, + end: (((rotation + 180) % 360) + 360) % 360, + }); + } else if (symbol === "above") { + // Through two points beside the text's top and one above its middle. + const lean = Math.atan2(1.575, 1.5) / RADIANS; + dimensionArcs.push({ + center: inText(0, 0.025 * half), + radius: 2.175 * half, + start: (((rotation + lean) % 360) + 360) % 360, + end: (((rotation + 180 - lean) % 360) + 360) % 360, + }); + } + + const arrowheads: Point[][] = []; + const arrowheadEntities: ArrowheadEntity[] = []; + const arrow = (degrees: number, turn: 1 | -1): void => { + if (!(size > 0)) return; + const tip = polar(degrees, arcRadius); + if (tick) { + const pointing = (((degrees + turn * 90) % 360) + 360) % 360; + const way = direction(pointing); + arrowheadEntities.push({ + kind: "insert", + block: info!.block!, + at: tip, + rotation: pointing, + scale: size, + }); + const halfStroke = move( + move([0, 0], way, stroke.to[0] * size), + [-way[1], way[0]], + stroke.to[1] * size, + ); + const wide = (stroke.width * size) / 2 / Math.SQRT2; + const edge: Point = [(way[0] + way[1]) * wide, (way[1] - way[0]) * wide]; + arrowheads.push([ + [tip[0] - halfStroke[0] + edge[0], tip[1] - halfStroke[1] + edge[1]], + [tip[0] + halfStroke[0] + edge[0], tip[1] + halfStroke[1] + edge[1]], + [tip[0] + halfStroke[0] - edge[0], tip[1] + halfStroke[1] - edge[1]], + [tip[0] - halfStroke[0] - edge[0], tip[1] - halfStroke[1] - edge[1]], + ]); + return; + } + const base = polar(degrees - turn * chord, arcRadius); + const length = Math.hypot(tip[0] - base[0], tip[1] - base[1]); + const way: Point = [(tip[0] - base[0]) / length, (tip[1] - base[1]) / length]; + const left: Point = [-way[1], way[0]]; + arrowheads.push([tip, move(base, left, size / 6), move(base, left, -size / 6)]); + arrowheadEntities.push({ + kind: "solid", + corners: [move(base, left, size / 6), move(base, left, -size / 6), tip], + }); + }; + arrow(arcStart, flipped ? 1 : -1); + arrow(arcEnd, flipped ? -1 : 1); + + const textStyleName = style.textStyle; + const at: Point = [written(dimension.at[0]), written(dimension.at[1])]; + return { + measurement, + definitionPoint: at, + extensionLines, + dimensionLine: [polar(arcStart, arcRadius), polar(arcEnd, arcRadius)], + dimensionLines: [], + leader: [], + dimensionArcs, + arrowheads, + arrowheadEntities, + label: { + value, + at: move(textMiddle, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction: quarter, + ...(textStyleName === undefined ? {} : { style: textStyleName }), + }, + textMiddle, + textPoint: textMiddle, + textWidth, + lineweights: { + dimension: lineweightCode(style.dimensionLineweight), + extension: lineweightCode(style.extensionLineweight), + }, + }; +} + +/** What is wrong with an arc length dimension in its style, or undefined. */ +function arcLengthDrawnProblem( + dimension: ArcLengthDimension, + style: DimensionStyle, + textStyle: TextStyle | undefined, +): string | undefined { + const { radius, sweep, reach } = arcLengthArc(dimension); + if (!(written(dimension.radius) > 0) || !(radius > 0) || !(sweep > 0) || sweep >= 360) + return ARC_LENGTH_NO_ARC; + if (!(reach > 0)) return ARC_LENGTH_NO_REACH; + // The arc's ends are written with 6 decimals, which moves the radius by as much. + if (Math.abs(reach - radius) <= 1e-6 * Math.max(1, radius)) return ARC_LENGTH_ON_ARC; + // Inside an arc under a right angle, the leading CAD app's own arc stops short of an extension + // line by an amount not laid out. + if (sweep < RIGHT_ANGLE_UNDER && reach < radius) return ARC_LENGTH_INSIDE_SHORT; + if (dimension.textBelow !== undefined && (style.arcSymbol ?? "before") !== "none") + return ARC_LENGTH_SYMBOL_BELOW; + if (style.textPlacement === "centered" && dimension.textBelow !== undefined) + return ANGULAR_CENTERED_BELOW; + const size = dimensionSizes(style).arrowSize; + const closed = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.stroke === undefined; + const picture = arcLengthPicture(dimension, style, textStyle); + const own = picture.dimensionArcs[0]!; + if (closed && size >= 2 * own.radius) return ANGULAR_ARROWS_LONG; + for (const piece of picture.dimensionArcs) { + if (arcProblem(piece.start, piece.end)) return ANGULAR_ARC_LOST; + } + // The room on its own arc, with a symbol before the text counted on both sides of it. + const { arcRadius, arcSweep } = arcLengthOwnArc(dimension); + const layout = layoutDimensionText({ + value: mtextOfLabel(picture.label.value), + height: dimensionSizes(style).textHeight, + font: textStyle?.font ?? STANDARD_FONT, + widthFactor: written(textStyle?.widthFactor ?? 1), + obliqueAngle: written(textStyle?.obliqueAngle ?? 0), + align: "center", + valign: "middle", + }); + const half = (layout.frame[3] - layout.frame[1]) / 2; + const symbolWidth = (style.arcSymbol ?? "before") === "before" ? 3.6 * half : 0; + const room = angularRoom(arcRadius, arcSweep, picture.textWidth + 2 * symbolWidth, style); + if (style.textFit === "leader" && !room.text) return ANGULAR_TEXT_OUT; + const chord = + closed && size > 0 ? (2 * Math.asin(Math.min(1, size / (2 * arcRadius)))) / RADIANS : 0; + // A centered text breaks the arc, and each piece must run on from its mark to the text. + // The pieces of its own arc: all its arcs but the symbol, which comes last. + const pieces = picture.dimensionArcs.length - ((style.arcSymbol ?? "before") === "none" ? 0 : 1); + if (style.textPlacement === "centered" && pieces === 2) { + const gap = dimensionSizes(style).textGap; + const opening = (along: number): number => Math.asin(Math.min(1, along / arcRadius)) / RADIANS; + const widest = opening(gap + picture.textWidth / 2 + symbolWidth); + if (widest + chord > arcSweep / 2 + 1e-9) return ANGULAR_CENTERED_SHORT; + } + // Turned outward, the marks and their tails must stay clear of each other round the back. + if (pieces === 3) { + const tail = (2 * Math.asin(Math.min(1, size / (2 * arcRadius)))) / RADIANS; + if (arcSweep + 2 * ((closed ? tail : 0) + tail) >= 360) return ANGULAR_TAILS_MEET; + } + // What it reads is held to the digits a length's writing holds. + const scaled = picture.measurement * written(style.measurementScale ?? 1); + const digits = dimensionMeasureProblem( + picture.measurement, + scaled, + roundedMeasurement(picture.measurement, style), + true, + picture.label.value, + undefined, + ); + if (digits) return digits; + return pictureNumbersProblem(picture); +} + +/** What an arc length dimension draws above its arc and below it, as `dimensionTexts` for a line. */ +function arcLengthTexts( + dimension: ArcLengthDimension, + length: number, + style: DimensionStyle, +): readonly [above: string, below: string | undefined] { + return dimensionTexts(dimension, length, style); +} + /** * The widest a character of any font in `FONTS` is drawn, as a share of the text's height, * before its style's width factor: for the characters of a measurement, the widest the leading CAD @@ -1640,6 +2030,8 @@ export function dimensionDrawnProblem( if (isRadial(dimension)) return radialDrawnProblem(dimension, measurement, style, textStyle); if (dimension.kind === "angular-dimension") return angularDrawnProblem(dimension, style, textStyle); + if (dimension.kind === "arc-length-dimension") + return arcLengthDrawnProblem(dimension, style, textStyle); // The arrowheads need room for the wider of the texts above and below the line. const [above, below] = dimensionTexts(dimension, measurement, style); let drawn = above; diff --git a/src/drawing.ts b/src/drawing.ts index 476fb3e..459f90c 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -19,6 +19,7 @@ import { type DIMENSION_TEXT_FITS, type DIMENSION_RADIAL_TEXTS, type DIMENSION_ANGLE_UNITS, + type DIMENSION_ARC_SYMBOLS, type FEET_INCH_ZEROS, type LeaderArrowhead, type ZERO_SUPPRESSIONS, @@ -657,6 +658,28 @@ export interface AngularDimension extends Placed { readonly textBelow?: string; } +/** + * An arc length dimension: the length of the arc about `center` of `radius`, counterclockwise from + * `startAngle` to `endAngle` in degrees, as `d.arc` takes them, its own arc through `at`. Under a + * right angle its extension lines run parallel to the arc's bisector; from one up they run along + * radii. The arc symbol stands before its text, above it or nowhere, as its style says. + */ +export interface ArcLengthDimension extends Placed { + readonly kind: "arc-length-dimension"; + /** A dimension style of the drawing. */ + readonly style: string; + readonly center: Point; + readonly radius: number; + readonly startAngle: number; + readonly endAngle: number; + /** A point the dimension's own arc passes through. */ + readonly at: Point; + /** A text to draw in place of the measurement, as a linear dimension's `text`. */ + readonly text?: string; + /** Words drawn under its arc, opposite the text, as a linear dimension's `textBelow`. */ + readonly textBelow?: string; +} + /** Which side of the point where its shafts meet a leader's note is on. */ export type LeaderSide = (typeof LEADER_SIDES)[number]; @@ -827,6 +850,7 @@ export type Entity = | DiameterDimension | JoggedRadiusDimension | AngularDimension + | ArcLengthDimension | Leader | Image | Hatch @@ -993,6 +1017,11 @@ export interface DimensionStyle { * the text's box grown by a quarter of its height. Defaults to none. */ readonly textMask?: boolean | { readonly color: number }; + /** + * Where an arc length dimension draws the arc symbol: `"before"` its text, the default, + * `"above"` it, or `"none"`. + */ + readonly arcSymbol?: (typeof DIMENSION_ARC_SYMBOLS)[number]; } /** @@ -1856,6 +1885,11 @@ export interface DimensionStyleDefinition< * the text's box grown by a quarter of its height. Defaults to none. */ readonly textMask?: boolean | { readonly color: number }; + /** + * Where an arc length dimension draws the arc symbol: `"before"` its text, the default, + * `"above"` it, or `"none"`. + */ + readonly arcSymbol?: (typeof DIMENSION_ARC_SYMBOLS)[number]; } /** What every dimension is drawn with. */ @@ -1921,6 +1955,13 @@ export type DiameterDimensionOptions< I extends string = string, > = RadiusDimensionOptions; +/** The options of `arcLengthDimension()`. */ +export type ArcLengthDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, +> = DimensionOptions; + /** The options of `angularDimension()`. */ export type AngularDimensionOptions< S extends string = string, @@ -3802,7 +3843,7 @@ export class DrawingBuilder< const { prefix, suffix, suppressZeros, feetInchZeros } = definition; const { fraction, fractionScale, textPlacement, textFit } = definition; const { dimensionLineweight, extensionLineweight, radialText, jogAngle, textMask } = definition; - const { angleUnits, anglePrecision, suppressAngleZeros } = definition; + const { angleUnits, anglePrecision, suppressAngleZeros, arcSymbol } = definition; const units = definition.units ?? "decimal"; const scale = definition.scale ?? 1; const measurementScale = definition.measurementScale ?? 1; @@ -3837,6 +3878,7 @@ export class DrawingBuilder< ...(textMask === undefined || textMask === false ? {} : { textMask: textMask === true ? true : { color: textMask.color } }), + ...(arcSymbol === undefined || arcSymbol === "before" ? {} : { arcSymbol }), }); this.#dimensionStylesAudited.set(layerAuditKey(named), named); } @@ -4010,6 +4052,41 @@ export class DrawingBuilder< ); } + /** + * Draws an arc length dimension on the current layer: the length of the arc about `center` of + * `radius`, counterclockwise from `startAngle` to `endAngle` in degrees, as `arc` takes them, + * with its own arc through `at`. + */ + arcLengthDimension( + center: Point, + radius: number, + startAngle: number, + endAngle: number, + at: Point, + options: Z extends Standard + ? StandardAlignedDimensionOptions + : V extends "R12" + ? R12Dimensions + : ArcLengthDimensionOptions, + ): this { + return this.#add(DrawingBuilder.prototype.arcLengthDimension, idOf(options), () => + this.#dimension( + options as unknown as ArcLengthDimensionOptions | undefined, + (style, text) => ({ + kind: "arc-length-dimension", + layer: this.#current, + style, + center: pt(center), + radius: kept(radius, "radius"), + startAngle: kept(startAngle, "startAngle"), + endAngle: kept(endAngle, "endAngle"), + at: pt(at), + ...text, + }), + ), + ); + } + /** A radius or a diameter dimension, with its text where `options.textFromCenter` says. */ #radial( kind: K, @@ -4179,6 +4256,7 @@ export class DrawingBuilder< ...(fields.suppressAngleZeros === undefined ? {} : { suppressAngleZeros: fields.suppressAngleZeros }), + ...(fields.arcSymbol === "before" ? {} : { arcSymbol: fields.arcSymbol }), }); return this.#dimensionStyles.get(layerKey(name))!; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 57653d8..7c562e3 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -11,6 +11,7 @@ import { DEFAULT_ARROWHEAD, DEFAULT_LEADER_ARROWHEAD, DIMENSION_ANGLE_UNITS, + DIMENSION_ARC_SYMBOLS, JOG_ANGLE, leaderArrowheadInfo, type LeaderArrowheadStroke, @@ -18,6 +19,7 @@ import { import { arrowheadEntityHandle, arrowheadsWithBlocks, + arcLengthArc, dimensionAngle, dimensionFileText, dimensionMeasure, @@ -228,6 +230,16 @@ export function toDXFR2018( entity: true, }); } + // So is an arc length dimension. + const arcLengths = [drawing.entities, ...sheets.map((sheet) => sheet.layout.entities)] + .flat() + .filter((e) => e.kind === "arc-length-dimension").length; + if (arcLengths > 0) { + writeClass(g, "ARC_DIMENSION", "AcDbArcDimension", "ObjectDBX Classes", 1025, { + count: arcLengths, + entity: true, + }); + } // A multileader and its style are objects of classes, which a drawing that has them lists. if (leaderStyles.length > 0) { writeClass(g, "MLEADERSTYLE", "AcDbMLeaderStyle", "ACDB_MLEADERSTYLE_CLASS", 4095, { @@ -1328,6 +1340,8 @@ function writeDimensionStyle(g: Group, style: DimensionStyle, textStyle: string) ); // DIMZIN const angleZeros = style.suppressAngleZeros; if (angleZeros !== undefined) g(79, ANGLE_ZERO_CODES[angleZeros]); // DIMAZIN + const arcSymbol = style.arcSymbol ?? "before"; + if (arcSymbol !== "before") g(90, DIMENSION_ARC_SYMBOLS.indexOf(arcSymbol)); // DIMARCSYM g(140, style.textHeight); // DIMTXT g(144, style.measurementScale ?? 1); // DIMLFAC if (style.fractionScale !== undefined) g(146, style.fractionScale); // DIMTFAC @@ -1376,12 +1390,19 @@ function writeDimension( ? e.center : e.kind === "linear-dimension" ? e.line - : e.kind === "angular-dimension" + : e.kind === "angular-dimension" || e.kind === "arc-length-dimension" ? e.at : e.to; const picture = drawn ?? { definitionPoint: at, textPoint: at }; const jogged = e.kind === "jogged-radius-dimension"; - g(0, jogged ? "LARGE_RADIAL_DIMENSION" : "DIMENSION"); + g( + 0, + jogged + ? "LARGE_RADIAL_DIMENSION" + : e.kind === "arc-length-dimension" + ? "ARC_DIMENSION" + : "DIMENSION", + ); g(5, handle); g(330, owner); g(100, "AcDbEntity"); @@ -1401,6 +1422,21 @@ function writeDimension( // itself, and keeps the picture the file holds. if (style) g(42, measurementValue(e, style)); g(3, style?.name ?? e.style); + if (e.kind === "arc-length-dimension") { + // The arc's ends, its center, no part of it alone, its angles in radians, and no leader. + const { center, first, second, start, sweep } = arcLengthArc(e); + g(100, "AcDbArcDimension"); + point(g, 13, ...first); + point(g, 14, ...second); + point(g, 15, ...center); + g(70, 0); + g(40, fifteenDigits((start * Math.PI) / 180)); + g(41, fifteenDigits((((start + sweep) % 360) * Math.PI) / 180)); + g(71, 0); + point(g, 16, ...first); + point(g, 17, ...second); + return; + } if (e.kind === "angular-dimension") { g(100, "AcDb3PointAngularDimension"); point(g, 13, ...e.from); @@ -1475,6 +1511,7 @@ const DIMENSION_TYPES = { "radius-dimension": 4, "jogged-radius-dimension": 9, "angular-dimension": 5, + "arc-length-dimension": 5, } as const; /** The block of a dimension's picture, with what the writer needs for it. */ diff --git a/src/extents.ts b/src/extents.ts index 219b531..dae6c4f 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -339,6 +339,7 @@ export function boxer( case "diameter-dimension": case "jogged-radius-dimension": case "angular-dimension": + case "arc-length-dimension": dimension(e, from, add); break; case "leader": { diff --git a/src/index.ts b/src/index.ts index ecb047a..e4e350b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,7 @@ export { ARROWHEADS, DEFAULT_LEADER_ARROWHEAD, DIMENSION_ANGLE_UNITS, + DIMENSION_ARC_SYMBOLS, DIMENSION_FRACTIONS, DIMENSION_RADIAL_TEXTS, DIMENSION_TEXT_FITS, @@ -30,6 +31,7 @@ export { export type { CallSite } from "./callsite.ts"; export { angleNumber, + arcLengthArc, arrowheadHandles, dimensionArcPoints, dimensionAngle, @@ -82,6 +84,8 @@ export { type JoggedRadiusDimensionOptions, type AngularDimension, type AngularDimensionOptions, + type ArcLengthDimension, + type ArcLengthDimensionOptions, type InsertOptions, type Layer, type LayerOptions, @@ -373,6 +377,7 @@ export { type ReadDimension, type ReadRadialDimension, type ReadAngularDimension, + type ReadArcLengthDimension, type ReadDimensionStyle, type ReadDrawingFile, type ReadEntity, diff --git a/src/inspect.ts b/src/inspect.ts index b8f75a4..3a1403c 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -602,6 +602,7 @@ function looked( case "diameter-dimension": case "jogged-radius-dimension": case "angular-dimension": + case "arc-length-dimension": case "leader": return true; default: diff --git a/src/lint.ts b/src/lint.ts index 7db14b5..ac054d7 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -532,6 +532,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) case "diameter-dimension": case "jogged-radius-dimension": case "angular-dimension": + case "arc-length-dimension": cost += long1(e.style) + long1(e.text) + long1(e.textBelow); break; case "leader": @@ -2345,7 +2346,8 @@ function costsBoxes(e: Readonly>): boolean { kind === "radius-dimension" || kind === "diameter-dimension" || kind === "jogged-radius-dimension" || - kind === "angular-dimension" + kind === "angular-dimension" || + kind === "arc-length-dimension" ); } @@ -2438,6 +2440,16 @@ function geometryProblems(e: Entity): string[] { case "angular-dimension": finite("its points", ...e.vertex, ...e.from, ...e.to, ...e.at); break; + case "arc-length-dimension": + finite( + "its points, radius and angles", + ...e.center, + e.radius, + e.startAngle, + e.endAngle, + ...e.at, + ); + break; case "leader": finite("its point", ...e.at); break; diff --git a/src/read/check.ts b/src/read/check.ts index e9625e8..e75c4f1 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -198,6 +198,24 @@ const ENTITY: Readonly> = { "block?": "string", "blockHandle?": "string", }, + "arc-length-dimension": { + ...BASE, + kind: { oneOf: ["arc-length-dimension"] }, + center: "point", + radius: "number", + startAngle: "number", + endAngle: "number", + at: "point", + textAt: "point", + "placed?": "boolean", + "partial?": "boolean", + "measurement?": "number", + "text?": "string", + "textBelow?": "string", + style: "string", + "block?": "string", + "blockHandle?": "string", + }, "angular-dimension": { ...BASE, kind: { oneOf: ["angular-dimension"] }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 04501af..52f30cd 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -190,6 +190,7 @@ const BLOCK_READS = new Set([ "IMAGE", "INSERT", "LARGE_RADIAL_DIMENSION", + "ARC_DIMENSION", "LEADER", "LINE", "LWPOLYLINE", @@ -210,6 +211,7 @@ const SPACE_READS = new Set([ "IMAGE", "INSERT", "LARGE_RADIAL_DIMENSION", + "ARC_DIMENSION", "MTEXT", "POLYLINE", "SEQEND", @@ -1123,7 +1125,8 @@ class DxfReader { return; } case "DIMENSION": - case "LARGE_RADIAL_DIMENSION": { + case "LARGE_RADIAL_DIMENSION": + case "ARC_DIMENSION": { if (!space) return; const style = name(r, 3) ?? "Standard"; const dstyle = xdata(r, "ACAD"); @@ -1775,7 +1778,8 @@ class DxfReader { entity.kind !== "insert" && entity.kind !== "dimension" && entity.kind !== "radial-dimension" && - entity.kind !== "angular-dimension" + entity.kind !== "angular-dimension" && + entity.kind !== "arc-length-dimension" ) continue; const block = entity.block; diff --git a/src/read/entities.ts b/src/read/entities.ts index da31357..9284954 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -9,6 +9,7 @@ import type { ReadDimension, ReadRadialDimension, ReadAngularDimension, + ReadArcLengthDimension, ReadEntity, ReadEntityBase, ReadHatchLoop, @@ -229,6 +230,8 @@ export function readingOf( case "DIMENSION": case "LARGE_RADIAL_DIMENSION": return dimension(r, base, face, r12); + case "ARC_DIMENSION": + return arcLengthDimension(r, base, face); case "MULTILEADER": return multileader(r, base, later); case "LEADER": @@ -704,6 +707,49 @@ function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolea return { entity }; } +/** + * An arc length dimension: its center (group 15), the radius to the arc's first end (13), the arc's + * angles (40 and 41, after the common group 70, in radians), a point of its own arc (10), and + * whether it measures part of the arc (the second group 70). + */ +function arcLengthDimension(r: Rec, base: ReadEntityBase, face: Facing): Reading { + if (face !== 1) + return { other: face === -1 ? "ARC_DIMENSION seen from below" : "ARC_DIMENSION in 3D" }; + const center = point(r, 15); + const end = point(r, 13); + // The arc's own groups follow its subclass marker: the common part holds a 41 and a 70 too. + const marker = r.codes.findIndex((code, i) => code === 100 && r.values[i] === "AcDbArcDimension"); + const after = (code: number): string | undefined => { + const at = marker < 0 ? -1 : r.codes.indexOf(code, marker); + return at < 0 ? undefined : r.values[at]; + }; + const partial = after(70); + const degrees = (code: number): number => { + const value = Number(after(code) ?? 0) * (180 / Math.PI); + return Number.isFinite(value) ? value : 0; + }; + const text = first(r, 1); + const block = name(r, 2); + const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); + const entity: ReadArcLengthDimension = { + ...base, + kind: "arc-length-dimension", + center, + radius: Math.hypot(end[0] - center[0], end[1] - center[1]), + startAngle: degrees(40), + endAngle: degrees(41), + at: point(r, 10), + textAt: point(r, 11), + ...(((num(r, 70) ?? 0) & 128) !== 0 && { placed: true }), + ...(partial !== undefined && Number(partial) !== 0 && { partial: true }), + measurement: num(r, 42) ?? 1, + ...parts, + style: name(r, 3) ?? "Standard", + ...(block !== undefined && block !== "" && { block }), + }; + return { entity }; +} + /** * An angular dimension by two lines (group 70's kind 2), 13 to 14 and 15 to 10, its arc through * 16, or by three points (5), its vertex 15, its lines through 13 and 14, its arc through 10. @@ -964,6 +1010,7 @@ export function costOf(e: ReadEntity): number { case "radial-dimension": return own + 5 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "angular-dimension": + case "arc-length-dimension": return own + 6 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "multileader": { let points = 3; diff --git a/src/read/model.ts b/src/read/model.ts index 1849ecf..e03df74 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -482,6 +482,33 @@ export interface ReadAngularDimension extends ReadEntityBase { readonly blockHandle?: string; } +/** + * An arc length dimension: the length of the arc about `center` of `radius` from `startAngle` to + * `endAngle`, counterclockwise in degrees, as the file holds the arc. + */ +export interface ReadArcLengthDimension extends ReadEntityBase { + readonly kind: "arc-length-dimension"; + readonly center: Point; + readonly radius: number; + readonly startAngle: number; + readonly endAngle: number; + /** A point its own arc passes through. */ + readonly at: Point; + /** The middle of its text. */ + readonly textAt: Point; + /** True where the file holds its text where it was placed, not where the leading CAD app puts it. */ + readonly placed?: boolean; + /** True where it measures part of the arc, from points of its own. */ + readonly partial?: boolean; + /** What it measures, as the file states it, as `ReadDimension`'s. */ + readonly measurement?: number; + readonly text?: string; + readonly textBelow?: string; + readonly style: string; + readonly block?: string; + readonly blockHandle?: string; +} + /** One root of a multileader: where some of its shafts meet, and the landing from there. */ export interface ReadLeaderRoot { /** Where its shafts meet and its landing starts. */ @@ -676,6 +703,7 @@ export type ReadEntity = | ReadDimension | ReadRadialDimension | ReadAngularDimension + | ReadArcLengthDimension | ReadMultileader | ReadLeader | ReadSolid diff --git a/src/rules.ts b/src/rules.ts index ed05722..a7f4dcc 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -15,6 +15,7 @@ import { DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, DIMENSION_ANGLE_UNITS, + DIMENSION_ARC_SYMBOLS, MAX_ANGLE_PRECISION, JOG_ANGLE, DIMENSION_TEXT_PLACEMENTS, @@ -3064,6 +3065,13 @@ export function radialTextProblem(value: unknown): string | undefined { : RADIAL_TEXT_MESSAGE; } +/** Returns what is wrong with a dimension style's `arcSymbol`, or undefined. */ +export function arcSymbolProblem(value: unknown): string | undefined { + return (DIMENSION_ARC_SYMBOLS as readonly unknown[]).includes(value) + ? undefined + : 'arcSymbol must be "before", "above" or "none"'; +} + /** Returns what is wrong with a dimension style's `angleUnits`, or undefined. */ export function angleUnitsProblem(value: unknown): string | undefined { return (DIMENSION_ANGLE_UNITS as readonly unknown[]).includes(value) @@ -3137,6 +3145,7 @@ export function dimensionStyleLookProblem(s: Record): string | if (problem) return problem; } for (const [field, problemOf] of [ + ["arcSymbol", arcSymbolProblem], ["angleUnits", angleUnitsProblem], ["anglePrecision", anglePrecisionProblem], ["suppressAngleZeros", angleZerosProblem], @@ -3256,6 +3265,26 @@ export const ANGULAR_NO_ARC = export const ANGULAR_ARC_ON_POINT = "its arc passes through one of its two points, where the leading CAD app runs that point's extension line toward the vertex or away from it by a rounding, which is not laid out yet, so tsdraft refuses it. Move the arc's point nearer the vertex or further from it"; +/** An arc length dimension with no arc to measure. */ +export const ARC_LENGTH_NO_ARC = + "it measures no arc: its radius is 0 or less, or its two angles are one once its ends are written with the 6 decimals tsdraft writes"; + +/** An arc length dimension whose own arc's point is its center. */ +export const ARC_LENGTH_NO_REACH = + "its arc's point is its center once they are written with the 6 decimals tsdraft writes, so its own arc has no radius"; + +/** An arc length dimension whose own arc runs on the arc it measures. */ +export const ARC_LENGTH_ON_ARC = + "its own arc's point is on the arc it measures, where the leading CAD app runs its extension lines toward the center or away from it by a rounding, which is not laid out yet, so tsdraft refuses it. Move the point further from the arc"; + +/** An arc length dimension inside an arc under a right angle. */ +export const ARC_LENGTH_INSIDE_SHORT = + "its own arc inside an arc under a right angle is not laid out yet, so tsdraft refuses it. Put its point outside the arc"; + +/** An arc length dimension with words below and its arc symbol. */ +export const ARC_LENGTH_SYMBOL_BELOW = + 'its words below the arc with the arc symbol is not laid out yet, so tsdraft refuses it. Use a style with arcSymbol "none"'; + /** An angular dimension whose arc, or a piece of it, is all but a whole turn. */ export const ANGULAR_ARC_LOST = "its arc, or a piece of it, runs all but a whole turn, so its two angles are one once they are written with the 6 decimals tsdraft writes, and the leading CAD app draws such an arc as nothing"; @@ -3264,6 +3293,10 @@ export const ANGULAR_ARC_LOST = export const ANGULAR_ARROWS_LONG = "its closed arrowheads are as long as its arc is wide or longer, which is not laid out yet, so tsdraft refuses it. Move the arc's point further from the vertex, or use a smaller arrow size"; +/** A dimension whose marks, turned outward, and their tails would meet round the back of its arc. */ +export const ANGULAR_TAILS_MEET = + "its marks turn outward where its arc is too short for its text, and they and their tails would meet round the back of the arc, which is not laid out yet, so tsdraft refuses it. Use a smaller arrow size, or move the arc's point further out"; + /** An angular dimension whose arc's point lies on one of its lines. */ export const ANGULAR_ARC_ON_LINE = "its arc's point is on one of its two lines, where the leading CAD app takes the angle between them or the rest of the turn by a rounding, which is not laid out yet, so tsdraft refuses it. Move the arc's point into the angle it measures"; diff --git a/src/shape.ts b/src/shape.ts index 796b0c6..2d74575 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -24,6 +24,7 @@ import type { DiameterDimension, JoggedRadiusDimension, AngularDimension, + ArcLengthDimension, Linetype, Paragraph, Polyline, @@ -544,6 +545,19 @@ function shapes(all: boolean, typed = all): Shapes { { kind, layer: string, style: ruled(string), center: point, point, start: point, jog: point }, { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, ), + "arc-length-dimension": fields( + { + kind, + layer: string, + style: ruled(string), + center: point, + radius: number, + startAngle: number, + endAngle: number, + at: point, + }, + { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + ), "angular-dimension": fields( { kind, @@ -703,6 +717,7 @@ function shapes(all: boolean, typed = all): Shapes { suppressAngleZeros: ruled(string), // true, false or an object: the rule reports any other. textMask: LEFT, + arcSymbol: ruled(string), }, ), ); diff --git a/src/standard/document.ts b/src/standard/document.ts index 4923c67..acf0c66 100644 --- a/src/standard/document.ts +++ b/src/standard/document.ts @@ -7,6 +7,7 @@ import type { DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, DIMENSION_ANGLE_UNITS, + DIMENSION_ARC_SYMBOLS, DIMENSION_TEXT_PLACEMENTS, DIMENSION_UNITS, FEET_INCH_ZEROS, @@ -204,6 +205,7 @@ export interface DimensionStyleFieldsDocument extends Commented { readonly angleUnits?: string; readonly anglePrecision?: number; readonly suppressAngleZeros?: string; + readonly arcSymbol?: string; readonly writing?: { readonly [U in Units]?: WritingDocument }; readonly description?: string; } @@ -387,6 +389,7 @@ export interface StandardDimensionStyleFields { readonly angleUnits?: (typeof DIMENSION_ANGLE_UNITS)[number]; readonly anglePrecision?: number; readonly suppressAngleZeros?: (typeof ZERO_SUPPRESSIONS)[number]; + readonly arcSymbol?: (typeof DIMENSION_ARC_SYMBOLS)[number]; readonly writing?: { readonly [U in Units]?: StandardWriting }; readonly description?: string; } @@ -407,6 +410,7 @@ export interface StandardDimensionStyle { readonly angleUnits: (typeof DIMENSION_ANGLE_UNITS)[number]; readonly anglePrecision: number; readonly suppressAngleZeros?: (typeof ZERO_SUPPRESSIONS)[number]; + readonly arcSymbol: (typeof DIMENSION_ARC_SYMBOLS)[number]; readonly writing: { readonly [U in Units]?: StandardWriting }; /** Its name in the leading CAD app on a layout, when it is not its id in capitals. */ readonly layoutName?: string; diff --git a/src/standard/lint.ts b/src/standard/lint.ts index c49308d..37c3055 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -372,6 +372,7 @@ export function lintStandard( style.suppressAngleZeros ?? "none", fields.suppressAngleZeros ?? "none", ], + ["arcSymbol", style.arcSymbol ?? "before", fields.arcSymbol], ["dimensionLineweight", style.dimensionLineweight, fields.dimensionLineweight], ["extensionLineweight", style.extensionLineweight, fields.extensionLineweight], ]; diff --git a/src/standard/literal.ts b/src/standard/literal.ts index bec2861..f548967 100644 --- a/src/standard/literal.ts +++ b/src/standard/literal.ts @@ -5,6 +5,7 @@ import type { DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, DIMENSION_ANGLE_UNITS, + DIMENSION_ARC_SYMBOLS, DIMENSION_TEXT_PLACEMENTS, ZERO_SUPPRESSIONS, } from "../arrowheads.ts"; @@ -342,13 +343,15 @@ type StyleFields = { ? Str> : F extends "angleUnits" ? Str> - : F extends "suppressAngleZeros" - ? Str> - : F extends "writing" - ? { readonly [U in keyof E[F]]: Writing } - : F extends "discipline" - ? Discipline - : unknown; + : F extends "arcSymbol" + ? Str> + : F extends "suppressAngleZeros" + ? Str> + : F extends "writing" + ? { readonly [U in keyof E[F]]: Writing } + : F extends "discipline" + ? Discipline + : unknown; }; type DimensionStyle = { diff --git a/src/standard/shape.ts b/src/standard/shape.ts index a40f532..fb39a1d 100644 --- a/src/standard/shape.ts +++ b/src/standard/shape.ts @@ -11,6 +11,7 @@ import { DIMENSION_TEXT_FITS, DIMENSION_RADIAL_TEXTS, DIMENSION_ANGLE_UNITS, + DIMENSION_ARC_SYMBOLS, MAX_ANGLE_PRECISION, JOG_ANGLE, DIMENSION_TEXT_PLACEMENTS, @@ -35,6 +36,7 @@ import { angleUnitsProblem, anglePrecisionProblem, angleZerosProblem, + arcSymbolProblem, textPlacementProblem, blockNameProblem, dimensionPrefixProblem, @@ -560,6 +562,12 @@ const STYLE_FIELDS = { node: string({ enum: ZERO_SUPPRESSIONS }, angleZerosProblem), description: "The zeros an angle leaves out. Defaults to none", }, + arcSymbol: { + node: string({ enum: DIMENSION_ARC_SYMBOLS }, arcSymbolProblem), + description: + "Where an arc length dimension draws the arc symbol: before its text, above it, or nowhere", + default: "before", + }, textFit: { node: string({ enum: DIMENSION_TEXT_FITS }, textFitProblem), description: diff --git a/standard.json b/standard.json index c7eb93c..3b8ae5e 100644 --- a/standard.json +++ b/standard.json @@ -268,6 +268,7 @@ "jogAngle": 45, "angleUnits": "degrees", "anglePrecision": 0, + "arcSymbol": "before", "textFit": "inside", "writing": { "in": { @@ -308,6 +309,7 @@ "jogAngle": 45, "angleUnits": "degrees", "anglePrecision": 0, + "arcSymbol": "before", "textFit": "inside", "writing": { "in": { @@ -347,6 +349,7 @@ "jogAngle": 45, "angleUnits": "degrees", "anglePrecision": 0, + "arcSymbol": "before", "textFit": "inside", "writing": { "in": { diff --git a/standard.schema.json b/standard.schema.json index e434d36..6a1ec1b 100644 --- a/standard.schema.json +++ b/standard.schema.json @@ -339,6 +339,12 @@ "enum": ["leading", "trailing", "both"], "description": "The zeros an angle leaves out. Defaults to none" }, + "arcSymbol": { + "type": "string", + "enum": ["before", "above", "none"], + "description": "Where an arc length dimension draws the arc symbol: before its text, above it, or nowhere", + "default": "before" + }, "textFit": { "type": "string", "enum": ["inside", "leader"], @@ -474,6 +480,11 @@ "enum": ["leading", "trailing", "both"], "description": "The zeros an angle leaves out. Defaults to none" }, + "arcSymbol": { + "type": "string", + "enum": ["before", "above", "none"], + "description": "Where an arc length dimension draws the arc symbol: before its text, above it, or nowhere" + }, "textFit": { "type": "string", "enum": ["inside", "leader"], diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 16344e8..5d4d3d5 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2100,6 +2100,22 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint textBelow: pick([long, "A\\P".repeat(5_000)]), })), ); + // Arc length ones: a sliver of an arc or most of a turn, its own arc near or far. + (pick([drawing, layout]).entities as Data[]).push( + ...Array.from({ length: pick([1, 300]) }, (_, i): Data => ({ + kind: "arc-length-dimension", + layer: "0", + style: style.name, + center: [0, i], + radius: pick([0.01, 10, 1e9]), + startAngle: pick([0, 30, 359.9999]), + endAngle: pick([0.0001, 120, 359]), + at: [pick([0.02, 15, 1e9]), i + pick([0.0001, 3, -2])], + text: pick(["<>", long]), + textBelow: pick([long, "A\\P".repeat(5_000)]), + })), + ); + style.arcSymbol = pick(["before", "above", "none"]); style.radialText = pick(["aligned", "horizontal"]); style.jogAngle = pick([5, 45, 90]); style.angleUnits = pick(["degrees", "degrees-minutes-seconds", "grads", "radians"]); diff --git a/test/dimensions.test.ts b/test/dimensions.test.ts index a2f3a70..941c2ed 100644 --- a/test/dimensions.test.ts +++ b/test/dimensions.test.ts @@ -807,7 +807,7 @@ test("a dimension is written with its style, its points and the block of its pic dimensionLines: ["14E64A214426A5", "1A23E71AA31D32", "1A22E71AA31F7D", "1A25E71AA31254"], leader: ["1C6E99C485049E", "1C7199C48501B7"], belowText: "1A5AD40549288F", - dimensionArcs: ["1FAB45DF867869", "1FAC45DF867AA4", "1FAD45DF867CF3"], + dimensionArcs: ["1FAB45DF867869", "1FAC45DF867AA4", "1FAD45DF867CF3", "1FA645DF8670D6"], }); assert.equal(dimensionPictureHandles({ index: 1 }).record, "16DCBD6115A74B"); assert.equal(dimensionPictureHandles({ index: 0, layout: "a-101" }).record, "1D645DAA891E34"); @@ -1264,3 +1264,135 @@ test("a style's text mask is kept by the builder, written, plotted and boxed", ( )[3]; assert.ok(top(masked(true)) > top(masked()), `${top(masked(true))} ${top(masked())}`); }); + +test("an arc length dimension is built, written and read back, with the arc symbol before its text", async () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + d.dimensionStyle({ ...sizes, name: "BARE", arcSymbol: "none" }); + d.arcLengthDimension([0, 0], 10, 30, 120, [0, 13], { style: "S", id: "l" }); + d.arcLengthDimension( + [20, 0], + 10, + 30, + 60, + [20 + 13 * Math.cos(Math.PI / 4), 13 * Math.sin(Math.PI / 4)], + { + style: "BARE", + text: "<> TYP.", + }, + ); + const drawing = d.build(); + assert.deepEqual(lint(drawing), []); + assert.deepEqual(fromJSON(toJSON(drawing)), drawing); + const style = drawing.dimensionStyles![0]!; + const picture = dimensionPicture(drawing.entities[0] as never, style); + assert.equal(picture.label.value, "15.71"); + // The symbol is a half circle before the text, the last of its arcs. + assert.equal(picture.dimensionArcs.length, 2); + const read = await readDXF(toDXF(drawing), { geometry: true }); + const arcs = (read.model.entities ?? []).filter((e) => e.kind === "arc-length-dimension"); + assert.deepEqual( + arcs.map((e) => [ + e.center, + Number(e.radius.toFixed(6)), + Math.round(e.startAngle), + Math.round(e.endAngle), + ]), + [ + [[0, 0], 10, 30, 120], + [[20, 0], 10, 30, 60], + ], + ); + assert.equal(Number(arcs[0]!.measurement!.toFixed(6)), Number(((10 * Math.PI) / 2).toFixed(6))); + assert.equal(arcs[1]!.text, "<> TYP."); + // A right angle about a far center, whose ends' decimals put it a hair under, runs along radii. + const far = createDrawing({ units: "in" }); + far.dimensionStyle({ ...sizes, name: "S" }); + far.arcLengthDimension([1000, 2000], 10, 2, 92, [1000, 2013], { style: "S" }); + const farDrawing = far.build(); + const [from, to] = dimensionPicture(farDrawing.entities[0] as never, style).extensionLines[0]!; + const [cx, cy] = [1000, 2000]; + assert.ok( + Math.abs((from[0] - cx) * (to[1] - from[1]) - (from[1] - cy) * (to[0] - from[0])) < 1e-6, + ); +}); + +test("an arc length dimension is refused where the leading CAD app would draw what tsdraft does not", () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + assert.throws( + () => d.arcLengthDimension([0, 0], 10, 30, 30, [0, 13], { style: "S" }), + /measures no arc/, + ); + assert.throws( + () => d.arcLengthDimension([0, 0], 10, 30, 120, [0, 0], { style: "S" }), + /no radius/, + ); + assert.throws( + () => d.arcLengthDimension([0, 0], 10, 30, 120, [0, 10], { style: "S" }), + /on the arc it measures/, + ); + // Inside an arc under a right angle. + assert.throws( + () => d.arcLengthDimension([0, 0], 10, 30, 60, [5, 5], { style: "S" }), + /inside an arc under a right angle/, + ); + // Words below with the symbol. + assert.throws( + () => d.arcLengthDimension([0, 0], 10, 30, 120, [0, 13], { style: "S", textBelow: "MIN." }), + /with the arc symbol/, + ); + assert.throws( + () => d.arcLengthDimension([0, 0], -10, 0, 90, [0, 13], { style: "S" }), + /0 or less/, + ); + // A centered text too wide for its arc, with no marks to turn. + d.dimensionStyle({ + ...sizes, + name: "BARE", + arrowSize: 0, + textPlacement: "centered", + arcSymbol: "none", + }); + assert.throws( + () => d.arcLengthDimension([0, 0], 1, 0, 10, [1.3, 0.11], { style: "BARE", text: "VERIFY" }), + /too short for its text "centered"/, + ); + // A text too wide for its own arc, which "leader" moves outside. + d.dimensionStyle({ + ...sizes, + name: "OUT", + textFit: "leader", + textHeight: 0.125, + arcSymbol: "none", + }); + assert.throws( + () => + d.arcLengthDimension([0, 0], 10, 0, 5, [25, 1], { style: "OUT", text: "VERIFY IN FIELD" }), + /too short for its text/, + ); + // Ticks longer than the arc is wide, turned outward, whose tails would meet round the back. + d.dimensionStyle({ + ...sizes, + name: "TICKS", + arrowhead: "architectural-tick", + textPlacement: "centered", + textHeight: 0.125, + arrowSize: 0.25, + textGap: 0.04, + }); + assert.throws( + () => d.arcLengthDimension([0, 0], 0.25, 0, 270, [0.1, 0], { style: "TICKS", text: "VERIFY" }), + /meet round the back/, + ); + // More digits than a measurement's writing holds. + d.dimensionStyle({ ...sizes, name: "LONG", precision: 8, measurementScale: 304.8 }); + assert.throws( + () => d.arcLengthDimension([0, 0], 25000, 0, 90, [0, 26000], { style: "LONG" }), + /16 digits/, + ); + assert.throws( + () => d.dimensionStyle({ ...sizes, name: "BAD", arcSymbol: "after" as never }), + /arcSymbol must be "before", "above" or "none"/, + ); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index 90ae724..c363563 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -7,6 +7,7 @@ import { placeAttribute } from "../src/blocks.ts"; import { dimensionAngle, + arcLengthArc, dimensionMeasure, dimensionPicture, isDimension, @@ -445,6 +446,37 @@ export function readProblems( } return; } + case "arc-length-dimension": { + if (!kind("arc-length-dimension") || got.kind !== "arc-length-dimension") return; + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + const arc = arcLengthArc(want); + const turn = (a: number, b: number): number => + Math.abs(((((a - b) % 360) + 540) % 360) - 180); + if ( + !nearPoint(got.center, arc.center) || + Math.abs(got.radius - arc.radius) > 1e-6 || + turn(got.startAngle, arc.start) > 1e-6 || + turn(got.endAngle, arc.start + arc.sweep) > 1e-6 + ) { + say( + `${label}: about ${got.center} of ${got.radius}, ${got.startAngle} to ${got.endAngle}`, + ); + } + if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { + say(`${label}: text ${JSON.stringify(got.text)}`); + } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; + const measurement = + dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); + if ( + got.measurement === undefined || + Math.abs(got.measurement - measurement) > 1e-9 * Math.max(1, Math.abs(measurement)) + ) { + say(`${label}: measures ${got.measurement}, expected ${measurement}`); + } + return; + } case "angular-dimension": { if (!kind("angular-dimension") || got.kind !== "angular-dimension") return; if (got.type !== "three-point") say(`${label}: ${got.type}, expected three-point`); diff --git a/test/shape.test.ts b/test/shape.test.ts index 0e4c939..c2e0cc6 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -246,6 +246,19 @@ const kinds: { textBelow: "CURB", id: "h-j", }, + "arc-length-dimension": { + kind: "arc-length-dimension", + layer: "0", + style: "ARCH", + center: [0, 0], + radius: 10, + startAngle: 30, + endAngle: 120, + at: [0, 12], + text: "<> TYP", + textBelow: "MIN.", + id: "h-l", + }, "angular-dimension": { kind: "angular-dimension", layer: "0", @@ -357,6 +370,7 @@ const full: Required & { anglePrecision: 4, suppressAngleZeros: "leading", textMask: { color: 3 }, + arcSymbol: "above", }, { name: "ARCH", @@ -386,6 +400,7 @@ const full: Required & { anglePrecision: 0, suppressAngleZeros: "both", textMask: true, + arcSymbol: "none", }, ], leaderStyles: [ @@ -673,7 +688,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #17: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #18: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ From 42f2ab14d1654097247d81b43af9b3c8ecde27f2 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 14:33:00 -0500 Subject: [PATCH 15/35] Hatch patterns from a firm's pattern file: written, read and plotted as CAD programs draw them Hatch patterns, in R2018 drawings. - `parsePatterns(text)` reads a pattern file in the format CAD programs read: a pattern starts at `*NAME, description`, and each line after it is `angle, x, y, dx, dy` and its dashes. `d.patterns(file)` adds a firm's patterns to a drawing, and `Drawing.patterns` holds them. tsdraft ships no patterns of its own. - `d.hatch(boundary, { pattern: { name, scale?, angle?, origin? } })` hatches with one of the drawing's patterns. `{ spacing, angle?, crossed?, origin? }` draws lines of the hatch's own, `spacing` apart, crossed by as many square to them when `crossed`. - Both writers write a pattern's lines placed, scaled and turned as CAD programs hold them, and `toSVG` and `toPDF` draw each dash and dot cut to the hatch's loops where CAD programs plot it. - `readDXF` reads a hatch's pattern: its type, angle, scale, whether it is crossed, and its lines as the file holds them, so a firm's patterns can also come from its drawings. - `lint` and the builder refuse a pattern that is not one of the drawing's, a scale or spacing that is not greater than 0, a name and a spacing together, two patterns of one name (`duplicate-hatch-pattern`), a pattern line whose family has no spacing, and a hatch that would draw more than 1,000,000 lines (`hatch-pattern`). The builder's types catch a zero scale or spacing, and a name with a spacing. - [Patterns](docs/fills.md#patterns) describes them. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 7 +- CHANGELOG.md | 11 ++ GUIDE.md | 5 +- README.md | 16 ++- cli/src/omit.ts | 7 +- docs/fills.md | 79 ++++++++++- docs/format.md | 8 +- docs/plotting.md | 6 +- docs/reading.md | 9 +- docs/rules.md | 14 +- src/dimensions.ts | 11 +- src/drawing.ts | 232 +++++++++++++++++++++++++++++++- src/dxf-r2018.ts | 29 +++- src/fills.ts | 276 +++++++++++++++++++++++++++++++++++++- src/index.ts | 10 ++ src/lint.ts | 198 +++++++++++++++++++++++++++- src/patterns.ts | 298 ++++++++++++++++++++++++++++++++++++++++++ src/polylines.ts | 11 ++ src/read/check.ts | 9 ++ src/read/entities.ts | 56 +++++++- src/read/model.ts | 23 ++++ src/rules.ts | 215 +++++++++++++++++++++++++++++- src/shape.ts | 27 +++- src/svg.ts | 111 +++++++++++++++- test/bounded.test.ts | 65 +++++++++ test/patterns.test.ts | 191 +++++++++++++++++++++++++++ test/read.test.ts | 28 ++++ test/rules.test.ts | 136 +++++++++++++++++++ test/shape.test.ts | 13 ++ 29 files changed, 2047 insertions(+), 54 deletions(-) create mode 100644 src/patterns.ts create mode 100644 test/patterns.test.ts diff --git a/AGENTS.md b/AGENTS.md index 6fdb709..f677207 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -378,7 +378,12 @@ and factor, a paragraph's and a dimension style's. The writers, `toSVG`, the extents, `lint` and the readers take them from it. The wipeout frame is the dictionary variable `WIPEOUTFRAME`, which is what that app reads, beside `WIPEOUTVARIABLES`, which it does not. A hatch is drawn as one path - with `fill-rule="evenodd"`, which `toPDF` writes as `f*`. + with `fill-rule="evenodd"`, which `toPDF` writes as `f*`. tsdraft ships no hatch pattern: a + firm's pattern file gives them. A hatch finds its pattern by `layerKey` of its name, the first of + a name, and `patternDrawnProblem` is the one check of what its lines draw, which `lint`, the + builder and `toSVG` share: a pattern that would draw more than `HATCH_LINES` lines across the + box of its loops, or place a number of 1e100 or more, is refused, and `toSVG` draws none of its + lines. - `src/pdf.ts` plots layouts to PDF from the pictures `toSVG` draws of them, and decides nothing about a drawing: every rule of what a sheet plots stays in `toSVG`, so the preview and the plot cannot part. It reads the closed set of elements and attributes `toSVG` writes diff --git a/CHANGELOG.md b/CHANGELOG.md index f2db539..5f8dde6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,17 @@ or a loop of fewer than 3 points, or 2 joined by an arc; a wipeout of fewer than 3 points, on one line or with sides that cross; and a mask of another shape. `LeaderMask` is now `TextMask`, which a leader's and a paragraph's mask share. +- Hatch patterns, in R2018 drawings. tsdraft has no patterns of its own: `parsePatterns(text)` + reads a firm's pattern file, and `d.patterns()` adds its patterns, or definitions given as data, + to the drawing's `patterns`. A hatch's `pattern` names one, with its `scale`, `angle` and + `origin`, or draws lines of its own `spacing` apart at its `angle`, `crossed` by as many more. + `toDXF` writes the lines each hatch draws, and `toSVG` and `toPDF` draw them and their dashes cut + to its loops, as CAD programs plot them. `readDXF` and `readDWG` read a hatch's `patternType`, + `patternAngle`, `patternScale`, `crossed` and `patternLines`, so a firm's patterns can be read + back from its drawings. `lint` and the builder refuse, under the rule `hatch-pattern`, a hatch + that names a pattern the drawing does not have, a scale or spacing not greater than 0, a + pattern's definition that cannot be written, and a hatch whose pattern would draw more than + 1,000,000 lines across its loops; two patterns of one name are a `duplicate-hatch-pattern`. - `readDXF` and `readDWG` read a hatch, its loops of polylines or of lines and arcs as points and bulges, its pattern and its island style; a wipeout; an `MTEXT`'s background mask; the order a file's sort table draws a space or a block in, `drawOrder`; and whether wipeouts' frames show, diff --git a/GUIDE.md b/GUIDE.md index 2de5c35..1bf6bc3 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -68,7 +68,8 @@ inside it, and `donut` a filled ring or dot. [docs/polylines.md](docs/polylines. folder for the pictures, and warns of one that is missing. [docs/images.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/images.md) has them. `hatch` fills one outline, or a list of loops `{ points, bulges? }` where a loop inside another is -a hole, solid in the layer's color; `wipeout` hides what is drawn before it behind a polygon; and +a hole, solid in the layer's color, or with `pattern` draws a pattern `patterns()` added from the +firm's pattern file, or lines `spacing` apart; `wipeout` hides what is drawn before it behind a polygon; and a paragraph's `mask: true` hides what is drawn before it behind its text. Draw a fill before the lines over it. [docs/fills.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/fills.md) has them. @@ -622,7 +623,7 @@ writeFileSync("plan.dxf", toDXF(drawing)); ## What tsdraft cannot draw yet -- Hatches, fills, and angular, arc length and ordinate dimensions. +- Gradient fills, and angular, arc length and ordinate dimensions. - A block read from another file. A block is drawn in the drawing that inserts it. An xref references a whole DWG file, as an overlay, and the pictures draw it only from a drawing you give. diff --git a/README.md b/README.md index 88437d6..0aedb6a 100644 --- a/README.md +++ b/README.md @@ -198,8 +198,9 @@ toPDF(drawing, { images: { "aerial.png": readFileSync("aerial.png") } }); [Images](docs/images.md) has clips, frames and transparency, and what `lint` refuses. -A hatch fills the area inside its loops solid, a loop inside another a hole. A wipeout hides what -is drawn before it, and a paragraph's mask hides it behind the text: +A hatch fills the area inside its loops solid, a loop inside another a hole, or draws a pattern +of the firm's pattern file there. A wipeout hides what is drawn before it, and a paragraph's mask +hides it behind the text: ```ts d.hatch([ @@ -223,8 +224,8 @@ d.hatch([ d.paragraph("VERIFY IN FIELD", { at: [40, 20], height: 3, mask: true }); ``` -[Fills, wipeouts and masks](docs/fills.md) has holes and arcs, wipeouts' frames, a dimension -style's mask and the draw order. +[Fills, wipeouts and masks](docs/fills.md) has holes and arcs, patterns, wipeouts' frames, a +dimension style's mask and the draw order. A dimension measures between two points and writes what it measures. In the file it is a dimension, which a CAD program measures again when its points move, and a dimension style says how @@ -302,7 +303,7 @@ feet and inches with stacked fractions, words below the line and text on a leade layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have overlines in paragraph text, ellipses, splines or points, hatch patterns or gradients, tables, color or transparency set on one +It does not yet have overlines in paragraph text, ellipses, splines or points, gradients, tables, color or transparency set on one entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit @@ -408,8 +409,9 @@ lint(drawing, { version: "R12" }); // check a drawing against another version value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, transparency, how the plot draws one, and what `lint` refuses. -- [Fills, wipeouts and masks](docs/fills.md) covers solid hatches with holes, wipeouts, the - masks of paragraphs, leaders and dimensions, the draw order, and what `lint` refuses. +- [Fills, wipeouts and masks](docs/fills.md) covers hatches with holes, solid or of a pattern + file's patterns, wipeouts, the masks of paragraphs, leaders and dimensions, the draw order, and + what `lint` refuses. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. - [Xrefs](docs/xrefs.md) covers references to DWG files: the path, units, a diff --git a/cli/src/omit.ts b/cli/src/omit.ts index aa2c735..4a2498d 100644 --- a/cli/src/omit.ts +++ b/cli/src/omit.ts @@ -10,8 +10,8 @@ export const LEFT_OUT: Entity = { kind: "polyline", layer: "", points: [], close /** * The drawing without the items at `items`, which are the `item` paths of `lint`'s diagnostics: * an entry of a list, such as `layers[1]`, `blocks[0]` or `blocks[0].attributes[2]`, an entity, - * such as `entities[3]` or `blocks[0].entities[1]`, a whole list, such as `xrefs` or - * `dimensionStyles` or `leaderStyles`, or + * such as `entities[3]` or `blocks[0].entities[1]`, a whole list, such as `xrefs`, + * `dimensionStyles`, `leaderStyles` or `patterns`, or * `linetypeScale`. A layout is left out whole, or keeps what is left of it: `layouts[0]`, * `layouts[0].viewports[1]`, `layouts[0].entities[2]`. */ @@ -53,6 +53,7 @@ export function without(drawing: Drawing, items: ReadonlySet): Drawing { }); const { linetypes, + patterns, textStyles, dimensionStyles, leaderStyles, @@ -62,7 +63,7 @@ export function without(drawing: Drawing, items: ReadonlySet): Drawing { linetypeScale, ...rest } = drawing; - const lists = { linetypes, textStyles, dimensionStyles, leaderStyles, xrefs }; + const lists = { linetypes, patterns, textStyles, dimensionStyles, leaderStyles, xrefs }; return { ...rest, layers: kept(drawing.layers, "layers") ?? [], diff --git a/docs/fills.md b/docs/fills.md index 4220eca..70d5666 100644 --- a/docs/fills.md +++ b/docs/fills.md @@ -2,7 +2,8 @@ A solid fill is a hatch: an area filled in its pen's color, which CAD programs hold as one entity a drafter selects, edits and measures as one. Wall poché, filled arrowheads, bar dots and the filled -parts of symbols are hatches. A wipeout is a polygon filled with the paper's color, which hides +parts of symbols are hatches. A hatch with a pattern draws the pattern's lines inside its loops +instead, as for concrete, earth or brick. A wipeout is a polygon filled with the paper's color, which hides what is drawn before it. A mask hides what is drawn before a text, behind the text's box: a paragraph, a leader's note and a dimension's text each take one. @@ -61,7 +62,74 @@ A hatch is filled in its layer's color, with no outline whatever its lineweight. as a polyline of its own where the sheet shows one. In a block, an insert's scale and rotation place a hatch as they place the rest of the block, and a negative scale mirrors it. -Hatch patterns, a firm's own pattern file and gradients come later. A hatch today is solid. +Gradients come later. + +## Patterns + +A hatch with a `pattern` draws a pattern's lines in its pen in place of the solid fill. tsdraft has +no patterns of its own: a firm's patterns are its pattern file, the `.pat` file CAD programs read. +`parsePatterns(text)` reads one into `HatchPattern`s, and `d.patterns()` adds them to the drawing, +from the file's text or a list of definitions. A hatch then names one, whatever the case of its +letters, as a layer names a linetype: + +```ts +import { readFileSync } from "node:fs"; + +const d = createDrawing({ units: "in" }); +d.patterns(readFileSync("firm.pat", "utf8")); +d.layer("A-WALL-PATT", { color: 8 }, () => + d.hatch( + [ + [0, 0], + [96, 0], + [96, 8], + [0, 8], + ], + { pattern: { name: "AR-CONC", scale: 0.5, angle: 45, origin: [0, 0] } }, + ), +); +``` + +`scale` multiplies every length of the pattern, `angle` turns it, in degrees counterclockwise, and +`origin` is the point its lines start from; they are 1, 0 and `[0, 0]` unless given. A pattern of +a name the drawing has replaces it and keeps the first spelling, as `linetype()` does, and of two +of one name in one call the first is added, as CAD programs read a pattern file. A drawing written +by hand holds its patterns in `Drawing.patterns`, and a hatch takes the first of a name. + +A pattern is families of parallel lines. In a pattern file a pattern starts at a line +`*NAME, description`, and each line after it is `angle, x, y, dx, dy` and its dashes: the family's +line runs through the base point `x, y` at `angle`, the next line of the family lies `dx` along it +and `dy` across it, and its dashes repeat along it from the base point, a positive length drawn, a +negative one left out and 0 a dot. A `;` starts a comment. A `HatchPattern` holds the same, +`{ name, description?, lines }`, with each line `{ angle, base, offset, dashes? }` and no dashes for +a solid line. + +Lines of the hatch's own need no pattern: `{ spacing, angle?, crossed?, origin? }` draws lines +`spacing` apart at `angle`, and with `crossed: true` as many more square to them: + +```ts +d.hatch(slab, { pattern: { spacing: 0.25, angle: 45, crossed: true } }); +``` + +`lint` and the builder refuse a hatch that names a pattern the drawing does not have, a `scale` or +`spacing` not greater than 0 or written as 0, a `name` and a `spacing` together, and `crossed` with +a name. They refuse a pattern whose name breaks the rules of a linetype's name, with no line or more +than 32,767, a line whose offset across it rounds to 0 at 6 decimals, more than 32,767 dashes on a +line or dashes all 0, and two patterns of one name. A hatch whose pattern would draw more than +1,000,000 lines across the box of its loops is refused, as is one whose lines, scaled, turned and +moved to its origin, hold a number of 1e100 or more: give it a larger scale or spacing. + +`toSVG` and `toPDF` draw the lines cut to the loops, inside an odd number of them as a solid hatch +is filled, as the leading CAD app plots them. Each line's dashes count from its base point, a dot +is a round end of no length, and where a line runs along a side of a loop the side is drawn alone. + +`readDXF` and `readDWG` read a hatch's pattern back: `pattern` is its name, `_U` for lines of its +own, `patternType` is 0 for lines of its own, 1 for a pattern CAD programs ship and 2 for one of a +file, and `patternAngle`, `patternScale`, the spacing of lines of its own, and `crossed` are as the +file holds them. `patternLines` holds each line as the file holds it, placed in the drawing: its +angle with the pattern's added, its base point scaled, turned and moved to the origin, its offset +scaled and turned to the line, and its dashes scaled. A firm's patterns can be read back from its +drawings this way. ## Wipeouts @@ -125,7 +193,12 @@ gives, `drawOrder`. ## In the file A hatch is a `HATCH` of the pattern `SOLID`, with island detection normal and each loop a -polyline path. A wipeout is a `WIPEOUT`, a square picture of one pixel clipped by its polygon, and +polyline path. A hatch with a pattern holds its lines instead: group 2 its pattern's name, or `_U` +for lines of its own, 70 0, 76 its type, 2 for a pattern of the drawing's and 0 for lines of its +own, 52 its angle, 41 its scale or its spacing, 77 1 where its lines are crossed, and 78 the +number of its lines. Each line follows, placed in the drawing: 53 its angle, 43 and 44 its base +point, 45 and 46 its offset, 79 the number of its dashes and a 49 for each dash, with 15 +significant digits. A wipeout is a `WIPEOUT`, a square picture of one pixel clipped by its polygon, and the drawing holds `WIPEOUTVARIABLES` and the dictionary variable `WIPEOUTFRAME`, which is what CAD programs read of whether frames show. A mask is the background of an `MTEXT`, and a dimension style's is its `DIMTFILL` and `DIMTFILLCLR` and the background of the `MTEXT` of its picture. diff --git a/docs/format.md b/docs/format.md index e4e36d6..5e6fec1 100644 --- a/docs/format.md +++ b/docs/format.md @@ -97,8 +97,12 @@ A drawing with no image has the JSON it had before images existed. [Images](imag them. A hatch is an entity of kind `"hatch"`, with its `layer` and its `loops`, each `{ points }` and -where a side is an arc its `bulges`, one for each side, and the `linetype` and `lineweight` of -every entity. A wipeout is an entity of kind `"wipeout"`, with its `layer` and its `points`. +where a side is an arc its `bulges`, one for each side, its `pattern` where it is not solid, and +the `linetype` and `lineweight` of every entity. A pattern is `{ name }` of one of the drawing's +`patterns`, with its `scale`, `angle` and `origin` where they are set, or `{ spacing }` of lines +of its own, with its `angle`, `crossed` and `origin`. `patterns` on the drawing holds its hatch +patterns, each `{ name, description, lines }` and each line `{ angle, base, offset, dashes }`, the +dashes where it has them. A wipeout is an entity of kind `"wipeout"`, with its `layer` and its `points`. `wipeoutFrame: false` on the drawing hides every wipeout's frame. A paragraph's `mask` and a dimension style's `textMask` are written where they are set. A drawing with none of them has the JSON it had before they existed. [Fills, wipeouts and masks](fills.md) describes them. diff --git a/docs/plotting.md b/docs/plotting.md index 57f5c24..689bc98 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -65,9 +65,9 @@ preview shows it: dashes as [How it plots](polylines.md#how-it-plots) says. - An image is drawn from its file's bytes, given as `images`, clipped to its clip, with its frame in its pen, and the PDF holds each file once, as [Plotting](images.md#plotting) says. -- A hatch is filled by the parity of its loops, a wipeout and a mask in the paper's white or a - mask's color, each over what is drawn before it, as [Fills, wipeouts and - masks](fills.md) says. +- A hatch is filled by the parity of its loops, or draws its pattern's lines and dashes cut to + them, a wipeout and a mask in the paper's white or a mask's color, each over what is drawn + before it, as [Fills, wipeouts and masks](fills.md) says. - Each layer is a layer of the PDF too, by the name the picture gives it, `XREF|LAYER` for a layer of an xref, so a PDF viewer lists the layers and can hide one. - Each page has a bookmark and a page label with its layout's name. diff --git a/docs/reading.md b/docs/reading.md index 2fa2e0e..a7e82be 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -171,7 +171,14 @@ leader: and arcs is read as points and bulges, a whole circle as two half circles. CAD programs fill a hatch of style `normal` by the parity of all its loops, one of style `outer` by the parity of those marked external or outermost, and one of style `ignore` by the external ones. A hatch - bounded by an ellipse or a spline is counted under `other`, as is one out of the plane. + bounded by an ellipse or a spline is counted under `other`, as is one out of the plane. One that + is not solid holds its `patternType`, 0 for user-defined lines, named `_U`, 1 for a pattern CAD + programs ship and 2 for one of a file, its `patternAngle`, its `patternScale`, which is the + spacing of user-defined lines, `crossed` for user-defined lines crossed by as many more, and + `patternLines`, each `{ angle, base, offset, dashes? }` as the file holds it: placed in the + drawing, with the pattern's angle added, the base point scaled, turned and moved to the origin, + and the offset and dashes scaled, the offset turned to the line. [Patterns](fills.md#patterns) + says how a firm's patterns are read back this way. - `wipeout`: its `points` in the world's coordinates, without the first again at the end. - An `mtext` with a background holds `mask`: its `offsetFactor`, and its `color` or `trueColor` where it is not in the drawing's background. diff --git a/docs/rules.md b/docs/rules.md index 369e1f5..7d50590 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -62,6 +62,17 @@ it would take `1e+100` for `1e+10` and report nothing. `{ color?, offsetFactor? }`, a color from 1 to 256 and a factor from 1 to 5, as a leader's is, on a paragraph without columns, and a dimension style's `textMask` is `true`, `false` or `{ color }`. [Fills, wipeouts and masks](fills.md) has the rest. +- A hatch pattern of the drawing's `patterns` has a name that follows the rules of a linetype's + name, a description of one line, and 1 to 32,767 lines, each with an angle, a base point and an + offset of finite numbers under 1e100, an offset across the line that does not round to 0 at 6 + decimals, and at most 32,767 dashes under 1e100, not all 0. Two patterns of one name, whatever + the case of its letters, are a `duplicate-hatch-pattern` error, and a hatch takes the first. A + hatch's `pattern` names one of them other than `SOLID`, which a solid hatch leaves the pattern + out for, or gives a `spacing` for lines of its own, not both; its + `scale` and `spacing` are greater than 0 and not written as 0, `crossed` goes with a spacing + alone, and its `angle` and `origin` are finite. The lines it places hold no number of 1e100 or + more, and it draws at most 1,000,000 lines across the box of its loops. The rule of these is + `hatch-pattern`. [Patterns](fills.md#patterns) has the rest. - Arc angles are stored from 0 up to 360, so -90 becomes 270. An arc cannot come within 0.000001 degrees of a full turn, because its two angles would be written the same and the leading CAD app holds such an arc as having no length. Draw a @@ -248,7 +259,8 @@ it would take `1e+100` for `1e+10` and report nothing. field and a field of the wrong type, it gives an error with the path to the value, such as `entities[3].from must be a point, [x, y]`. The rule is `linetype`, `text-style`, `block` or `attribute` for a value in that list, `xref` for one in `xrefs`, `dimension-style` for one - in `dimensionStyles`, `leader-style` for one in `leaderStyles`, `layout` for a layout, + in `dimensionStyles`, `leader-style` for one in `leaderStyles`, `hatch-pattern` for one in + `patterns`, `layout` for a layout, `viewport` for a viewport, and `format` for the rest, which an entity of a sheet is. No other rule is checked on an object of the wrong shape, and what names it gets no error for that. An object that a drawing made in code shares among many places is reported where it diff --git a/src/dimensions.ts b/src/dimensions.ts index 39b6a21..fe0d42a 100644 --- a/src/dimensions.ts +++ b/src/dimensions.ts @@ -33,6 +33,7 @@ import { import { written } from "./format.ts"; import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; +import { direction } from "./polylines.ts"; import { arrowRoomProblem, DIMENSION_CENTERED_WIDE, @@ -686,16 +687,6 @@ export function dimensionMeasure(dimension: Dimension): { return { angle, measurement: Math.abs((x2 - x1) * cos + (y2 - y1) * sin) }; } -/** The unit vector at an angle in degrees, exact along the axes. */ -function direction(degrees: number): Point { - const quarter = ((degrees % 360) + 360) % 360; - if (quarter === 0) return [1, 0]; - if (quarter === 90) return [0, 1]; - if (quarter === 180) return [-1, 0]; - if (quarter === 270) return [0, -1]; - return [Math.cos(degrees * RADIANS), Math.sin(degrees * RADIANS)]; -} - /** * What the leading CAD app draws for a dimension in a style, for a dimension and a style the rules * have passed. The dimension line runs through the definition point along the direction measured. diff --git a/src/drawing.ts b/src/drawing.ts index 459f90c..7c79e38 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -58,7 +58,16 @@ import { } from "./papers.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; import { arcsAlong, cloud, donut, MAX_CLOUD_ARCS, rounded } from "./polylines.ts"; -import { onOneLine, polygonCrosses } from "./fills.ts"; +import { + hatchSpread, + loopsBox, + onOneLine, + patternDrawnProblem, + patternSizes, + polygonCrosses, + type PatternSizes, +} from "./fills.ts"; +import { parsePatterns } from "./patterns.ts"; import { imageVectors } from "./images.ts"; import { canonical } from "./json.ts"; import { DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; @@ -215,6 +224,10 @@ import { type LEADER_VERTICAL_ATTACHMENTS, HATCH_LOOP_POINTS, HATCH_NO_LOOPS, + hatchPatternChoiceProblem, + hatchPatternProblem, + shown, + undefinedHatchPatternProblem, textMaskProblem, PARAGRAPH_MASK_COLUMNS, WIPEOUT_CROSSES, @@ -814,15 +827,62 @@ export interface HatchLoop { readonly bulges?: readonly number[]; } +/** One line of a pattern's definition, in its file's units. */ +export interface PatternLine { + /** Degrees counterclockwise. */ + readonly angle: number; + /** A point the line runs through. */ + readonly base: Point; + /** Where the next line of the family lies from this one: along the line, then across it. */ + readonly offset: Point; + /** Its dashes: a length drawn, a negative length left out, 0 a dot. Missing for a solid line. */ + readonly dashes?: readonly number[]; +} + +/** + * A hatch pattern's definition: families of parallel lines, each through its base point at its + * angle, the next one over moved by its offset, its dashes repeating from the base point. + * `parsePatterns` reads the patterns of a pattern file. + */ +export interface HatchPattern { + readonly name: string; + readonly description?: string; + readonly lines: readonly PatternLine[]; +} + /** - * A hatch: an area filled solid in its pen's color, which the leading CAD app holds as one entity - * a drafter edits and measures as one. The area inside an odd number of its loops is filled, so - * a loop inside another is a hole, and a loop inside a hole fills again. R2018 only. + * How a hatch is drawn when it is not solid: a pattern of the drawing's `patterns`, by its name, + * scaled and turned; or lines of its own, `spacing` apart at `angle`, crossed by as many square + * to them when `crossed`. `origin` is where the pattern's lines start, `[0, 0]` unless given. + */ +export type HatchPatternChoice = + | { + readonly name: string; + readonly scale?: number; + /** Degrees counterclockwise. */ + readonly angle?: number; + readonly origin?: Point; + } + | { + readonly spacing: number; + /** Degrees counterclockwise. */ + readonly angle?: number; + readonly crossed?: boolean; + readonly origin?: Point; + }; + +/** + * A hatch: an area filled solid in its pen's color, or with a pattern's lines in its pen, which + * the leading CAD app holds as one entity a drafter edits and measures as one. The area inside an + * odd number of its loops is filled, so a loop inside another is a hole, and a loop inside a hole + * fills again. R2018 only. */ export interface Hatch extends EntityBase { readonly kind: "hatch"; /** Its loops, in any order and either way round. */ readonly loops: readonly HatchLoop[]; + /** Its pattern. Missing, it is solid. */ + readonly pattern?: HatchPatternChoice; } /** @@ -1179,6 +1239,8 @@ export interface Drawing { * the leading CAD app has it. A mask behind notes wants false. */ readonly wipeoutFrame?: boolean; + /** The hatch patterns that hatches name, such as a firm's pattern file's from `parsePatterns`. */ + readonly patterns?: readonly HatchPattern[]; } /** @@ -1385,6 +1447,54 @@ export interface EntityOptions< readonly pen?: Z extends Standard ? PenOfStandard : PenWithoutStandard; } +/** + * A hatch's pattern as `hatch()` takes it: a `HatchPatternChoice` whose scale or spacing is greater + * than 0 and not written as 0, with no field of the other kind. + * + * @typeParam S - The scale or the spacing as written. + */ +export type HatchPatternOf = + | { + readonly name: string; + readonly scale?: Positive; + /** Degrees counterclockwise. */ + readonly angle?: number; + readonly origin?: Point; + readonly spacing?: never; + readonly crossed?: never; + } + | { + readonly spacing: Positive; + /** Degrees counterclockwise. */ + readonly angle?: number; + readonly crossed?: boolean; + readonly origin?: Point; + readonly name?: never; + readonly scale?: never; + }; + +/** + * The options of `hatch()`: its pattern, and the options of every entity. + * + * @typeParam S - The pattern's scale or spacing as written. + */ +export interface HatchOptions< + V extends DxfVersion = "R2018", + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, + S extends number = number, +> extends EntityOptions { + /** + * The lines it is drawn with in its pen: a pattern that `patterns()` added, by its name, with its + * `scale`, `angle` and `origin`, or lines of its own, `spacing` apart. Solid when left out. + */ + readonly pattern?: HatchPatternOf; +} + /** * How wide a polyline is drawn: the width of every side, in drawing units, 0 or more. CAD * programs fill a side that has a width, at that width whatever its pen, and draw one of width 0 @@ -2507,6 +2617,8 @@ export class DrawingBuilder< ); /** Keyed by `layerKey`: the leading CAD app compares text style names as it compares layer names. */ readonly #textStyles = new Map(); + /** Keyed by `layerKey`, with the sizes a hatch's check reads: a hatch finds its pattern so. */ + readonly #patterns = new Map(); readonly #textStylesAudited = new Map([ [layerAuditKey(STANDARD_TEXT_STYLE), STANDARD_TEXT_STYLE], ]); @@ -2601,6 +2713,62 @@ export class DrawingBuilder< return this; } + /** + * Adds hatch patterns, which a hatch names in its `pattern`: the text of a pattern file, which + * `parsePatterns` reads, or definitions. tsdraft has no patterns of its own, so pass the firm's + * file. A pattern of a name the drawing has replaces it and keeps the first spelling, as + * `linetype()` does, and of two of one name in one call the first is added, as CAD programs read + * a pattern file. Nothing is added when one is refused. A hatch is checked against its pattern + * when it is drawn; one a later pattern of its name makes too dense is left to `lint`. + * + * ```ts + * d.patterns(readFileSync("firm.pat", "utf8")); + * d.hatch(slab, { pattern: { name: "AR-CONC", scale: 0.5 } }); + * ``` + */ + patterns(file: string | readonly HatchPattern[]): this { + try { + if (this.dxf === "R12") refuse("hatch-pattern", R12_ONLY.hatches); + let given: unknown = file; + if (typeof file === "string") { + try { + given = parsePatterns(file); + } catch (thrown) { + refuse("hatch-pattern", thrown instanceof Error ? thrown.message : String(thrown)); + } + } + if (!Array.isArray(given)) { + refuse( + "hatch-pattern", + "patterns() takes a pattern file's text or a list of hatch patterns", + ); + } + const added = new Map(); + for (const definition of given as readonly unknown[]) { + const problem = hatchPatternProblem(definition); + const { name, description, lines } = (definition ?? {}) as HatchPattern; + if (problem) refuse("hatch-pattern", `Hatch pattern ${shown(name)}: ${problem}`); + const key = layerKey(name); + if (added.has(key)) continue; + const copy: HatchPattern = { + name: this.#patterns.get(key)?.[0].name ?? name, + ...(description === undefined ? {} : { description }), + lines: lines.map(({ angle, base, offset, dashes }) => ({ + angle, + base: [base[0], base[1]], + offset: [offset[0], offset[1]], + ...(dashes === undefined ? {} : { dashes: [...dashes] }), + })), + }; + added.set(key, [copy, patternSizes(copy.lines, new WeakMap())!]); + } + for (const [key, pattern] of added) this.#patterns.set(key, pattern); + } catch (thrown) { + throw located(thrown, DrawingBuilder.prototype.patterns, {}); + } + return this; + } + /** * Defines a text style, or updates the one of the same name. `notes` and `NOTES` are the * same style, and keep the first spelling. `Standard` is in every drawing, with the font @@ -3002,11 +3170,20 @@ export class DrawingBuilder< * inside a hole fills again, whichever way each runs. A loop's `bulges` make its sides arcs, as * a polyline's do. R2018 only. * + * With `pattern`, it draws a pattern's lines in its pen instead: a pattern `patterns()` added, + * by its name, or lines of its own `spacing` apart, crossed by as many square to them when + * `crossed`. A pattern that would draw more than 1,000,000 lines across the loops is refused. + * * ```ts * d.hatch([ * { points: [[0, 0], [8, 0], [8, 0.5], [0, 0.5]] }, * { points: [[3, 0], [3.5, 0], [3.5, 0.5]] }, * ]); + * d.patterns(readFileSync("firm.pat", "utf8")); + * d.hatch([[0, 1], [8, 1], [8, 3], [0, 3]], { + * pattern: { name: "AR-CONC", scale: 0.25, angle: 45, origin: [0, 1] }, + * }); + * d.hatch([[10, 1], [12, 1], [12, 3], [10, 3]], { pattern: { spacing: 0.125, crossed: true } }); * ``` */ hatch< @@ -3015,9 +3192,10 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, + S extends number = number, >( boundary: readonly Point[] | readonly HatchLoop[], - options: EntityOptions = {}, + options: HatchOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.hatch, options, () => { if (this.dxf === "R12") refuse("hatch", R12_ONLY.hatches); @@ -3042,10 +3220,49 @@ export class DrawingBuilder< if (problem) refuse("geometry", `Loop ${k}: ${problem}`); return { points, ...(bulges === undefined ? {} : { bulges: [...bulges] }) }; }); - return { kind: "hatch", layer: this.#current, loops }; + const choice: unknown = options.pattern; + return { + kind: "hatch", + layer: this.#current, + loops, + ...(choice === undefined ? {} : { pattern: this.#hatchPattern(choice, loops) }), + }; }); } + /** + * Checks a hatch's pattern as `lint` does, with the name in the drawing's spelling, and returns + * a copy of it. + */ + #hatchPattern(choice: unknown, loops: readonly HatchLoop[]): HatchPatternChoice { + const problem = hatchPatternChoiceProblem(choice); + if (problem) refuse("hatch-pattern", capitalized(problem)); + const c = choice as Record; + const angle = c.angle === undefined ? {} : { angle: c.angle as number }; + const at = c.origin as Point | undefined; + const origin = at === undefined ? {} : { origin: [at[0], at[1]] as Point }; + let found: readonly [HatchPattern, PatternSizes] | undefined; + let copy: HatchPatternChoice; + if (typeof c.name === "string") { + found = this.#patterns.get(layerKey(c.name)); + if (found === undefined) refuse("hatch-pattern", undefinedHatchPatternProblem(c.name, true)); + const scale = c.scale === undefined ? {} : { scale: c.scale as number }; + copy = { name: found![0].name, ...scale, ...angle, ...origin }; + } else { + const crossed = c.crossed === undefined ? {} : { crossed: c.crossed as boolean }; + copy = { spacing: c.spacing as number, ...angle, ...crossed, ...origin }; + } + const box = loopsBox(loops); + const spread = hatchSpread( + { pattern: copy }, + () => found?.[0], + () => found?.[1], + ); + const drawn = box && spread ? patternDrawnProblem(box, spread) : undefined; + if (drawn) refuse("hatch-pattern", capitalized(drawn)); + return copy; + } + /** * A wipeout: a polygon filled with the paper's color, which hides what is drawn before it, such * as the lines behind a note. Its frame shows as `Drawing.wipeoutFrame` says. R2018 only. @@ -5236,6 +5453,9 @@ export class DrawingBuilder< ? { dimensionStyles: [...this.#dimensionStyles.values()] } : {}), ...(this.#leaderStyles.size > 0 ? { leaderStyles: [...this.#leaderStyles.values()] } : {}), + ...(this.#patterns.size > 0 + ? { patterns: [...this.#patterns.values()].map(([pattern]) => pattern) } + : {}), }; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 7c562e3..8cbf6aa 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -52,10 +52,13 @@ import type { TextStyle, Units, Viewport, + HatchPattern, } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; import { dimensionMask, + hatchLines, + patternFinder, loopBulged, maskOf, type Mask, @@ -392,6 +395,7 @@ export function toDXFR2018( ]); // Keyed as style names are compared, so a text that names `notes` takes the style `NOTES`. const stylesByKey = new Map(textStyles.map((style) => [layerKey(style.name), style])); + const patternOf = patternFinder(drawing.patterns); const styleOf = (name: string | undefined): TextStyle | undefined => name === undefined ? undefined : stylesByKey.get(layerKey(name)); writeTable(g, handle, "VIEW", []); @@ -586,6 +590,7 @@ export function toDXFR2018( owner, entity.kind === "text" || entity.kind === "paragraph" ? styleOf(entity.style) : undefined, paper, + patternOf, ); return; } @@ -1114,6 +1119,7 @@ function writeEntity( owner: string, style: TextStyle | undefined, paper: boolean, + patternOf: (name: string) => HatchPattern | undefined, ): void { const begin = (type: string, subclass: string) => { g(0, type); @@ -1219,8 +1225,9 @@ function writeEntity( begin("HATCH", "AcDbHatch"); point(g, 10, 0, 0); point3(g, 210, 0, 0, 1); - g(2, "SOLID"); - g(70, 1); // solid + const pattern = hatchLines(e, patternOf); + g(2, pattern?.name ?? "SOLID"); + g(70, pattern === undefined ? 1 : 0); // solid, or lines g(71, 0); // no boundary objects const loops = e.loops; g(91, loops.length); @@ -1239,7 +1246,23 @@ function writeEntity( g(97, 0); } g(75, 0); // normal: the parity of the loops around a point - g(76, 1); // predefined + if (pattern === undefined) g(76, 1); // predefined + else { + g(76, pattern.type); + g(52, pattern.angle); + g(41, pattern.scale); + g(77, pattern.crossed ? 1 : 0); + g(78, pattern.lines.length); + for (const line of pattern.lines) { + g(53, fifteenDigits(line.angle)); + g(43, fifteenDigits(line.base[0])); + g(44, fifteenDigits(line.base[1])); + g(45, fifteenDigits(line.offset[0])); + g(46, fifteenDigits(line.offset[1])); + g(79, line.dashes.length); + for (const dash of line.dashes) g(49, fifteenDigits(dash)); + } + } g(98, 1); g(10, 0); g(20, 0); diff --git a/src/fills.ts b/src/fills.ts index 63d245a..59c7856 100644 --- a/src/fills.ts +++ b/src/fills.ts @@ -7,11 +7,23 @@ // lower-left corner the polygon's least X and Y and its side the larger of the polygon's width and // height, clipped by the polygon in that pixel's axes, y down from its top. It plots a text's mask // as the text's box grown by the mask's factor less one times its height, each side. -import type { Drawing, Entity, HatchLoop, Point, Polyline } from "./drawing.ts"; +import type { + Drawing, + Entity, + Hatch, + HatchLoop, + HatchPattern, + PatternLine, + Point, + Polyline, +} from "./drawing.ts"; +import { placedLines, userLines, type PlacedLine } from "./patterns.ts"; import { written } from "./format.ts"; import { keyHandle } from "./handles.ts"; +import { layerKey } from "./layers.ts"; import { placer, type ParagraphLayout, type ParagraphToMeasure } from "./paragraphs.ts"; -import { polylineSides, type PolylineSide } from "./polylines.ts"; +import { direction, polylineSides, type PolylineSide } from "./polylines.ts"; +import { HATCH_LINES, PATTERN_ITEMS, PATTERN_REACH, patternDensityProblem } from "./rules.ts"; import { filled } from "./shape.ts"; /** @@ -38,6 +50,266 @@ export function loopOutline(loop: HatchLoop, layer: string): Polyline { }; } +/** What a hatch's pattern draws, as a file holds it. */ +export interface HatchLines { + /** The pattern's name, or `_U` for user-defined lines, as the leading CAD app names them. */ + readonly name: string; + /** Group 76: 2 a pattern of a file, 0 user-defined lines. */ + readonly type: 0 | 2; + readonly angle: number; + /** The pattern's scale, or the user-defined lines' spacing. */ + readonly scale: number; + readonly crossed: boolean; + readonly lines: readonly PlacedLine[]; +} + +/** + * A drawing's patterns by the name a hatch gives, which is taken as a linetype's name is, whatever + * the case of its letters: the first of a name where two share it, which `lint` refuses. + */ +export function patternFinder( + patterns: readonly HatchPattern[] | undefined, +): (name: string) => HatchPattern | undefined { + const byKey = new Map(); + for (const pattern of patterns ?? []) { + const key = layerKey(pattern.name); + if (!byKey.has(key)) byKey.set(key, pattern); + } + return (name) => byKey.get(layerKey(name)); +} + +/** A hatch's pattern as it is drawn, before its lines are placed. */ +interface Chosen extends Omit { + readonly origin: Point; + /** The pattern of the drawing it names, or undefined for user-defined lines. */ + readonly pattern?: HatchPattern; +} + +/** + * A hatch's pattern from its numbers as written, a field the rules refuse taken as its default: + * undefined for a solid hatch, and for a pattern `patternOf` does not find. + */ +function chosen( + hatch: Pick, + patternOf: (name: string) => HatchPattern | undefined, +): Chosen | undefined { + const p: unknown = hatch.pattern; + if (typeof p !== "object" || p === null || Array.isArray(p)) return undefined; + const given = p as Record; + const number = (value: unknown, otherwise: number) => + typeof value === "number" && Number.isFinite(value) ? written(value) : otherwise; + const at = given.origin; + const origin: Point = + Array.isArray(at) && at.length === 2 ? [number(at[0], 0), number(at[1], 0)] : [0, 0]; + const angle = number(given.angle, 0); + if (typeof given.spacing === "number") { + const spacing = number(given.spacing, 0); + if (!(spacing > 0)) return undefined; + const crossed = given.crossed === true; + return { name: "_U", type: 0, angle, scale: spacing, crossed, origin }; + } + if (typeof given.name !== "string") return undefined; + const pattern = patternOf(given.name); + if (pattern === undefined) return undefined; + const scale = number(given.scale, 1); + if (!(scale > 0)) return undefined; + return { name: pattern.name, type: 2, angle, scale, crossed: false, origin, pattern }; +} + +/** + * The lines a hatch's pattern draws, placed in the drawing: undefined for a solid hatch, and for a + * pattern `patternOf` does not find, which `lint` refuses. + */ +export function hatchLines( + hatch: Pick, + patternOf: (name: string) => HatchPattern | undefined, +): HatchLines | undefined { + const c = chosen(hatch, patternOf); + if (c === undefined) return undefined; + const { name, type, angle, scale, crossed, origin, pattern } = c; + const lines = pattern + ? placedLines(filled(pattern.lines), scale, angle, origin) + : userLines(scale, angle, crossed, origin); + return { name, type, angle, scale, crossed, lines }; +} + +/** The box of a hatch's loops: `[x0, y0, x1, y1]`. */ +export type LoopsBox = readonly [number, number, number, number]; + +/** + * A box that holds what a hatch's loops close around, its arcs too, from their numbers as given: + * the box of each side grown by the height of its arc, `|bulge|` times half its chord, which holds + * the arc whatever its sweep. Undefined for a loop with a point or a bulge that is not a finite + * number, which `lint` refuses, and for no point at all. + */ +export function loopsBox(loops: unknown): LoopsBox | undefined { + let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity]; + const finite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n); + for (const loop of drawnLoops(loops)) { + const points = filled(loop.points as unknown); + const bulges: unknown = loop.bulges; + const n = points.length; + for (let i = 0; i < n; i++) { + const p: unknown = points[i]; + const q: unknown = points[(i + 1) % n]; + if (!Array.isArray(p) || !Array.isArray(q)) return undefined; + const [px, py, qx, qy]: unknown[] = [p[0], p[1], q[0], q[1]]; + if (!finite(px) || !finite(py) || !finite(qx) || !finite(qy)) return undefined; + const b: unknown = Array.isArray(bulges) && i < bulges.length ? bulges[i] : 0; + if (b !== undefined && !finite(b)) return undefined; + const grow = b ? (Math.abs(b) * Math.hypot(qx - px, qy - py)) / 2 : 0; + x0 = Math.min(x0, px - grow, qx - grow); + y0 = Math.min(y0, py - grow, qy - grow); + x1 = Math.max(x1, px + grow, qx + grow); + y1 = Math.max(y1, py + grow, qy + grow); + } + } + return x0 <= x1 && y0 <= y1 ? [x0, y0, x1, y1] : undefined; +} + +/** What a hatch pattern's definition holds, as the checks of what a hatch draws read it. */ +export interface PatternSizes { + /** Its lines and the dashes of each, which a hatch's lines are placed from. */ + readonly items: number; + /** The largest size of a line's angle. */ + readonly angle: number; + /** The largest sum of the sizes of a line's base point's numbers. */ + readonly base: number; + /** The largest size of a number a line's offset or dashes gives, the offset's two summed. */ + readonly reach: number; +} + +/** The sizes of one of a pattern's lines, whose numbers are all finite. */ +export function lineSizes(line: PatternLine): Omit { + let reach = Math.abs(line.offset[0]) + Math.abs(line.offset[1]); + for (const dash of filled(line.dashes ?? [])) reach = Math.max(reach, Math.abs(dash)); + return { + angle: Math.abs(line.angle), + base: Math.abs(line.base[0]) + Math.abs(line.base[1]), + reach, + }; +} + +/** + * The sizes of a pattern's lines, or undefined when one cannot be placed: at most `PATTERN_ITEMS` + * lines, each an object of finite numbers with at most as many dashes. A list of dashes that many + * lines share is read once, through `dashesRead`. + */ +export function patternSizes( + lines: unknown, + dashesRead: WeakMap, +): PatternSizes | undefined { + if (!Array.isArray(lines) || lines.length > PATTERN_ITEMS) return undefined; + const finite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n); + const pair = (p: unknown): boolean => Array.isArray(p) && finite(p[0]) && finite(p[1]); + let [items, angle, bases, reach] = [lines.length, 0, 0, 0]; + for (let i = 0; i < lines.length; i++) { + const line: unknown = lines[i]; + if (typeof line !== "object" || line === null) return undefined; + const l = line as Record; + if (!finite(l.angle) || !pair(l.base) || !pair(l.offset)) return undefined; + const dashes: unknown = l.dashes; + let most = 0; + if (dashes !== undefined) { + if (!Array.isArray(dashes)) return undefined; + if (!dashesRead.has(dashes)) { + let found: number | undefined = 0; + if (dashes.length > PATTERN_ITEMS) found = undefined; + else + for (let j = 0; j < dashes.length; j++) { + const dash: unknown = dashes[j]; + if (!finite(dash)) { + found = undefined; + break; + } + found = Math.max(found, Math.abs(dash)); + } + dashesRead.set(dashes, found); + } + const found = dashesRead.get(dashes); + if (found === undefined) return undefined; + most = found; + items += dashes.length; + } + const [base, offset] = [l.base as Point, l.offset as Point]; + angle = Math.max(angle, Math.abs(l.angle)); + bases = Math.max(bases, Math.abs(base[0]) + Math.abs(base[1])); + reach = Math.max(reach, most, Math.abs(offset[0]) + Math.abs(offset[1])); + } + return { items, angle, base: bases, reach }; +} + +/** A family of a hatch's lines as their count reads it: their angle and how far apart they lie. */ +export interface Family { + readonly angle: number; + readonly apart: number; +} + +/** What a hatch's pattern places, as the checks of what it draws read it. */ +export interface PatternSpread { + readonly families: readonly Family[]; + /** At least the largest size of a number a placed line holds: an angle, a coordinate, a dash. */ + readonly reach: number; +} + +/** + * What a hatch's pattern places, from its numbers as written: each family of lines, and a size no + * number its placed lines hold is above. Undefined for a solid hatch, and for a pattern `patternOf` + * does not find; `sizesOf` gives the sizes of the definition it finds. + */ +export function hatchSpread( + hatch: Pick, + patternOf: (name: string) => HatchPattern | undefined, + sizesOf: (pattern: HatchPattern) => PatternSizes | undefined, +): PatternSpread | undefined { + const c = chosen(hatch, patternOf); + if (c === undefined) return undefined; + const { angle, scale, origin, pattern } = c; + const away = Math.max(Math.abs(origin[0]), Math.abs(origin[1])); + if (pattern === undefined) { + const families = [{ angle, apart: scale }]; + if (c.crossed) families.push({ angle: angle + 90, apart: scale }); + return { families, reach: Math.max(Math.abs(angle) + 90, scale, away) }; + } + const sizes = sizesOf(pattern); + if (sizes === undefined) return undefined; + const families: Family[] = []; + for (const line of filled(pattern.lines)) { + families.push({ angle: line.angle + angle, apart: line.offset[1] * scale }); + } + // A line's base is scaled, turned and moved, and its offset and dashes scaled and turned. + return { + families, + reach: Math.max(sizes.angle + Math.abs(angle), sizes.base * scale + away, sizes.reach * scale), + }; +} + +/** + * How many lines a hatch's pattern draws across the box of its loops, at most: for each family, + * the box's extent across its lines over how far apart they lie, and one more. + */ +export function linesAcross(box: LoopsBox, families: readonly Family[]): number { + const [width, height] = [box[2] - box[0], box[3] - box[1]]; + let count = 0; + for (const { angle, apart } of families) { + const [c, s] = direction(angle); + count += Math.floor((width * Math.abs(s) + height * Math.abs(c)) / Math.abs(apart)) + 1; + } + return count; +} + +/** + * What is wrong with what a hatch's pattern draws inside its loops, or undefined: a number of its + * placed lines that is 1e100 or more, or more lines than `HATCH_LINES`. `lint` and the builder + * refuse such a hatch, and `toSVG` draws none of its lines. + */ +export function patternDrawnProblem(box: LoopsBox, spread: PatternSpread): string | undefined { + // Written with 15 digits, a number just under 1e100 would print as 1e+100. + if (!(Number(spread.reach.toPrecision(15)) < 1e100)) return PATTERN_REACH; + const count = linesAcross(box, spread.families); + return count <= HATCH_LINES ? undefined : patternDensityProblem(count); +} + /** The sides of a hatch's loop, as a closed polyline's. */ export function loopSides(loop: HatchLoop): PolylineSide[] { return polylineSides(loopOutline(loop, "")); diff --git a/src/index.ts b/src/index.ts index e4e350b..d4e7364 100644 --- a/src/index.ts +++ b/src/index.ts @@ -77,6 +77,10 @@ export { type EntityOptions, type Hatch, type HatchLoop, + type HatchOptions, + type HatchPattern, + type HatchPatternOf, + type HatchPatternChoice, type Image, type ImageOptions, type Insert, @@ -110,6 +114,7 @@ export { type Lineweight, type Paragraph, type ParagraphAlign, + type PatternLine, type ParagraphOptions, type ParagraphVerticalAlign, type Point, @@ -142,6 +147,8 @@ export { type Zone, } from "./drawing.ts"; export { toDXF, type DxfOptions } from "./dxf.ts"; +export { parsePatterns, PATTERN_FILE_LENGTH } from "./patterns.ts"; +export { fifteenDigits } from "./format.ts"; export { rasterSize } from "./raster.ts"; export { drawingImages, @@ -167,8 +174,10 @@ export { } from "./images.ts"; export { dimensionMask, + hatchLines, loopBulged, maskOf, + patternFinder, variableDictionaryHandle, WIPEOUT_APPLICATION, wipeoutClip, @@ -396,6 +405,7 @@ export { type ReadLinetype, type ReadMask, type ReadMtext, + type ReadPatternLine, type ReadMultileader, type ReadOptions, type ReadPolyline, diff --git a/src/lint.ts b/src/lint.ts index ac054d7..e7c5370 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -35,6 +35,8 @@ import type { Drawing, DxfVersion, Entity, + Hatch, + HatchPattern, Image, Layout, Viewport, @@ -43,6 +45,7 @@ import type { Leader, LeaderStyle, Linetype, + PatternLine, Point, Text, TextStyle, @@ -182,8 +185,23 @@ import { WIPEOUT_FLAT, WIPEOUT_FRAME, WIPEOUT_POINTS, + hatchPatternChoiceProblem, + hatchPatternNameProblem, + PATTERN_ITEMS, + patternLineProblem, + patternLinesProblem, + undefinedHatchPatternProblem, } from "./rules.ts"; -import { loopBulged, onOneLine, polygonCrosses } from "./fills.ts"; +import { + hatchSpread, + lineSizes, + loopBulged, + loopsBox, + onOneLine, + patternDrawnProblem, + polygonCrosses, + type PatternSizes, +} from "./fills.ts"; export type LintRule = | "format" @@ -228,6 +246,8 @@ export type LintRule = | "paragraph" | "image" | "hatch" + | "hatch-pattern" + | "duplicate-hatch-pattern" | "wipeout" | "zero-length" | "standard" @@ -366,6 +386,25 @@ const REPEATS = 16; /** The attributes of each insert that are placed, and take handles, free of the limit. */ const FREE = 64; +/** A check of no type, for a list whose items' types a rule reports with the item's path. */ +const UNTYPED: Check = () => {}; + +/** + * True for a line of a hatch pattern whose fields all have their types: a rule refused it for a + * value, not for a type. A list of more dashes than a pattern holds is refused for its length. + */ +function lineTyped(line: Readonly>): boolean { + const pair = (p: unknown): boolean => + Array.isArray(p) && p.length === 2 && typeof p[0] === "number" && typeof p[1] === "number"; + if (typeof line.angle !== "number" || !pair(line.base) || !pair(line.offset)) return false; + const dashes: unknown = line.dashes; + if (dashes === undefined) return true; + if (!Array.isArray(dashes)) return false; + if (dashes.length > PATTERN_ITEMS) return true; + for (let i = 0; i < dashes.length; i++) if (typeof dashes[i] !== "number") return false; + return true; +} + /** The values of an insert that gives none. */ const NO_VALUES: Readonly> = Object.freeze({}); @@ -541,6 +580,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) case "image": cost += long1(e.path); break; + case "hatch": + // A message quotes the name of a pattern the drawing does not have. + cost += long1(isObject(e.pattern) ? e.pattern.name : undefined); + break; } return cost; }; @@ -687,7 +730,8 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) | "xrefs" | "layouts" | "dimensionStyles" - | "leaderStyles", + | "leaderStyles" + | "patterns", rule: LintRule, ): readonly T[] => { const value: unknown = drawing[field]; @@ -777,6 +821,153 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) linetypes.add(key); if (!linetypesAudited.has(auditKey)) linetypesAudited.set(auditKey, linetype.name); }); + // A hatch finds its pattern by name as a linetype is found, whatever the case of its letters, + // and takes the first of a name. A pattern's lines are read up to `PATTERN_ITEMS` of them, and a + // list of lines or of dashes that many definitions share is paid for each time it is read again. + /** Each pattern a hatch can find, with its sizes, by `layerKey`: undefined for one refused. */ + const patternsByKey = new Map(); + const patternList = listed("patterns", "hatch-pattern"); + if (r12 && patternList.length > 0) { + out.push({ + rule: "hatch-pattern", + severity: "error", + message: `patterns: ${R12_ONLY.hatches}`, + }); + } else { + each(patternList, "patterns", "hatch-pattern", UNTYPED, (pattern, i) => { + const at = `patterns[${i}]`; + const where = () => at; + const from = out.length; + const name: unknown = isObject(pattern) ? pattern.name : undefined; + const long = long1(name) + long1(isObject(pattern) ? pattern.description : undefined); + if (long > 0 && !spend(long, where)) return; + const key = typeof name === "string" && name.length <= 255 ? layerKey(name) : undefined; + /** Names the pattern, which a reader leaves out, where an error names a part of it. */ + const whole = (): void => { + for (let k = from; k < out.length; k++) { + const found = out[k]!; + if (found.item?.startsWith(`${at}.`)) out[k] = { ...found, item: at }; + } + }; + if (malformed(WALKABLE.pattern, pattern, at, "hatch-pattern")) { + // A hatch that names it gets no second error. + if (key !== undefined && !patternsByKey.has(key)) patternsByKey.set(key, undefined); + return; + } + const label = `Hatch pattern ${shown(name)}`; + const error = (message: string, typed: boolean): void => { + out.push({ + rule: "hatch-pattern", + severity: "error", + message: `${label}: ${message}`, + ...(typed ? { item: at } : {}), + }); + }; + const description: unknown = pattern.description; + let sound = true; + const head = hatchPatternNameProblem(name, description); + if (head) { + error( + head, + typeof name !== "string" || !["string", "undefined"].includes(typeof description), + ); + sound = false; + } + const lines: unknown = pattern.lines; + const listProblem = patternLinesProblem(lines); + const sizes = { items: 0, angle: 0, base: 0, reach: 0 }; + if (listProblem) { + error(listProblem, !Array.isArray(lines)); + sound = false; + } else { + const list = lines as readonly unknown[]; + // A list read again pays for its lines and for the dashes of each. + const repeated = list.length >= FREE && again(list); + if (repeated && !spend(Math.floor(list.length / 8), where)) return; + sizes.items = list.length; + for (let j = 0; j < list.length; j++) { + if (!(j in list)) { + error(slotProblem(`${at}.lines`, j), true); + sound = false; + break; + } + const line: unknown = list[j]; + if (malformed(WALKABLE.patternLine, line, `${at}.lines[${j}]`, "hatch-pattern")) { + sound = false; + break; + } + const dashes: unknown = (line as Record).dashes; + const shared = + Array.isArray(dashes) && + dashes.length <= PATTERN_ITEMS && + (repeated || (dashes.length >= FREE && again(dashes))); + if (shared && !spend(Math.floor(dashes.length / 8), where)) return; + const problem = patternLineProblem(line); + if (problem) { + error(`line ${j}: ${problem}`, !lineTyped(line as Record)); + sound = false; + break; + } + const { angle, base, reach } = lineSizes(line as PatternLine); + sizes.angle = Math.max(sizes.angle, angle); + sizes.base = Math.max(sizes.base, base); + sizes.reach = Math.max(sizes.reach, reach); + sizes.items += Array.isArray(dashes) ? dashes.length : 0; + } + } + whole(); + if (key === undefined) return; + if (patternsByKey.has(key)) { + out.push({ + rule: "duplicate-hatch-pattern", + severity: "error", + message: `${label} is defined twice. A hatch finds its pattern by name whatever the case of its letters, as CAD programs do, and takes the first`, + }); + } else patternsByKey.set(key, sound ? [pattern, sizes] : undefined); + }); + } + /** The key of each name a hatch gives its pattern, worked out once. */ + const patternKeys = new Map(); + /** What is wrong with each object a hatch gives as its pattern, worked out once. */ + const choices = new WeakMap(); + /** + * Checks a hatch's pattern: its fields, the definition it names, and, for a hatch whose loops are + * sound, what its lines draw. + */ + const lintHatchPattern = (hatch: Hatch, add: Add, sound: boolean, here: () => string): void => { + const choice: unknown = hatch.pattern; + let problem: string | undefined; + if (typeof choice === "object" && choice !== null) { + if (choices.has(choice)) problem = choices.get(choice); + else choices.set(choice, (problem = hatchPatternChoiceProblem(choice))); + } else problem = hatchPatternChoiceProblem(choice); + if (problem) return add("hatch-pattern", "error", problem); + const name: unknown = (choice as Record).name; + let found: readonly [HatchPattern, PatternSizes] | undefined; + if (typeof name === "string") { + let key = name.length <= 255 ? patternKeys.get(name) : undefined; + if (key === undefined && name.length <= 255) patternKeys.set(name, (key = layerKey(name))); + if (key === undefined || !patternsByKey.has(key)) { + return add("hatch-pattern", "error", undefinedHatchPatternProblem(name)); + } + found = patternsByKey.get(key); + // A definition the rules refused has its errors, and draws nothing that can be checked. + if (found === undefined) return; + } + if (!sound) return; + // The writers place every line and dash of the pattern again for each hatch that names it. + const items = found?.[1].items ?? 0; + if (items >= FREE && !spend(Math.floor(items / 8), here)) return; + const box = loopsBox(hatch.loops); + const spread = hatchSpread( + hatch, + () => found?.[0], + () => found?.[1], + ); + const drawn = box && spread ? patternDrawnProblem(box, spread) : undefined; + if (drawn) add("hatch-pattern", "error", drawn); + }; + /** What is wrong with a reference to a linetype, which the leading CAD app discards a drawing over. */ const missing = (name: unknown): string | undefined => { if (typeof name !== "string") return "a linetype is named by a string"; @@ -1799,6 +1990,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) add(entity.kind, "error", R12_ONLY.hatches); return; } + if (entity.kind === "hatch" && entity.pattern !== undefined) { + lintHatchPattern(entity, add, problems.length === 0, here); + } // Each side against each other one, paid for by the pairs past the first 4,096. if (entity.kind === "wipeout" && entity.points.length > 3 && problems.length === 0) { const n = entity.points.length; diff --git a/src/patterns.ts b/src/patterns.ts new file mode 100644 index 0000000..c631c07 --- /dev/null +++ b/src/patterns.ts @@ -0,0 +1,298 @@ +// Hatch patterns: a pattern file's definitions, and the lines a pattern draws inside a hatch's +// loops. A pattern is a set of families of parallel lines: each family's line runs through its +// base point at its angle, the next one over is moved by its offset, and its dashes repeat along +// it from the base point, a positive length drawn, a negative one left out, and 0 a dot. A pattern +// file gives the offset along and across its line; a hatch in a file holds every line already +// turned by the hatch's angle, scaled and moved to its origin, the offset turned to the line's +// angle. The lines are cut to the area the loops fill by parity, as the leading CAD app cuts them. +import type { HatchPattern, PatternLine, Point } from "./drawing.ts"; +import { + direction, + includeArc, + sideArc, + type PolylineBox, + type PolylineSide, + type SideArc, +} from "./polylines.ts"; + +/** The most characters of a pattern file `parsePatterns` reads. */ +export const PATTERN_FILE_LENGTH = 1_000_000; + +/** + * The patterns of a pattern file's text, in the format CAD programs read: a pattern starts at a + * line `*NAME, description`, and each line after it is `angle, x, y, dx, dy` and its dashes. A `;` + * starts a comment. + * + * @throws RangeError for a line it cannot read, naming its number, and for text past + * `PATTERN_FILE_LENGTH` characters. + */ +export function parsePatterns(text: string): HatchPattern[] { + if (typeof text !== "string") throw new RangeError("A pattern file's text must be a string"); + if (text.length > PATTERN_FILE_LENGTH) + throw new RangeError(`A pattern file is at most ${PATTERN_FILE_LENGTH} characters`); + const out: { name: string; description?: string; lines: PatternLine[] }[] = []; + const rows = text.split(/\r\n|\r|\n/); + rows.forEach((row, index) => { + const comment = row.indexOf(";"); + const line = (comment < 0 ? row : row.slice(0, comment)).trim(); + if (line === "") return; + const where = `line ${index + 1} of the pattern file`; + if (line.startsWith("*")) { + const at = line.indexOf(","); + const name = (at < 0 ? line.slice(1) : line.slice(1, at)).trim(); + if (name === "") throw new RangeError(`${where}: a pattern needs a name after *`); + const description = at < 0 ? "" : line.slice(at + 1).trim(); + out.push({ name, ...(description === "" ? {} : { description }), lines: [] }); + return; + } + const pattern = out.at(-1); + if (pattern === undefined) throw new RangeError(`${where}: a line before any *NAME`); + const values = line.split(",").map((v) => v.trim()); + const numbers = values.map(Number); + if (values.length < 5 || values.some((v) => v === "") || !numbers.every(Number.isFinite)) + throw new RangeError( + `${where}: a line is angle, x, y, dx, dy and its dashes, all numbers, not ${JSON.stringify(line)}`, + ); + const [angle, x, y, dx, dy, ...dashes] = numbers as [number, number, number, number, number]; + pattern.lines.push({ + angle, + base: [x, y], + offset: [dx, dy], + ...(dashes.length === 0 ? {} : { dashes }), + }); + }); + for (const pattern of out) { + if (pattern.lines.length === 0) + throw new RangeError(`The pattern ${JSON.stringify(pattern.name)} has no lines`); + } + return out; +} + +/** A pattern's line placed in a drawing: turned, scaled and moved, the offset turned to it. */ +export interface PlacedLine { + readonly angle: number; + readonly base: Point; + /** In the drawing's axes. */ + readonly offset: Point; + readonly dashes: readonly number[]; +} + +const turn = ([x, y]: Point, degrees: number): Point => { + const [c, s] = direction(degrees); + return [x * c - y * s, x * s + y * c]; +}; + +/** + * A pattern's lines placed by a hatch: each angle plus `angle`, each base scaled, turned and moved + * to `origin`, each offset scaled and turned to its line's angle, and each dash scaled. + */ +export function placedLines( + lines: readonly PatternLine[], + scale: number, + angle: number, + origin: Point, +): PlacedLine[] { + return lines.map((line) => { + const base = turn([line.base[0] * scale, line.base[1] * scale], angle); + return { + angle: line.angle + angle, + base: [origin[0] + base[0], origin[1] + base[1]], + offset: turn([line.offset[0] * scale, line.offset[1] * scale], line.angle + angle), + dashes: (line.dashes ?? []).map((d) => d * scale), + }; + }); +} + +/** User-defined lines: one family at `angle`, `spacing` apart, and another square to it when crossed. */ +export function userLines( + spacing: number, + angle: number, + crossed: boolean, + origin: Point, +): PlacedLine[] { + const one = (a: number): PlacedLine => ({ + angle: a, + base: origin, + offset: turn([0, spacing], a), + dashes: [], + }); + return crossed ? [one(angle), one(angle + 90)] : [one(angle)]; +} + +/** A side of a loop a pattern is cut to: straight, or an arc by its bulge. */ +export type PatternSide = Pick; + +/** + * The pieces a pattern's lines draw inside the area loops fill by parity: each family's lines + * cross the loops' box, each line is cut where it crosses a side, an arc where the line meets its + * circle, and the pieces between an odd and an even crossing are cut again into its dashes from + * its base point. `step` is asked before each line, paying for the sides it crosses, and before + * each repeat of a line's dashes, paying for them; `piece` is given each piece. The walk stops when + * either says no. + */ +export function patternPieces( + rings: readonly (readonly PatternSide[])[], + lines: readonly PlacedLine[], + step: (cost: number) => boolean, + piece: (from: Point, to: Point) => boolean, +): void { + const box: PolylineBox = [Infinity, Infinity, -Infinity, -Infinity]; + const sides: { readonly side: PatternSide; readonly arc: SideArc | undefined }[] = []; + for (const ring of rings) { + for (const side of ring) { + const arc = sideArc(side.from, side.to, side.bulge); + sides.push({ side, arc }); + const [x, y] = side.from; + if (x < box[0]) box[0] = x; + if (y < box[1]) box[1] = y; + if (x > box[2]) box[2] = x; + if (y > box[3]) box[3] = y; + if (arc) includeArc(box, arc); + } + } + const [x0, y0, x1, y1] = box; + if (!(x0 <= x1 && y0 <= y1)) return; + // A line is crossed with every side, twice: once for where it crosses, once for where it runs along. + const lineCost = 1 + Math.floor(sides.length / 32); + // How far two distances may differ and be one: to the last bits of the loops' size, and of + // where they lie, so that a hatch far from the origin cuts as one near it. + const magnitude = Math.max(Math.abs(x0), Math.abs(y0), Math.abs(x1), Math.abs(y1)); + const tiny = 1e-9 * Math.max(x1 - x0, y1 - y0) + 2 * Number.EPSILON * magnitude; + const corners: Point[] = [ + [x0, y0], + [x1, y0], + [x1, y1], + [x0, y1], + ]; + for (const line of lines) { + const along = direction(line.angle); + const across: Point = [-along[1], along[0]]; + // How far one line of the family lies from the next, square to them. + const apart = line.offset[0] * across[0] + line.offset[1] * across[1]; + if (!(Math.abs(apart) > 1e-12)) continue; + const reach = corners.map( + ([x, y]) => ((x - line.base[0]) * across[0] + (y - line.base[1]) * across[1]) / apart, + ); + const first = Math.ceil(Math.min(...reach) - 1e-9); + const last = Math.floor(Math.max(...reach) + 1e-9); + const period = line.dashes.reduce((sum, d) => sum + Math.abs(d), 0); + const repeatCost = 1 + Math.floor(line.dashes.length / 32); + for (let k = first; k <= last; k++) { + if (!step(lineCost)) return; + const origin: Point = [line.base[0] + k * line.offset[0], line.base[1] + k * line.offset[1]]; + const off = ([x, y]: Point): number => + (x - origin[0]) * across[0] + (y - origin[1]) * across[1]; + const at = ([x, y]: Point): number => (x - origin[0]) * along[0] + (y - origin[1]) * along[1]; + // Where the line crosses each side, as a distance along it from its origin. An end on the + // line counts as below it, so that the two sides that meet there count it once between them. + const crossings: number[] = []; + // The stretches of the line that straight sides lie along, which it draws nothing on. + const runs: [number, number][] = []; + for (const { side, arc } of sides) { + const sp = off(side.from); + const sq = off(side.to); + if (!arc) { + if (Math.abs(sp) <= tiny && Math.abs(sq) <= tiny) { + const [tp, tq] = [at(side.from), at(side.to)]; + if (Math.abs(tq - tp) > tiny) runs.push([Math.min(tp, tq), Math.max(tp, tq)]); + } + if (sp > 0 === sq > 0) continue; + const t = sp / (sp - sq); + crossings.push( + at([ + side.from[0] + (side.to[0] - side.from[0]) * t, + side.from[1] + (side.to[1] - side.from[1]) * t, + ]), + ); + continue; + } + // The arc's circle meets the line where its center lies less than its radius off it. Along + // the arc, from its start, through each meeting inside its sweep, to its end, the line is + // crossed wherever the side of it the arc is on changes, as for a straight side. + const sweep = Math.abs(arc.sweep); + const arcAt = (u: number): Point => { + const angle = arc.start + Math.sign(arc.sweep) * u; + return [ + arc.center[0] + arc.radius * Math.cos(angle), + arc.center[1] + arc.radius * Math.sin(angle), + ]; + }; + const meetings: number[] = []; + const centerOff = off(arc.center); + if (Math.abs(centerOff) < arc.radius) { + const facing = Math.atan2(across[1], across[0]); + const turn = Math.acos(-centerOff / arc.radius); + for (const angle of [facing + turn, facing - turn]) { + const from = arc.sweep > 0 ? angle - arc.start : arc.start - angle; + const u = ((from % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI); + if (u > 0 && u < sweep) meetings.push(u); + } + meetings.sort((m, n) => m - n); + } + const events = [0, ...meetings, sweep]; + let above = sp > 0; + for (let e = 0; e + 1 < events.length; e++) { + // The side between two meetings, where it lies furthest off the line: a tangent touches + // it at one point, which is no crossing. + const [a, b] = [events[e]!, events[e + 1]!]; + let most = 0; + for (const f of [0.25, 0.5, 0.75]) { + const d = off(arcAt(a + (b - a) * f)); + if (Math.abs(d) > Math.abs(most)) most = d; + } + const inside = most > 0; + if (inside !== above) crossings.push(e === 0 ? at(side.from) : at(arcAt(events[e]!))); + above = inside; + } + if (sq > 0 !== above) crossings.push(at(side.to)); + } + crossings.sort((m, n) => m - n); + if (!step(1 + Math.floor((crossings.length + runs.length) / 8))) return; + // The stretches inside the loops, less the runs along a side: the runs sorted and joined + // where they overlap, then both walked once together. + runs.sort((m, n) => m[0] - n[0]); + const joined: [number, number][] = []; + for (const run of runs) { + const last = joined.at(-1); + if (last && run[0] <= last[1]) last[1] = Math.max(last[1], run[1]); + else joined.push([run[0], run[1]]); + } + const stretches: [number, number][] = []; + let r = 0; + for (let i = 0; i + 1 < crossings.length; i += 2) { + let from = crossings[i]!; + const to = crossings[i + 1]!; + while (r < joined.length && joined[r]![1] <= from) r++; + for (let q = r; q < joined.length && joined[q]![0] < to && from < to; q++) { + const [a, b] = joined[q]!; + if (a > from) stretches.push([from, a]); + if (b > from) from = b; + } + if (from < to) stretches.push([from, to]); + } + const point = (t: number): Point => [origin[0] + along[0] * t, origin[1] + along[1] * t]; + for (const [from, to] of stretches) { + if (period === 0) { + if (!piece(point(from), point(to))) return; + continue; + } + // The dashes from the pattern's start before `from` on, up to `to`. + let t = Math.floor(from / period) * period; + while (t <= to) { + if (!step(repeatCost)) return; + for (const dash of line.dashes) { + const end = t + Math.abs(dash); + // A dash that only touches the stretch draws nothing there. A dot draws inside it and + // at its far end, not at its near one, as the leading CAD app draws them. + const drawn = + dash > 0 + ? end > from + tiny && t < to - tiny + : dash === 0 && t > from + tiny && t <= to + tiny; + if (drawn && !piece(point(Math.max(t, from)), point(Math.min(end, to)))) return; + t = end; + } + } + } + } + } +} diff --git a/src/polylines.ts b/src/polylines.ts index 14851f3..207fa8a 100644 --- a/src/polylines.ts +++ b/src/polylines.ts @@ -6,6 +6,17 @@ import type { Point, Polyline } from "./drawing.ts"; import { written } from "./format.ts"; import { filled } from "./shape.ts"; +/** The unit vector at an angle in degrees, exact along the axes. */ +export function direction(degrees: number): Point { + const quarter = ((degrees % 360) + 360) % 360; + if (quarter === 0) return [1, 0]; + if (quarter === 90) return [0, 1]; + if (quarter === 180) return [-1, 0]; + if (quarter === 270) return [0, -1]; + const radians = (degrees * Math.PI) / 180; + return [Math.cos(radians), Math.sin(radians)]; +} + /** A side of a polyline, from one of its points to the next. */ export interface PolylineSide { readonly from: Point; diff --git a/src/read/check.ts b/src/read/check.ts index e75c4f1..fd8cdce 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -315,6 +315,15 @@ const ENTITY: Readonly> = { fields: { points: { list: "point" }, "bulges?": { list: "number" }, flags: "number" }, }, }, + "patternType?": "number", + "patternAngle?": "number", + "patternScale?": "number", + "crossed?": "boolean", + "patternLines?": { + list: { + fields: { angle: "number", base: "point", offset: "point", "dashes?": { list: "number" } }, + }, + }, }, wipeout: { ...BASE, kind: { oneOf: ["wipeout"] }, points: { list: "point" } }, }; diff --git a/src/read/entities.ts b/src/read/entities.ts index 9284954..6584270 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -14,6 +14,7 @@ import type { ReadEntityBase, ReadHatchLoop, ReadImage, + ReadPatternLine, ReadMtext, ReadMultileader, ReadPolyline, @@ -331,7 +332,14 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { const { codes, values } = s; let i = codes.indexOf(91); if (i < 0) return { malformed: "HATCH with no count of loops" }; - const value = (k: number) => Number(values[k]); + // A group whose value is not a finite number makes the hatch malformed, once all is read. + let broken = false; + const value = (k: number) => { + const text = values[k]!; + const n = Number(text); + if (text.trim() === "" || !Number.isFinite(n)) broken = true; + return n; + }; // The next group of a code from `i` on, read by the order of the loop's groups. const take = (code: number): number | undefined => { if (codes[i] !== code) return undefined; @@ -405,15 +413,58 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { }); } const style = HATCH_STYLES[num(s, 75) ?? 0] ?? "normal"; + const solid = num(s, 70) === 1; + // What a pattern holds after its loops: its kind, angle, scale, crossing and lines. + let pattern: Partial> & { + crossed?: true; + patternLines?: ReadPatternLine[]; + } = {}; + if (!solid) { + while (i < codes.length && codes[i] !== 76) i++; + const type = take(76); + const angle = take(52); + const scale = take(41); + const crossed = take(77) === 1; + const count = take(78) ?? 0; + const lines: ReadPatternLine[] = []; + for (let k = 0; k < count && codes[i] === 53; k++) { + const angleOf = take(53) ?? 0; + const placedBase = mirror([take(43) ?? 0, take(44) ?? 0]); + const offset = mirror([take(45) ?? 0, take(46) ?? 0]); + const dashCount = take(79) ?? 0; + const dashes: number[] = []; + for (let d = 0; d < dashCount && codes[i] === 49; d++) dashes.push(take(49) ?? 0); + if (dashes.length !== dashCount || codes[i] === 49) + return { malformed: "HATCH whose pattern lines do not follow their counts" }; + lines.push({ + // Seen from below, a line's direction is mirrored too. + angle: face === -1 ? 180 - angleOf : angleOf, + base: placedBase, + offset, + ...(dashes.length > 0 && { dashes }), + }); + } + if (lines.length !== count || codes[i] === 53) + return { malformed: "HATCH whose pattern lines do not follow their counts" }; + pattern = { + ...(type !== undefined && { patternType: type }), + ...(angle !== undefined && { patternAngle: angle }), + ...(scale !== undefined && { patternScale: scale }), + ...(crossed && { crossed: true as const }), + patternLines: lines, + }; + } + if (broken) return { malformed: "HATCH with a number that is not finite" }; return { entity: { ...base, kind: "hatch", pattern: name(s, 2) ?? "", - solid: num(s, 70) === 1, + solid, style, ...(num(s, 71) === 1 && { associative: true as const }), loops, + ...pattern, }, }; } @@ -1044,6 +1095,7 @@ export function costOf(e: ReadEntity): number { case "hatch": { let points = 0; for (const loop of e.loops) points += 1 + loop.points.length + (loop.bulges?.length ?? 0); + for (const line of e.patternLines ?? []) points += 3 + (line.dashes?.length ?? 0); return own + points + chars(e.pattern); } case "wipeout": diff --git a/src/read/model.ts b/src/read/model.ts index e03df74..68616c6 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -683,6 +683,29 @@ export interface ReadHatch extends ReadEntityBase { * A hatch with a loop of an ellipse or a spline is counted instead. */ readonly loops: readonly ReadHatchLoop[]; + /** Group 76 of one that is not solid: 0 user-defined lines, 1 a pattern the app ships, 2 a pattern of a file. */ + readonly patternType?: number; + /** Group 52: the pattern's angle, in degrees, as the file holds it: not mirrored for a hatch seen from below, though its lines are. */ + readonly patternAngle?: number; + /** Group 41: the pattern's scale, or the user-defined lines' spacing. */ + readonly patternScale?: number; + /** Group 77: true for user-defined lines crossed by as many more. */ + readonly crossed?: true; + /** + * The lines its pattern draws, as the file holds them: in the world's coordinates, each angle + * with the pattern's added, its base point placed and its offset turned to the line, its dashes + * scaled. A firm's patterns can be read back from its drawings this way. + */ + readonly patternLines?: readonly ReadPatternLine[]; +} + +/** A line of a hatch's pattern, as `ReadHatch.patternLines` holds it. */ +export interface ReadPatternLine { + readonly angle: number; + readonly base: Point; + readonly offset: Point; + /** Left out for a solid line. */ + readonly dashes?: readonly number[]; } /** A wipeout: its polygon in the world's coordinates, without its first point again at its end. */ diff --git a/src/rules.ts b/src/rules.ts index a7f4dcc..2149217 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -129,13 +129,22 @@ const LEADER_STYLE_NAMES = { length: "Leader style names cannot be longer than 255 characters, as dimension style names cannot", } as const; +const HATCH_PATTERN_NAMES = { + empty: "Hatch pattern names cannot be empty", + chars: 'Hatch pattern names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', + rejected: + "Hatch pattern names cannot contain a character the leading CAD app rejects or replaces in names, such as a zero-width space or the ohm sign U+2126. docs/layer-names.md in the tsdraft repository lists them", + edge: "Hatch pattern names cannot start or end with a space", + length: "Hatch pattern names cannot be longer than 255 characters", +} as const; type NameMessages = | typeof LAYER_NAMES | typeof LINETYPE_NAMES | typeof TEXT_STYLE_NAMES | typeof BLOCK_NAMES | typeof DIMENSION_STYLE_NAMES - | typeof LEADER_STYLE_NAMES; + | typeof LEADER_STYLE_NAMES + | typeof HATCH_PATTERN_NAMES; const NAME_R12_CHARS = 'R12 layer names can only use letters, digits, $, - and _. Use DXF version "R2018" for other characters'; const NAME_R12_LENGTH = @@ -1710,6 +1719,210 @@ export const WIPEOUT_CROSSES = /** What is wrong with a value of `wipeoutFrame`. */ export const WIPEOUT_FRAME = "wipeoutFrame must be true or false"; +/** + * The most lines a hatch pattern has, and the most dashes one of its lines has: a file holds each + * count as a 16-bit integer. + */ +export const PATTERN_ITEMS = 32_767; + +/** The most lines tsdraft draws for one hatch's pattern, across the box of its loops. */ +export const HATCH_LINES = 1_000_000; + +const PATTERN_CHOICE = + "pattern must be { name, scale?, angle?, origin? } for a pattern of the drawing's patterns, or { spacing, angle?, crossed?, origin? } for lines of the hatch's own"; +const PATTERN_NAME_AND_SPACING = + "pattern has a name or a spacing, not both: a name for a pattern of the drawing's patterns, a spacing for lines of the hatch's own"; +const PATTERN_SCALE_WITH_SPACING = + "pattern's scale is for a pattern by its name: lines of the hatch's own are spaced by spacing"; +const PATTERN_CROSSED_WITH_NAME = + "pattern's crossed is for lines of the hatch's own, with spacing: a pattern by its name has the lines its definition gives"; +const PATTERN_POINT = "must be a point, [x, y], of finite numbers"; +const PATTERN_LINES = + "A hatch pattern's lines must be a list of lines, each { angle, base, offset, dashes? }"; +const PATTERN_NO_LINES = "A hatch pattern needs at least one line"; +const PATTERN_MANY_LINES = `A hatch pattern has at most ${PATTERN_ITEMS} lines: a file holds their count as a 16-bit integer`; +const PATTERN_DASHES = "its dashes must be a list of finite numbers"; +const PATTERN_MANY_DASHES = `a line of a hatch pattern has at most ${PATTERN_ITEMS} dashes: a file holds their count as a 16-bit integer`; +const PATTERN_ZERO_DASHES = + "its dashes cannot all be 0: dots with no gap between them repeat over no length. Give each gap as a negative length"; +const PATTERN_NO_SPACING = + "its offset across the line, the second number of offset, rounds to 0 at the 6 decimals tsdraft writes, and at 0 all its lines would lie on one. Use 0.000001 or more"; + +/** + * What is wrong with a hatch's lines placed by its pattern: a number of 1e100 or more, which the + * file holds for each line. + */ +export const PATTERN_REACH = + "its pattern's lines, scaled, turned and moved to its origin, hold a number of 1e100 or more, and the leading CAD app reads only two exponent digits from DXF: give it a smaller scale, or an angle or origin nearer 0"; + +/** What is wrong with a size of a hatch's pattern, its `scale` or its `spacing`, or undefined. */ +function patternSizeProblem(field: "scale" | "spacing", value: unknown): string | undefined { + if (typeof value !== "number" || !Number.isFinite(value) || !(value > 0)) { + return `pattern's ${field} must be a finite number greater than 0`; + } + if (written(value) === 0) return `pattern's ${field}: ${WRITTEN_AS_ZERO}`; + const large = magnitudeProblem(value); + return large ? `pattern's ${field}: ${large}` : undefined; +} + +/** What is wrong with a value that must be a point of finite numbers, or undefined. */ +function finitePointProblem(value: unknown, what: string): string | undefined { + if (!Array.isArray(value) || value.length !== 2) return `${what} ${PATTERN_POINT}`; + for (let i = 0; i < 2; i++) { + const n: unknown = value[i]; + if (typeof n !== "number" || !Number.isFinite(n)) return `${what} ${PATTERN_POINT}`; + } + const large = magnitudeProblem(value[0] as number) ?? magnitudeProblem(value[1] as number); + return large ? `${what}: ${large}` : undefined; +} + +/** What is wrong with a value that must be a finite angle, or undefined. */ +function finiteAngleProblem(value: unknown, what: string): string | undefined { + if (typeof value !== "number" || !Number.isFinite(value)) { + return `${what} must be a finite number`; + } + const large = magnitudeProblem(value); + return large ? `${what}: ${large}` : undefined; +} + +/** What is wrong with a hatch whose pattern is named SOLID. */ +export const PATTERN_SOLID = + "pattern SOLID is the name CAD programs give a solid fill: leave the pattern out for a solid hatch"; + +/** + * Returns what is wrong with a hatch's `pattern`, or undefined: an object with a `name` of the + * drawing's patterns and its `scale`, `angle` and `origin`, or a `spacing` of lines of the hatch's + * own with their `angle`, `crossed` and `origin`. Whether the drawing has a pattern of the name + * depends on the drawing, so it is checked apart. + */ +export function hatchPatternChoiceProblem(value: unknown): string | undefined { + if (typeof value !== "object" || value === null || Array.isArray(value)) return PATTERN_CHOICE; + const c = value as Record; + for (const key of Object.keys(c)) { + if (!["name", "scale", "angle", "origin", "spacing", "crossed"].includes(key)) { + return PATTERN_CHOICE; + } + } + const named = c.name !== undefined; + const spaced = c.spacing !== undefined; + if (named && spaced) return PATTERN_NAME_AND_SPACING; + if (!named && !spaced) return PATTERN_CHOICE; + if (named) { + if (typeof c.name !== "string") return "pattern's name must be a string"; + if (c.name.toUpperCase() === "SOLID") return PATTERN_SOLID; + if (c.crossed !== undefined) return PATTERN_CROSSED_WITH_NAME; + if (c.scale !== undefined) { + const problem = patternSizeProblem("scale", c.scale); + if (problem) return problem; + } + } else { + if (c.scale !== undefined) return PATTERN_SCALE_WITH_SPACING; + const problem = patternSizeProblem("spacing", c.spacing); + if (problem) return problem; + if (c.crossed !== undefined && typeof c.crossed !== "boolean") { + return "pattern's crossed must be true or false"; + } + } + if (c.angle !== undefined) { + const problem = finiteAngleProblem(c.angle, "pattern's angle"); + if (problem) return problem; + } + return c.origin === undefined ? undefined : finitePointProblem(c.origin, "pattern's origin"); +} + +/** + * Returns what is wrong with a hatch that names a pattern the drawing does not have. tsdraft has + * none of its own, so the message says where a firm's come from. The rule depends on the drawing, + * so it has no type. + */ +export function undefinedHatchPatternProblem(name: string, builder = false): string { + const fix = builder + ? "add the firm's pattern file with patterns() first" + : "pass the firm's pattern file through parsePatterns into the drawing's patterns"; + return `Hatch pattern ${shown(name)} is not defined. tsdraft has no patterns of its own: ${fix}`; +} + +/** What is wrong with a hatch whose pattern draws more lines than `HATCH_LINES`. */ +export function patternDensityProblem(lines: number): string { + const count = lines < 1e15 ? Math.ceil(lines).toLocaleString("en-US") : "1e15 or more"; + return `its pattern draws ${count} lines across its loops, more than the ${HATCH_LINES.toLocaleString("en-US")} tsdraft draws for one hatch: give it a larger scale or spacing`; +} + +/** + * Returns what is wrong with a hatch pattern's name and description, or undefined. The name is + * held to the rules of a linetype's. + */ +export function hatchPatternNameProblem(name: unknown, description: unknown): string | undefined { + if (typeof name !== "string") return "A hatch pattern's name must be a string"; + const problem = nameProblem(name, HATCH_PATTERN_NAMES); + if (problem) return problem; + if (description === undefined) return undefined; + if (typeof description !== "string") return "A hatch pattern's description must be a string"; + const text = textProblem(description); + return text ? `its description: ${text}` : undefined; +} + +/** + * Returns what is wrong with a hatch pattern's list of lines as a list, or undefined: from 1 to + * `PATTERN_ITEMS` of them. No line is read. + */ +export function patternLinesProblem(lines: unknown): string | undefined { + if (!Array.isArray(lines)) return PATTERN_LINES; + if (lines.length === 0) return PATTERN_NO_LINES; + return lines.length > PATTERN_ITEMS ? PATTERN_MANY_LINES : undefined; +} + +/** + * Returns what is wrong with a line of a hatch pattern, or undefined: its angle, base and offset + * finite and under 1e100, its offset across the line not 0 as written, and its dashes at most + * `PATTERN_ITEMS` finite numbers under 1e100, not all 0. + */ +export function patternLineProblem(line: unknown): string | undefined { + if (typeof line !== "object" || line === null || Array.isArray(line)) { + return "a line must be { angle, base, offset, dashes? }"; + } + const l = line as Record; + const problem = + finiteAngleProblem(l.angle, "its angle") ?? + finitePointProblem(l.base, "its base") ?? + finitePointProblem(l.offset, "its offset"); + if (problem) return problem; + if (written((l.offset as readonly number[])[1]!) === 0) return PATTERN_NO_SPACING; + const dashes: unknown = l.dashes; + if (dashes === undefined) return undefined; + if (!Array.isArray(dashes)) return PATTERN_DASHES; + if (dashes.length > PATTERN_ITEMS) return PATTERN_MANY_DASHES; + let drawn = dashes.length === 0; + for (let i = 0; i < dashes.length; i++) { + const length: unknown = dashes[i]; + if (typeof length !== "number" || !Number.isFinite(length)) return PATTERN_DASHES; + const large = magnitudeProblem(length); + if (large) return `its dashes: ${large}`; + if (length !== 0) drawn = true; + } + return drawn ? undefined : PATTERN_ZERO_DASHES; +} + +/** + * Returns what is wrong with a hatch pattern's definition, or undefined: its name, its + * description and each of its lines. It reads at most `PATTERN_ITEMS` lines and as many dashes of + * each. + */ +export function hatchPatternProblem(definition: unknown): string | undefined { + if (typeof definition !== "object" || definition === null || Array.isArray(definition)) { + return "A hatch pattern must be { name, description?, lines }"; + } + const { name, description, lines } = definition as Record; + const problem = hatchPatternNameProblem(name, description) ?? patternLinesProblem(lines); + if (problem) return problem; + const list = lines as readonly unknown[]; + for (let i = 0; i < list.length; i++) { + const found = patternLineProblem(list[i]); + if (found) return `line ${i}: ${found}`; + } + return undefined; +} + /** What is wrong with a dimension style's mask. */ export const DIMENSION_TEXT_MASK = "textMask must be true, false, or { color }: a color index from 1 to 256, where 256 is the layer's"; diff --git a/src/shape.ts b/src/shape.ts index 2d74575..e6194c0 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -12,6 +12,7 @@ import type { Entity, Hatch, HatchLoop, + HatchPattern, Image, Insert, Layer, @@ -27,6 +28,7 @@ import type { ArcLengthDimension, Linetype, Paragraph, + PatternLine, Polyline, Text, TextStyle, @@ -303,6 +305,8 @@ export interface Shapes { readonly point: Check; readonly layer: Check; readonly linetype: Check; + readonly pattern: Check; + readonly patternLine: Check; readonly textStyle: Check; readonly dimensionStyle: Check; readonly leaderStyle: Check; @@ -619,7 +623,11 @@ function shapes(all: boolean, typed = all): Shapes { transparent: ruled(boolean), }, ), - hatch: fields({ kind, layer: string, loops: list(record(loop)) }, shared), + // A rule of `lint` reports the pattern, whatever its type. + hatch: fields( + { kind, layer: string, loops: list(record(loop)) }, + { ...shared, pattern: LEFT }, + ), wipeout: fields({ kind, layer: string, points: list(point) }, shared), } satisfies Record; @@ -670,6 +678,20 @@ function shapes(all: boolean, typed = all): Shapes { }, ), ); + // A rule of `lint` reports every field of a hatch pattern and of its lines, whatever its type, + // and reads at most as many lines and dashes as a file holds. + const patternLine = record( + fields( + { angle: ruled(number), base: ruled(point), offset: ruled(point) }, + { dashes: ruled(list(number)) }, + ), + ); + const pattern = record( + fields( + { name: ruled(string), lines: ruled(list(patternLine)) }, + { description: ruled(string) }, + ), + ); const linetype = record( fields( { name: ruled(string), description: ruled(string), pattern: ruled(list(number)) }, @@ -809,6 +831,7 @@ function shapes(all: boolean, typed = all): Shapes { leaderStyles: ruled(table(leaderStyle)), imageFrame: ruled(boolean), wipeoutFrame: ruled(boolean), + patterns: ruled(table(pattern)), }, ); return { @@ -816,6 +839,8 @@ function shapes(all: boolean, typed = all): Shapes { point, layer, linetype, + pattern, + patternLine, textStyle, dimensionStyle, leaderStyle, diff --git a/src/svg.ts b/src/svg.ts index b59566a..0e7ba8a 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -15,6 +15,7 @@ import { type Drawing, type Entity, type Hatch, + type HatchPattern, type Image, type Insert, type Layer, @@ -29,7 +30,21 @@ import { type Viewport, type Wipeout, } from "./drawing.ts"; -import { dimensionMask, drawnLoops, loopSides, maskOf, paragraphMaskCorners } from "./fills.ts"; +import { + dimensionMask, + drawnLoops, + hatchLines, + type HatchLines, + hatchSpread, + loopsBox, + loopSides, + maskOf, + paragraphMaskCorners, + patternDrawnProblem, + patternSizes, + type PatternSizes, +} from "./fills.ts"; +import { patternPieces } from "./patterns.ts"; import { arcPoint, hasArcsOrWidths, @@ -74,7 +89,7 @@ const markedOpaque = (info: RasterInfo): boolean => (info.color === 4 || info.color === 6) && info.width * info.height > OPAQUE_PIXELS; import { fontInfo, STANDARD_FONT, capHeightOf } from "./fonts.ts"; -import { fmt, written } from "./format.ts"; +import { fifteenDigits, fmt, written } from "./format.ts"; import { layerKey, layerKeys } from "./layers.ts"; import { findLayout, validViewportView } from "./layouts.ts"; import { leaderBlock, leaderPicture, type LeaderPicture } from "./leaders.ts"; @@ -91,7 +106,7 @@ import { import { arrowheadInfo, DEFAULT_ARROWHEAD } from "./arrowheads.ts"; import { DEFAULT_PLOT_STYLE_TABLE, paperInfo } from "./papers.ts"; import { shown as quoted, turning, viewportProblem } from "./rules.ts"; -import { filled } from "./shape.ts"; +import { filled, KEYED } from "./shape.ts"; import { isUnits } from "./units.ts"; /** @@ -721,7 +736,23 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ? imageElement(e, mark, drawnPen, look, from, matrix, room) : ""; } - if (e.kind === "hatch") return hatchToSvg(e, mark, drawnPen, matrix, room); + if (e.kind === "hatch") { + const found = tablesOf(from).hatchPatterns; + // A pattern whose lines cannot be placed, which `lint` refuses, is one the drawing lacks. + const patternOf = (name: string) => { + const pattern = name.length > KEYED ? undefined : found.get(layerKey(name)); + return pattern !== undefined && sizesOf(pattern) !== undefined ? pattern : undefined; + }; + // The walk of a pattern's lines is paid for as the picture's other work is, and placing + // them by their number and their dashes'. + const step = (cost: number) => spend(cost) || refuse(drawingAt?.() ?? "a hatch"); + const placing = (pattern: HatchPattern) => { + const sizes = sizesOf(pattern); + if (sizes !== undefined) step(Math.floor(sizes.items / 16)); + return sizes; + }; + return hatchToSvg(e, mark, drawnPen, look, matrix, room, patternOf, placing, step); + } if (e.kind === "wipeout") { const frame = (from?.drawing ?? drawing).wipeoutFrame !== false; return wipeoutToSvg(e, mark, drawnPen, look, matrix, frame); @@ -736,6 +767,15 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): return dimensionToSvg(e, style, textStyle, mark, drawnPen, look, matrix, room); }; + /** The sizes of each list of a hatch pattern's lines, read once for the picture. */ + const linesRead = new WeakMap(); + const dashesRead = new WeakMap(); + const sizesOf = (pattern: HatchPattern): PatternSizes | undefined => { + const lines: unknown = pattern.lines; + if (typeof lines !== "object" || lines === null) return undefined; + if (!linesRead.has(lines)) linesRead.set(lines, patternSizes(lines, dashesRead)); + return linesRead.get(lines); + }; /** The sides of each list of points a pattern cuts, read once for the picture. */ // A long list that one polyline's plan read and another's reads again is paid for, as `lint` // pays for it, by the entity drawn at the time. @@ -1247,9 +1287,17 @@ interface Tables { readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; readonly leaderStyles: ReadonlyMap; + /** The hatch patterns, by name as a linetype's is found: the first of a name. */ + readonly hatchPatterns: ReadonlyMap; } function tablesFor(drawing: Drawing): Tables { + const hatchPatterns = new Map(); + for (const pattern of filled(drawing.patterns)) { + if (typeof pattern?.name !== "string") continue; + const key = layerKey(pattern.name); + if (!hatchPatterns.has(key)) hatchPatterns.set(key, pattern); + } return { layers: new Map(filled(drawing.layers).map((l) => [layerKey(l.name), l])), patterns: new Map( @@ -1258,6 +1306,7 @@ function tablesFor(drawing: Drawing): Tables { textStyles: new Map(filled(drawing.textStyles).map((t) => [layerKey(t.name), t])), dimensionStyles: new Map(filled(drawing.dimensionStyles).map((t) => [layerKey(t.name), t])), leaderStyles: new Map(filled(drawing.leaderStyles).map((t) => [layerKey(t.name), t])), + hatchPatterns, }; } @@ -1513,9 +1562,21 @@ function hatchToSvg( e: Hatch, mark: string, pen: Pen, + look: Look, matrix: Matrix | undefined, room: number, + patternOf: (name: string) => HatchPattern | undefined, + sizesOf: (pattern: HatchPattern) => PatternSizes | undefined, + step: (cost: number) => boolean, ): string { + const spread = hatchSpread(e, patternOf, sizesOf); + if (spread !== undefined) { + // One whose loops or lines `lint` refuses draws none of its lines. + const box = loopsBox(e.loops); + if (box === undefined || patternDrawnProblem(box, spread) !== undefined) return ``; + const pattern = hatchLines(e, patternOf)!; + return patternToSvg(e, pattern, mark, pen, look, matrix, room, step); + } const place = (x: number, y: number): string => { const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; return `${fmt(px)} ${fmt(py)}`; @@ -1558,6 +1619,48 @@ function hatchToSvg( return ``; } +/** + * A hatch's pattern: each dash and dot its lines draw inside its loops, as one path in its pen, + * a dot as a piece of no length, which the plot's round ends draw. It stops once it passes the + * room left in the picture, longer than the room, which `write` then refuses; `step` pays for the + * walk of its lines. + */ +function patternToSvg( + e: Hatch, + pattern: HatchLines, + mark: string, + pen: Pen, + look: Look, + matrix: Matrix | undefined, + room: number, + step: (cost: number) => boolean, +): string { + const place = ([x, y]: Point): string => { + const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; + return `${fmt(px)} ${fmt(py)}`; + }; + // The loops and the lines as the file holds them: points with 6 decimals, lines with 15 digits. + const rings = drawnLoops(e.loops).map(loopSides); + const digits = (value: number) => Number(fifteenDigits(value)); + const lines = pattern.lines.map((line) => ({ + angle: digits(line.angle), + base: [digits(line.base[0]), digits(line.base[1])] as Point, + offset: [digits(line.offset[0]), digits(line.offset[1])] as Point, + dashes: line.dashes.map(digits), + })); + // The pieces are paid for from the room, and the one that passes it ends the path there. + const parts: string[] = []; + let left = room; + patternPieces(rings, lines, step, (from, to) => { + const part = `M ${place(from)} L ${place(to)}`; + parts.push(part); + return (left -= part.length + 1) >= 0; + }); + if (parts.length === 0) return ``; + const d = parts.join(" "); + return ``; +} + /** * A wipeout: its polygon in the paper's white, marked as a mask in the drawing's background, and * its frame in its pen when the drawing shows wipeouts' frames. diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 5d4d3d5..802c0f1 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -196,6 +196,65 @@ test("lint pays for what inserts repeat, and toDXF refuses what it stopped short ); }); +/** The example sheet with a hatch pattern, and a hatch of it in model space. */ +const patterned = (pattern: object): Drawing => ({ + ...sheet, + patterns: [pattern as never], + entities: [ + ...sheet.entities, + { + kind: "hatch", + layer: "0", + loops: [ + { + points: [ + [0, 0], + [10, 0], + [10, 10], + ], + }, + ], + pattern: { name: "HOLE" }, + }, + ], +}); + +test("lint and toSVG pay for the lines of hatch patterns that many places share", () => { + const dashes = Array.from({ length: 30_000 }, (_, i) => (i % 2 === 0 ? 1 : -1)); + const lines = Array.from({ length: 30_000 }, (_, i) => ({ + angle: i, + base: [0, 0] as Point, + offset: [0, 1] as Point, + dashes, + })); + const loops = [ + { + points: [ + [0, 0], + [1e5, 0], + [1e5, 1e5], + ] as Point[], + }, + ]; + const drawing: Drawing = { + ...createDrawing({ units: "ft" }).build(), + patterns: Array.from({ length: 1000 }, (_, i) => ({ name: `P${i}`, lines })), + entities: Array.from({ length: 10_000 }, (_, i) => ({ + kind: "hatch", + layer: "0", + loops, + pattern: pick(i), + })), + }; + function pick(i: number) { + return i % 2 === 0 ? { name: `P${i % 1000}` } : { spacing: 1e-6, crossed: true }; + } + const found = within(3000, () => lint(drawing)); + assert.ok(found.some((d) => d.rule === "check-capped")); + const drawn = settled(3000, () => toSVG(drawing)); + assert.ok(typeof drawn === "string" || drawn instanceof RangeError, String(drawn)); +}); + test("every walk stops at the first empty slot of a list", () => { // oxlint-disable-next-line unicorn/no-new-array const slots = () => new Array(2 ** 32 - 1); @@ -239,6 +298,12 @@ test("every walk stops at the first empty slot of a list", () => { ...sheet, linetypes: [...sheet.linetypes!, { name: "HOLE", description: "", pattern: slots() }], }, + { ...sheet, patterns: slots() }, + patterned({ name: "HOLE", lines: slots() }), + patterned({ + name: "HOLE", + lines: [{ angle: 0, base: [0, 0], offset: [0, 1], dashes: slots() }], + }), ] as Drawing[]) { assert.ok(within(1000, () => lint(drawing)).length > 0); for (const fn of [ diff --git a/test/patterns.test.ts b/test/patterns.test.ts new file mode 100644 index 0000000..cf11800 --- /dev/null +++ b/test/patterns.test.ts @@ -0,0 +1,191 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { createDrawing, readDXF, toDXF, toSVG, type Drawing, type Point } from "../src/index.ts"; +import { lintWithin } from "../src/lint.ts"; +import { svgWithin } from "../src/svg.ts"; +import { timeLimit } from "./time-limit.ts"; + +/** How many strokes a hatch's pattern draws in the plot. */ +function strokes(loops: { points: Point[]; bulges?: number[] }[], pattern: object): number { + const d = createDrawing({ units: "in" }); + d.hatch(loops, { pattern } as never); + const found = /]*data-hatch/.exec(toSVG(d.build())); + return found ? (found[1]!.match(/M /g) ?? []).length : 0; +} + +test("a pattern is cut to the loops as the file holds them, far from the origin and on an arc", () => { + // Seven lines inside, none on the edges, however far the hatch lies from the origin. + const far: Point[] = [ + [1e9, 0], + [1e9 + 10, 0], + [1e9 + 10, 2], + [1e9, 2], + ]; + assert.equal(strokes([{ points: far }], { spacing: 0.25 }), 7); + // The top edge is written at 7, where a line runs along it and draws nothing. + const rounded: Point[] = [ + [1, 6], + [5, 6], + [5, 7.0000004], + [1, 7.0000004], + ]; + assert.equal(strokes([{ points: rounded }], { spacing: 1 }), 0); + // A thin rectangle as far from the origin as near it. + const thin = (x: number): Point[] => [ + [x, 0], + [x + 10, 0], + [x + 10, 0.000006], + [x, 0.000006], + ]; + assert.equal(strokes([{ points: thin(0) }], { spacing: 0.000001 }), 5); + assert.equal(strokes([{ points: thin(1e9) }], { spacing: 0.000001 }), 5); + // A line that only touches a circle draws nothing there: only the diameter is drawn. + const unit: Point[] = [ + [-1, 0], + [1, 0], + ]; + assert.equal(strokes([{ points: unit, bulges: [1, 1] }], { spacing: 1 }), 1); + // A line just under a circle's top crosses it, and draws its short chord. + const circle: Point[] = [ + [11, 5.98], + [15, 6.02], + ]; + assert.equal( + strokes([{ points: circle, bulges: [1, 1] }], { spacing: 0.2, origin: [0, 8.00004] }), + 21, + ); +}); + +test("a pattern's lines that do not follow their counts make the hatch malformed", async () => { + const d = createDrawing({ units: "in" }); + d.hatch( + [ + [0, 0], + [1, 0], + [1, 1], + ], + { pattern: { spacing: 0.1, crossed: true } }, + ); + const dxf = toDXF(d.build()); + const at = dxf.lastIndexOf("AcDbHatch"); + for (const [from, to] of [ + ["78\r\n2\r\n", "78\r\n3\r\n"], + ["78\r\n2\r\n", "78\r\n1\r\n"], + ["79\r\n0\r\n", "79\r\n2\r\n"], + ["79\r\n0\r\n", "79\r\n0\r\n49\r\n1\r\n"], + ] as const) { + const bent = dxf.slice(0, at) + dxf.slice(at).replace(from, to); + assert.notEqual(bent, dxf); + const read = await readDXF(bent, { geometry: true }); + assert.deepEqual(JSON.parse(JSON.stringify(read.unread.malformed)), { + "HATCH whose pattern lines do not follow their counts": 1, + }); + } +}); + +test("a pattern whose lines would be written as 1e+100 is refused, and its repeats are paid for", () => { + const square: Point[] = [ + [0, 0], + [1, 0], + [1, 1], + ]; + const huge: Drawing = { + ...createDrawing({ units: "in" }).build(), + patterns: [ + { + name: "HUGE", + lines: [{ angle: 0, base: [0, 0], offset: [0, 1], dashes: [9.999999999999998e99, -1] }], + }, + ], + entities: [ + { kind: "hatch", layer: "0", loops: [{ points: square }], pattern: { name: "HUGE" } }, + ], + }; + assert.throws(() => toDXF(huge), /1e100/); + // One family of 32,767 dashes that 1,000 hatches name: lint pays for each hatch's. + const dashes = Array.from({ length: 32_767 }, (_, i) => (i % 2 === 0 ? 1 : -1)); + const many: Drawing = { + ...huge, + patterns: [{ name: "LONG", lines: [{ angle: 0, base: [0, 0], offset: [0, 1], dashes }] }], + entities: Array.from({ length: 1000 }, () => ({ + kind: "hatch" as const, + layer: "0", + loops: [{ points: square }], + pattern: { name: "LONG" }, + })), + }; + assert.ok(lintWithin(many, {}, 100_000).some((found) => found.rule === "check-capped")); +}); + +test("a line that crosses a thousand holes is cut in time", () => { + const holes = Array.from({ length: 1024 }, (_, i) => ({ + points: [ + [2 * i + 1, 0], + [2 * i + 2, 0], + [2 * i + 2, 0.5], + [2 * i + 1, 0.5], + ] as Point[], + })); + const d = createDrawing({ units: "in" }); + d.hatch( + [ + { + points: [ + [0, -1], + [2050, -1], + [2050, 1], + [0, 1], + ], + }, + ...holes, + ], + { pattern: { spacing: 0.25 } }, + ); + const started = performance.now(); + const found = (() => { + try { + return svgWithin(d.build(), {}, 20_000); + } catch (error) { + return error; + } + })(); + assert.ok(typeof found === "string" || found instanceof RangeError, String(found)); + assert.ok(performance.now() - started < timeLimit(2000)); +}); + +test("holes along an edge the lines run on are cut in time", () => { + // Each triangle's base lies on the outline's bottom edge, which a line runs along whole. + const count = 32_000; + const width = 2 * count + 2; + const holes = Array.from({ length: count }, (_, i) => ({ + points: [ + [2 * i + 1, 0], + [2 * i + 2, 0], + [2 * i + 1.5, 0.5], + ] as Point[], + })); + const drawing: Drawing = { + ...createDrawing({ units: "in" }).build(), + entities: [ + { + kind: "hatch", + layer: "0", + loops: [ + { + points: [ + [0, 0], + [width, 0], + [width, 3], + [0, 3], + ], + }, + ...holes, + ], + pattern: { spacing: 1 }, + }, + ], + }; + const started = performance.now(); + toSVG(drawing); + assert.ok(performance.now() - started < timeLimit(2000)); +}); diff --git a/test/read.test.ts b/test/read.test.ts index 551eb95..daefca9 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -1178,3 +1178,31 @@ test("A DXF comes back byte for byte from its document", async () => { assert.ok(document.references(layer).some((r) => r.code === 390)); assert.equal(document.names[document.sections[layer]!], "TABLES"); }); + +test("a hatch with a group that is not a number is counted, not read as NaN", async () => { + const d = createDrawing({ units: "in" }); + d.hatch([ + [0, 0], + [1, 0], + [1, 1], + ]); + d.hatch( + [ + [2, 0], + [3, 0], + [3, 1], + ], + { pattern: { spacing: 0.1 } }, + ); + const dxf = toDXF(d.build()); + // The first hatch's loop flags, and the second's pattern type. + const second = dxf.lastIndexOf("AcDbHatch"); + for (const bent of [ + dxf.replace("91\r\n1\r\n92\r\n2\r\n", "91\r\n1\r\n92\r\nx\r\n"), + dxf.slice(0, second) + dxf.slice(second).replace("76\r\n0\r\n", "76\r\n1e999\r\n"), + ]) { + assert.notEqual(bent, dxf); + const read = await readDXF(bent, { geometry: true }); + assert.deepEqual(plain(read.unread.malformed), { "HATCH with a number that is not finite": 1 }); + } +}); diff --git a/test/rules.test.ts b/test/rules.test.ts index cc47482..91a77be 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -7,12 +7,14 @@ import { DASHED, DrawingBuilder, DrawingError, + fromJSON, fromPaper, HIDDEN, inspectText, lint, measureText, toDXF, + toJSON, toSVG, viewportView, type Drawing, @@ -1359,3 +1361,137 @@ test("a paragraph's height, width, line spacing and codes are checked twice", () // @ts-expect-error: R12 holds no paragraph. assert.throws(() => r12.paragraph("NOTE", { at }), /no paragraphs to R12/); }); + +test("hatch patterns and a hatch's pattern are checked by the builder and by lint", () => { + const file = "*STRIPES, Dashed stripes\n45, 0,0, 0,0.25, 0.5,-0.25\n*STRIPES\n0, 0,0, 0,1\n"; + const box: Point[] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ]; + const d = createDrawing({ units: "in" }).patterns(file); + d.hatch(box, { pattern: { name: "stripes", scale: 2, angle: 30, origin: [1, 1] } }); + d.hatch(box, { pattern: { spacing: 0.5, crossed: true } }); + const built = d.build(); + // The first of a name in one file is added, and a hatch holds the name as the drawing has it. + assert.deepEqual(built.patterns, [ + { + name: "STRIPES", + description: "Dashed stripes", + lines: [{ angle: 45, base: [0, 0], offset: [0, 0.25], dashes: [0.5, -0.25] }], + }, + ]); + assert.deepEqual(built.entities[0], { + kind: "hatch", + layer: "0", + loops: [{ points: box }], + pattern: { name: "STRIPES", scale: 2, angle: 30, origin: [1, 1] }, + }); + assert.deepEqual(lint(built), []); + assert.deepEqual(fromJSON(toJSON(built)), built); + assert.equal("patterns" in createDrawing().build(), false); + // A later call replaces a pattern of the name, and keeps its spelling. + d.patterns([{ name: "Stripes", lines: [{ angle: 0, base: [0, 0], offset: [0, 1] }] }]); + assert.deepEqual(d.build().patterns, [ + { name: "STRIPES", lines: [{ angle: 0, base: [0, 0], offset: [0, 1] }] }, + ]); + + // The builder refuses what lint refuses, in its words. + const hatched = (pattern: unknown, patterns = built.patterns): Drawing => ({ + ...built, + ...(patterns ? { patterns } : {}), + entities: [{ kind: "hatch", layer: "0", loops: [{ points: box }], pattern: pattern as never }], + }); + const both = (pattern: unknown, expected: RegExp) => { + assert.throws(() => d.hatch(box, { pattern: pattern as never }), expected); + const found = lint(hatched(pattern)).map((x) => `${x.rule}: ${x.message}`); + assert.equal(found.length, 1, found.join("\n")); + assert.match(found[0]!, /^hatch-pattern: hatch #0: /); + assert.match(found[0]!, expected); + }; + both({ name: "BRICK" }, /"BRICK" is not defined\. tsdraft has no patterns of its own/); + both({ spacing: 0 }, /spacing must be a finite number greater than 0/); + both({ name: "STRIPES", scale: 1e-7 }, /scale: This value is written as 0/); + both({ name: "STRIPES", spacing: 1 }, /a name or a spacing, not both/); + both({ name: "STRIPES", crossed: true }, /crossed is for lines of the hatch's own/); + both({ spacing: 1, origin: [0, NaN] }, /origin must be a point/); + both({ spacing: 1, scale: 2 }, /scale is for a pattern by its name/); + both({ spacing: 1, zz: 1 }, /attern must be \{ name, scale\?/); + // The literal mistakes are compile errors too. + // @ts-expect-error: a spacing is greater than 0. + assert.throws(() => d.hatch(box, { pattern: { spacing: -1 } }), /greater than 0/); + // @ts-expect-error: and is not written as 0. + assert.throws(() => d.hatch(box, { pattern: { name: "STRIPES", scale: 1e-7 } }), /written as 0/); + // @ts-expect-error: a pattern has a name or a spacing. + assert.throws(() => d.hatch(box, { pattern: { name: "STRIPES", spacing: 1 } }), /not both/); + // @ts-expect-error: crossed goes with a spacing, and a scale with a name. + assert.throws(() => d.hatch(box, { pattern: { spacing: 1, scale: 2 } }), /scale is for/); + both({ spacing: 1e-6 }, /draws 4,000,001 lines .*more than the 1,000,000 tsdraft draws/); + // A line's base point at 10, scaled by 1e99, is placed at 1e100. + const big = [ + { name: "BIG", lines: [{ angle: 0, base: [10, 0] as Point, offset: [0, 1] as Point }] }, + ]; + const placed = { name: "BIG", scale: 1e99 }; + assert.throws( + () => createDrawing().patterns(big).hatch(box, { pattern: placed }), + /1e100 or more/, + ); + assert.match(lint(hatched(placed, big))[0]!.message, /1e100 or more/); + assert.deepEqual(lint(hatched({ name: "BIG", scale: 9e98 }, big)), []); + assert.match(lint(hatched({ name: "BRICK" }))[0]!.message, /through parsePatterns into/); + assert.throws(() => d.hatch(box, { pattern: { name: "BRICK" } }), /with patterns\(\) first/); + + // A definition of the drawing's patterns, by the builder and by lint. + const defined = (patterns: unknown[]) => + lint(hatched({ name: "STRIPES" }, patterns as never)).map((x) => `${x.rule}: ${x.message}`); + const line = { angle: 0, base: [0, 0], offset: [0, 1] }; + for (const [pattern, expected] of [ + [{ name: "", lines: [line] }, /Hatch pattern names cannot be empty/], + [{ name: "A*", lines: [line] }, /Hatch pattern names cannot contain/], + [{ name: "STRIPES", lines: [] }, /needs at least one line/], + [{ name: "STRIPES", lines: [{ ...line, offset: [1, 1e-7] }] }, /line 0: its offset across/], + [{ name: "STRIPES", lines: [{ ...line, dashes: [0, 0] }] }, /line 0: its dashes cannot all/], + [{ name: "STRIPES", lines: [{ ...line, angle: Infinity }] }, /line 0: its angle must be/], + [{ name: "STRIPES", lines: [{ ...line, base: [1e100, 0] }] }, /line 0: its base: .*1e100/], + ] as const) { + assert.throws(() => d.patterns([pattern as never]), expected); + const found = defined([pattern]); + assert.ok( + found.length >= 1 && found.every((x) => x.startsWith("hatch-pattern: ")), + String(found), + ); + assert.match(found[0]!, expected); + } + // Of two of a name, a hatch takes the first. + assert.deepEqual(defined([built.patterns![0], { ...built.patterns![0], name: "stripes" }]), [ + 'duplicate-hatch-pattern: Hatch pattern "stripes" is defined twice. A hatch finds its pattern by name whatever the case of its letters, as CAD programs do, and takes the first', + ]); + // A pattern file a line of which cannot be read, and R12, which has no hatches. + assert.throws(() => d.patterns("45, 0,0, 0,1"), /line 1 of the pattern file: a line before/); + assert.throws( + () => createDrawing({ dxf: "R12" }).patterns(file), + /no hatches or wipeouts to R12/, + ); + assert.match( + lint({ ...hatched(undefined), dxf: "R12", entities: [] })[0]!.message, + /^patterns: /, + ); +}); + +test("a hatch's pattern named SOLID is refused: a solid hatch has none", () => { + const d = createDrawing({ units: "in" }); + d.patterns("*SOLID, Solid fill\n45, 0,0, 0,.125\n"); + assert.throws( + () => + d.hatch( + [ + [0, 0], + [1, 0], + [1, 1], + ], + { pattern: { name: "Solid" } }, + ), + /SOLID is the name/, + ); +}); diff --git a/test/shape.test.ts b/test/shape.test.ts index c2e0cc6..49575c8 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -21,7 +21,9 @@ import { type Layer, type Layout, type LeaderStyle, + type HatchPattern, type Linetype, + type PatternLine, type Leader, type Polyline, type TextStyle, @@ -198,6 +200,7 @@ const kinds: { bulges: [0, 0.5, 0], }, ], + pattern: { name: "STRIPES", scale: 2, angle: 30, origin: [1, 1] }, id: "w1", ...styled, }, @@ -317,6 +320,9 @@ const keyed: Required< /** One of everything an R2018 drawing can hold, with every field of every object. */ const full: Required & { readonly linetypes: readonly [Required]; + readonly patterns: readonly [ + Required & { readonly lines: readonly [Required] }, + ]; readonly textStyles: readonly [Required]; // A style in decimal units leaves zeros out, and one in architectural units writes them. readonly dimensionStyles: readonly [ @@ -342,6 +348,13 @@ const full: Required & { imageFrame: false, wipeoutFrame: false, linetypes: [{ name: "DD", description: "Dash dot", pattern: [0.5, -0.25, 0, -0.25] }], + patterns: [ + { + name: "STRIPES", + description: "Dashed stripes", + lines: [{ angle: 45, base: [0, 0], offset: [0, 0.25], dashes: [0.5, -0.25, 0, -0.25] }], + }, + ], textStyles: [{ name: "NOTES", font: "Arial", widthFactor: 0.9, obliqueAngle: 10 }], dimensionStyles: [ { From 08f30a1c0b609893d890055e5d4f82c71860f321 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 15:20:44 -0500 Subject: [PATCH 16/35] Attributes of paragraph text Attributes of paragraph text: a block's attribute definition may hold text of more than one line, as the leading CAD app's multiple-line attributes do, and each insert places it as that app's own insert does. - `d.attribute(tag, at, { kind: "paragraph", width, ... })` defines one. Its value and each insert's hold the codes of paragraph text, checked as a paragraph's value is, wrap at its width and break at each line feed, and its box is placed by `align`, `valign`, `lineSpacing` and `lineSpacingStyle` as a paragraph's is. `AttributeDefinition` is `TextAttributeDefinition` or `ParagraphAttributeDefinition`, told apart by `kind`. - Each insert holds the attribute at its height in the insert, wrapped at the width times the same share, and, where the insert scales its block unevenly, with its characters widened by a code of the attribute's width factor before its value, in place of the style's. `placeAttribute` gives that paragraph in `paragraph`, a `PlacedAttributeParagraph`, and `attributeParagraph` the `Paragraph` drawn, or undefined for an attribute of one line. - The R2018 DXF writes it, `readDXF` reads it back as `ReadAttributeParagraph`, and `toSVG`, `toPDF`, `inspectText`, the extents and `lint` lay it out where the leading CAD app plots it. `lint` and the builder refuse a width or a line spacing on a definition of one line, and `lint` warns of a `\N` in an attribute's value, which has no columns. - A leaned line of paragraph text wraps a word as the leading CAD app does: as if its ink reached twice its last character's lean further, whatever its width factor. A line in a style with an oblique angle, or after `\Q`, may wrap a word earlier than before. - `lint` no longer throws on an attribute definition whose value is not a string when an insert of its block sets no value for it. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 6 +- CHANGELOG.md | 20 +++++ docs/blocks.md | 33 +++++++ docs/paragraphs.md | 7 +- docs/reading.md | 13 ++- src/blocks.ts | 133 +++++++++++++++++++++++++++- src/drawing.ts | 191 +++++++++++++++++++++++++++++++++++++--- src/dxf-r2018.ts | 99 ++++++++++++++++++++- src/extents.ts | 65 +++++++++++--- src/index.ts | 5 ++ src/inspect.ts | 9 +- src/lint.ts | 95 +++++++++++++++++--- src/paragraphs.ts | 23 ++++- src/read/check.ts | 16 ++++ src/read/dxf.ts | 27 ++++-- src/read/entities.ts | 88 ++++++++++++++++-- src/read/model.ts | 33 +++++++ src/rules.ts | 15 ++++ src/shape.ts | 18 +++- src/standard/lint.ts | 32 +++++-- test/blocks.test.ts | 180 ++++++++++++++++++++++++++++++++++++- test/bounded.test.ts | 39 ++++++-- test/paragraphs.test.ts | 83 +++++++++++++++++ test/read-agreement.ts | 105 +++++++++++++++++++--- test/read.test.ts | 11 +++ test/rules.test.ts | 78 ++++++++++++++++ test/shape.test.ts | 27 +++++- 27 files changed, 1345 insertions(+), 106 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f677207..d719a00 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,7 +62,11 @@ depends on a block of a cycle being open is not kept for another way in. What many places share is read once a boxer: the box of a list of entities, of a long list of points and of a leader, a long value's measure, and the inserts of a list. An insert's attributes are written as texts in the insert's - own coordinates, which `placeAttribute` works out from the numbers as they are written. An + own coordinates, which `placeAttribute` works out from the numbers as they are written. One of + paragraph text is the paragraph `attributeParagraph` gives in those coordinates, mirrored where + X runs the other way, which `eachDrawn` draws with the matrix of the space the insert is in, and + the boxer keeps apart from a block's other attributes, in the coordinates of its insert's + space, since an uneven scale lays it out again rather than stretching it. An attribute is stored on its definition's layer, and one on layer `0` draws as its insert's layer does. An insert on a frozen layer, or in a plot on a layer that does not plot, draws nothing of its block. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f8dde6..12d9632 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,26 @@ file's sort table draws a space or a block in, `drawOrder`; and whether wipeouts' frames show, `header.wipeoutFrame`. +- Attributes of paragraph text. `d.attribute(tag, at, { kind: "paragraph", width, ... })` defines + one, as CAD programs' multiple-line attributes: its value and each insert's hold the codes of + paragraph text, checked as a paragraph's value is, wrap at its width and break at each line + feed, and its box is placed by `align`, `valign`, `lineSpacing` and `lineSpacingStyle` as a + paragraph's is. `AttributeDefinition` is `TextAttributeDefinition` or + `ParagraphAttributeDefinition`, told apart by `kind`. Each insert holds the attribute as CAD + programs' own insert does: at its height in the insert, wrapped at the width times the same + share, and, where the insert scales its block unevenly, with its characters widened by a code + of the attribute's width factor before its value, in place of the style's. `placeAttribute` + gives that paragraph in `paragraph`, and `attributeParagraph` the `Paragraph` drawn. The R2018 + DXF writes it, `readDXF` reads it back as `ReadAttributeParagraph`, and `toSVG`, `toPDF`, + `inspectText`, the extents and `lint` lay it out where CAD programs plot it. `lint` and the + builder refuse a width, a line spacing or a style of paragraph text on a definition of one + line, and R12 holds no blocks. +- A leaned line of paragraph text wraps a word as CAD programs do: as if its ink reached twice its + last character's lean further, whatever its width factor. A line in a style with an oblique + angle, or after `\Q`, may wrap a word earlier than before. +- `lint` no longer throws on an attribute definition whose value is not a string when an insert + of its block sets no value for it. + - Leaders' notes, as CAD programs draw them. A note is laid out as paragraph text is, each line set by the ink of its letters, so its lines move where they plot by up to a quarter of their height from where earlier versions drew them. `attachment` takes every place CAD programs diff --git a/docs/blocks.md b/docs/blocks.md index 93cd085..bcf12e1 100644 --- a/docs/blocks.md +++ b/docs/blocks.md @@ -70,6 +70,39 @@ default. Each insert carries one attribute for every definition of its block. An attribute stays a field in CAD, in model space and on a layout: the leading CAD app's `-ATTEDIT` command changes its value, and the drawing keeps the new value when it is saved. +### Attributes of paragraph text + +With `kind: "paragraph"`, a definition holds paragraph text, as CAD programs' multiple-line +attributes do: its value and each insert's hold a [paragraph's](paragraphs.md) codes, a line feed +in either is written as `\P`, and the value wraps at `width` when it has one. It is placed as +`paragraph()` places a paragraph: `align` is `"left"`, `"center"` or `"right"`, `valign` is +`"top"`, the default, `"middle"` or `"bottom"`, and `lineSpacing` and `lineSpacingStyle` space its +lines. It has no columns, so a `\N` breaks the line as `\P` does, and `lint` warns of it. R2018 +only. + +```ts +d.block("NOTE", {}, () => + d.attribute("NOTE", [0, 0], { + kind: "paragraph", + value: "ALL WORK SHALL COMPLY\nWITH THE CODES", + width: 3, + height: 0.1, + valign: "middle", + }), +); +d.insert("NOTE", [10, 5], { attributes: { NOTE: "VERIFY IN THE FIELD" } }); +``` + +An insert holds each such attribute as a paragraph of its own, in its own coordinates: at its +point, turned with it, and as high and as wide as its scale makes the definition's. One that +scales its block unevenly sets the paragraph at the height a text attribute would have and wraps +it at the definition's width times the same share, and widens its characters by the code +`\W` of the attribute's width factor, to four decimals, before its value, in place of the +style's width factor. It keeps the style's oblique angle, and slants no letter by the insert. +`placeAttribute` gives that paragraph in `paragraph`, and `attributeParagraph(placed)` the +`Paragraph` drawn, which `toSVG`, `toPDF`, `inspectText` and the extents lay out as a paragraph +where the insert holds it. + ## Inserting a block `d.insert(block, at, options)` places a block with its base point at `at`, on the current diff --git a/docs/paragraphs.md b/docs/paragraphs.md index 26c6728..4a8657a 100644 --- a/docs/paragraphs.md +++ b/docs/paragraphs.md @@ -242,7 +242,8 @@ from the widths and the ink of each character that `FONT_METRICS` holds: come to no more than the width. The left of the line's first letter has no part in it. A word wider than the width stays whole and passes it. In a word that holds a stack, what follows the last stack stands for the word, or the stack where it ends the word. A tab goes with the word - after it where the line wraps. + after it where the line wraps. A leaned word's ink is taken to reach twice its last letter's + lean further, whatever its width factor. - With a width, a paragraph's first line starts at its left indent plus its first-line indent, never left of the box, its other lines at its left indent, and its words wrap at its right indent. A word that reaches the width itself leaves a line that starts at an indent or holds a @@ -339,5 +340,5 @@ when the font is not the style's own or the value holds a code tsdraft does not ## Not yet The spacing of the characters, `\T`, an overline, stacked parts in lower case, tab stops that align text by its right, its -center or a decimal point, columns that flow from right to left, and attributes of more than one -line. +center or a decimal point, and columns that flow from right to left. Attributes of paragraph text +are in [Blocks](blocks.md#attributes-of-paragraph-text). diff --git a/docs/reading.md b/docs/reading.md index a7e82be..67367ae 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -109,7 +109,8 @@ leader: - `insert`: its block, by name and by the handle of its record in `blockHandle`, its point, scale and rotation, `tags`, and with `geometry` its `attributes`: each a text with its `tag` and its `value` where the file places it, and `invisible` for one that does not show. An - insert with columns and rows is counted under `other`. + attribute of paragraph text has its `paragraph` too, below, and its `value` is the paragraph's. + An insert with columns and rows is counted under `other`. - `mtext`: a paragraph text with its point, height, width, attachment, rotation, from its direction or else from group 50 in degrees, style, value, its formatting codes kept, `lineSpacing`, its line spacing factor, 1 where the file @@ -214,6 +215,16 @@ from: `backward` and `upsideDown` say a text is drawn mirrored along its baseline or across it. A text seen from below reads backward. +An attribute and an attribute definition of paragraph text, which the leading CAD app holds as a +text of one line with no value and a paragraph text after it, have `paragraph`, the paragraph +that app draws in the text's place, as an `mtext` holds one: its `at`, in the world's coordinates, +`height`, `width`, `attachment`, `rotation`, the direction of its lines, `style`, `lineSpacing` +and `lineSpacingStyle`, and `mirrored` for one seen from below, as an insert that mirrors its +block holds it, whose lines run along `rotation` with their tops to its right. The value of the +attribute, and the `default` of the definition, are the paragraph's, with its codes. Its text +keeps its place, justified by the attachment. One whose paragraph lies in another plane is +counted under `other`. + ### What a read keeps What the spaces draw counts against one budget, `GEOMETRY_ITEMS`, 400,000 items, and the blocks diff --git a/src/blocks.ts b/src/blocks.ts index a31e1a2..e14b42c 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -6,6 +6,8 @@ import type { Drawing, Entity, Insert, + Paragraph, + ParagraphAttributeDefinition, Point, Text, TextStyle, @@ -194,6 +196,25 @@ export interface PlacedAttribute { /** True for an insert with one negative scale, which the leading CAD app holds with an extrusion of 0, 0, -1. */ readonly mirrored: boolean; readonly definition: AttributeDefinition; + /** For a definition of paragraph text, the paragraph the leading CAD app holds for it. */ + readonly paragraph?: PlacedAttributeParagraph; +} + +/** + * The paragraph an insert makes of a definition of paragraph text, placed at the attribute's + * `at` and turned by its `rotation`, in the definition's text style. An insert that scales its + * block unevenly sets the paragraph at its height in the insert, wraps it at the definition's + * width times the share of its height that is left, and sets its characters at the attribute's + * width factor, to four decimals, by a code before its value, in the place of the style's: the + * leading CAD app slants none of them by the insert, and keeps the style's oblique angle. + */ +export interface PlacedAttributeParagraph { + /** The width its lines wrap at, or undefined for none. */ + readonly width: number | undefined; + /** The value as it is laid out, after the code of an uneven scale. */ + readonly value: string; + /** True for an insert that scales its block unevenly. */ + readonly uneven: boolean; } /** @@ -228,8 +249,11 @@ export function placeAttribute( ? [-matrix[0], matrix[1], -matrix[2], matrix[3], -matrix[4], matrix[5]] : matrix; const at: Point = [a * x + c * y + e, b * x + d * y + f]; - const widthFactor = written(style?.widthFactor ?? 1); - const obliqueAngle = written(style?.obliqueAngle ?? 0); + // A definition of paragraph text holds a text of no width factor or slant of its own: its + // paragraph is drawn in its style's. + const own = definition.kind === "paragraph" ? undefined : style; + const widthFactor = written(own?.widthFactor ?? 1); + const obliqueAngle = written(own?.obliqueAngle ?? 0); const height = written(definition.height); const turn = (written(definition.rotation) * Math.PI) / 180; const slant = Math.tan((obliqueAngle * Math.PI) / 180); @@ -243,7 +267,7 @@ export function placeAttribute( const length = Math.hypot(along[0], along[1]); const rise = (along[0] * up[1] - along[1] * up[0]) / length; const run = (along[0] * up[0] + along[1] * up[1]) / length; - return { + const placed = { tag: definition.tag, value, layer: definition.layer, @@ -255,8 +279,79 @@ export function placeAttribute( widthFactor: (widthFactor * length) / rise, obliqueAngle: (Math.atan2(run, rise) * 180) / Math.PI, }; + if (definition.kind !== "paragraph") return placed; + const uneven = Math.abs(written(sx)) !== Math.abs(written(sy)); + // A value or a width of the wrong type, which `lint` reports, is laid out as none. + const given: unknown = definition.width; + const width = typeof given === "number" ? written(given) * rise : undefined; + const text = typeof value === "string" ? value : ""; + return { + ...placed, + paragraph: { + width, + value: uneven ? `\\W${placed.widthFactor.toFixed(4)};${text}` : text, + uneven, + }, + }; +} + +/** + * True for a definition of paragraph text and an insert whose numbers `placeAttribute` can place. + * A walk draws nothing of any other, which `lint` reports. + */ +export function placeable(definition: AttributeDefinition, insert: Insert): boolean { + const number = (value: unknown): boolean => typeof value === "number"; + const point = (value: unknown): boolean => + Array.isArray(value) && number(value[0]) && number(value[1]); + const d = definition as unknown as Readonly>; + const i = insert as unknown as Readonly>; + return ( + point(d["at"]) && + number(d["height"]) && + number(d["rotation"]) && + point(i["at"]) && + (i["scale"] === undefined || point(i["scale"])) && + (i["rotation"] === undefined || number(i["rotation"])) + ); +} + +/** + * The paragraph an insert draws for a definition of paragraph text, in the insert's own + * coordinates, or for a mirrored insert in the coordinates `placeAttribute` gives, where X runs + * the other way. It reads the fields a paragraph has, so each placement costs the same whatever + * else the definition holds. + */ +export function attributeParagraph(placed: PlacedAttribute): Paragraph | undefined { + if (!placed.paragraph) return undefined; + const definition = placed.definition as ParagraphAttributeDefinition; + const paragraph: Record = { kind: "paragraph" }; + const given = definition as unknown as Readonly>; + for (const field of PARAGRAPH_FIELDS) { + if (Object.hasOwn(given, field)) paragraph[field] = given[field]; + } + paragraph["at"] = placed.at; + paragraph["height"] = placed.height; + paragraph["rotation"] = placed.rotation; + paragraph["value"] = placed.paragraph.value; + if (placed.paragraph.width === undefined) delete paragraph["width"]; + else paragraph["width"] = placed.paragraph.width; + return paragraph as unknown as Paragraph; } +/** The fields of a paragraph that a definition of paragraph text gives the one an insert draws. */ +const PARAGRAPH_FIELDS = [ + "layer", + "style", + "width", + "align", + "valign", + "lineSpacing", + "lineSpacingStyle", +] as const; + +/** The matrix that takes a mirrored attribute's coordinates, where X runs the other way, to the insert's. */ +export const MIRRORED: Matrix = [-1, 0, 0, 1, 0, 0]; + /** The value an insert gives an attribute: its own for the tag, or the definition's default. */ export function attributeValue(insert: Insert, definition: AttributeDefinition): string { const set = insert.attributes; @@ -615,6 +710,11 @@ export interface Placement { readonly from: Referenced | undefined; /** For the text of an insert's attribute, the attribute's tag. */ readonly attribute?: string; + /** + * True for an attribute of paragraph text an insert scales unevenly, whose value, with the code + * before it, is no string the drawing holds: whatever lays it out pays as `made` says. + */ + readonly made?: boolean; } /** A block the walk of an insert is in, and how far it has read it. */ @@ -624,6 +724,10 @@ interface Entered { readonly items: readonly Entity[]; readonly definitions: readonly AttributeDefinition[]; readonly matrix: Matrix; + /** The matrix of the space the insert is in, which an attribute of paragraph text is drawn with. */ + readonly outer: Matrix | undefined; + /** The block's base point. */ + readonly base: Point | undefined; readonly layer: LayerRef; readonly inside: Referenced | undefined; /** The blocks its inserts find theirs among. */ @@ -650,7 +754,8 @@ function holds(list: readonly unknown[], index: number): boolean { * block, and any other on its own layer of the referenced drawing. Inside a referenced drawing an * insert of one of its attachments draws the drawing `referencedTree` gives for it, the same way, * and one of its overlays draws nothing, as that app loads no overlay of a referenced drawing. An - * xref with no drawing given draws nothing. + * xref with no drawing given draws nothing. Each definition of paragraph text is drawn as the + * paragraph `attributeParagraph` gives, in the coordinates of the space its insert is in. * * @param isFrozen - True for a layer that hides everything an insert on it draws: a frozen * layer, and in a plot a layer that does not plot. @@ -705,6 +810,8 @@ export function eachDrawn( items: Array.isArray(items) ? items : [], definitions: Array.isArray(definitions) ? definitions : [], matrix: outer ? compose(outer, own) : own, + outer, + base: block?.base, layer, // What the insert holds names the layers, linetypes and text styles of this drawing. inside: referenced ?? from, @@ -741,6 +848,24 @@ export function eachDrawn( continue; } if (!spend(1 + lookupCost(at.insert, definition))) return false; + if (definition.kind === "paragraph") { + if (!placeable(definition, at.insert)) continue; + const placed = placeAttribute(definition, undefined, at.insert, at.base); + const flip = placed.mirrored + ? at.outer + ? compose(at.outer, MIRRORED) + : MIRRORED + : undefined; + draw(attributeParagraph(placed)!, { + matrix: flip ?? at.outer, + layer: layerOf(definition.layer), + insertLayer: at.layer, + from: inside, + attribute: definition.tag, + made: placed.paragraph!.uneven, + }); + continue; + } draw(attributeText(at.insert, definition), { matrix: at.matrix, layer: layerOf(definition.layer), diff --git a/src/drawing.ts b/src/drawing.ts index 7c79e38..2238c84 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -73,7 +73,10 @@ import { canonical } from "./json.ts"; import { DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; import { arcProblem, + ATTRIBUTE_KIND, ATTRIBUTES_SHAPE, + PARAGRAPH_ONLY, + paragraphOnlyProblem, attributeTagProblem, blockCycleProblem, blockNameProblem, @@ -1086,10 +1089,13 @@ export interface DimensionStyle { /** * An attribute definition of a block: a text that each insert of the block carries with a - * value of its own, under a tag. It is placed and justified as a `Text` is, in the block's - * coordinates. + * value of its own, under a tag, in the block's coordinates. One of one line is placed and + * justified as a `Text` is, and one of paragraph text as a `Paragraph` is. */ -export interface AttributeDefinition { +export type AttributeDefinition = TextAttributeDefinition | ParagraphAttributeDefinition; + +/** What an attribute definition of one line and one of paragraph text share. */ +interface AttributeDefinitionBase { /** The name of the attribute in its block, with no lower-case letter a to z. */ readonly tag: string; /** What CAD asks for when the block is inserted by hand. Defaults to the tag. */ @@ -1099,17 +1105,43 @@ export interface AttributeDefinition { /** The layer of the attribute on each insert. `"0"` stands for the insert's layer. */ readonly layer: string; readonly at: Point; + /** The height of a capital. */ readonly height: number; /** Degrees counterclockwise. */ readonly rotation: number; /** A text style of the drawing. Defaults to `"Standard"`. */ readonly style?: string; +} + +/** An attribute definition of one line, placed and justified as a `Text` is. */ +export interface TextAttributeDefinition extends AttributeDefinitionBase { + /** Defaults to `"text"`. */ + readonly kind?: "text"; /** Defaults to `"left"`. */ readonly align?: TextAlign; /** Defaults to `"baseline"`. */ readonly valign?: TextVerticalAlign; } +/** + * An attribute definition of paragraph text: its value, and each insert's, holds the codes of a + * `Paragraph`'s, wraps at `width` and breaks at each `\P`, and its box is placed by `at`, `align` + * and `valign` as a paragraph's is. R2018 only. + */ +export interface ParagraphAttributeDefinition extends AttributeDefinitionBase { + readonly kind: "paragraph"; + /** The width its lines wrap at. Missing, its lines break only at `\P`. */ + readonly width?: number; + /** Defaults to `"left"`. */ + readonly align?: ParagraphAlign; + /** Defaults to `"top"`. */ + readonly valign?: ParagraphVerticalAlign; + /** A factor of the spacing of its lines, from 0.25 to 4. Defaults to 1. */ + readonly lineSpacing?: number; + /** Defaults to `"at-least"`. */ + readonly lineSpacingStyle?: LineSpacingStyle; +} + /** * A block: entities drawn once, under a name, and placed any number of times by inserts. Its * coordinates are its own, and `base` is the point of them that an insert puts at its `at`. @@ -1821,10 +1853,12 @@ export interface BlockOptions { /** * The options of `attribute()`: the definition's default value and prompt, and its height, - * rotation, style and justification, which are a text's. + * rotation, style and justification, which are a text's, or with `kind: "paragraph"` a + * paragraph's. * * @typeParam D - The text style as written, a name or a definition, checked as a text's is. * @typeParam R - The role as written. + * @typeParam Q - The default value of paragraph text as written, checked as a paragraph's is. */ export type AttributeOptions< H extends number = number, @@ -1832,20 +1866,58 @@ export type AttributeOptions< D extends TextStyleValue = TextStyleDefinition, Z extends Standard | undefined = undefined, R extends string = string, -> = AttributeFields & Sized, TextStyleChoice>; + Q extends string = string, + N extends number = number, + F extends number = number, +> = (TextAttributeFields | ParagraphAttributeFields) & + Sized, TextStyleChoice>; /** What an attribute definition holds besides its role, height and style. */ interface AttributeFields { - /** The value of an insert that does not set the attribute. Defaults to `""`. */ - readonly value?: string; /** What CAD asks for when the block is inserted by hand. Defaults to the tag. */ readonly prompt?: string; /** Degrees counterclockwise. */ readonly rotation?: number; +} + +/** What a definition of one line holds besides its role, height and style. */ +interface TextAttributeFields extends AttributeFields { + /** Defaults to `"text"`. */ + readonly kind?: "text"; + /** The value of an insert that does not set the attribute. Defaults to `""`. */ + readonly value?: string; /** Where `at` is along the text's line. Defaults to `"left"`. */ readonly align?: TextAlign; /** Where `at` is up and down the text's line. Defaults to `"baseline"`. */ readonly valign?: TextVerticalAlign; + /** Fields of paragraph text alone, which an attribute of one line never has. */ + readonly width?: never; + readonly lineSpacing?: never; + readonly lineSpacingStyle?: never; +} + +/** What a definition of paragraph text holds besides its role, height and style. R2018 only. */ +interface ParagraphAttributeFields< + Q extends string, + N extends number, + F extends number, +> extends AttributeFields { + readonly kind: "paragraph"; + /** + * The value of an insert that does not set the attribute, with a paragraph's codes: a line + * feed in it is written as `\P`. Defaults to `""`. + */ + readonly value?: ParagraphValue; + /** The width its lines wrap at. Missing, its lines break only at a line feed. */ + readonly width?: Positive; + /** Where `at` is across the box, and how the lines are set in it. Defaults to `"left"`. */ + readonly align?: ParagraphAlign; + /** Where `at` is up and down the box. Defaults to `"top"`. */ + readonly valign?: ParagraphVerticalAlign; + /** A factor of the spacing of its lines, from 0.25 to 4. Defaults to 1. */ + readonly lineSpacing?: LineSpacing; + /** Defaults to `"at-least"`. */ + readonly lineSpacingStyle?: LineSpacingStyle; } /** @@ -3780,7 +3852,8 @@ export class DrawingBuilder< /** * Adds an attribute definition to the block being drawn: a text that each insert of the * block carries with a value of its own, under `tag`. It is placed and justified as `text()` - * places a text, and goes on the current layer. + * places a text, or with `kind: "paragraph"` as `paragraph()` places a paragraph, whose value + * and each insert's hold a paragraph's codes, and goes on the current layer. */ attribute< T extends string, @@ -3788,10 +3861,13 @@ export class DrawingBuilder< S extends string = string, const D extends TextStyleValue = TextStyleDefinition, R extends string = string, + Q extends string = string, + N extends number = number, + F extends number = number, >( tag: V extends "R12" ? R12Blocks : AttributeTag, at: Point, - options: AttributeOptions = {}, + options: AttributeOptions = {}, ): this { const requested: unknown = tag; const open = this.#open; @@ -3814,7 +3890,23 @@ export class DrawingBuilder< const problem = typeof prompt === "string" ? textProblem(prompt) : "must be a string"; if (problem) refuse("text", `prompt: ${problem}`); } - const fields = this.#textFields(at, options.value ?? "", options as unknown as TextOptions); + const kind: unknown = options.kind; + if (kind !== undefined && kind !== "text" && kind !== "paragraph") { + refuse("attribute", ATTRIBUTE_KIND); + } + if (kind !== "paragraph") { + const given = options as unknown as Readonly>; + for (const field of PARAGRAPH_ONLY) { + if (given[field] !== undefined) refuse("attribute", paragraphOnlyProblem(field)); + } + } + const fields = + kind === "paragraph" + ? this.#paragraphFields( + at, + options as unknown as ParagraphAttributeFields & TextOptions, + ) + : this.#textFields(at, options.value ?? "", options as unknown as TextOptions); this.#claim( definitionHandle(open.name, named), `the attribute ${JSON.stringify(named)} of the block ${JSON.stringify(open.name)}`, @@ -3824,7 +3916,7 @@ export class DrawingBuilder< ...(prompt === undefined ? {} : { prompt: prompt as string }), layer: this.#current, ...fields, - }); + } as AttributeDefinition); if (options.role !== undefined) open.roles = true; } catch (thrown) { const about = typeof requested === "string" ? { attribute: requested } : {}; @@ -3929,8 +4021,12 @@ export class DrawingBuilder< if (set !== undefined) { const values: Record = {}; for (const [tag, value] of Object.entries(set as Record)) { - if (!definitions.some((definition) => definition.tag === tag)) { - refuse("undefined-attribute", undefinedAttributeProblem(tag, placed.name)); + const definition = definitions.find((d) => d.tag === tag); + if (!definition) refuse("undefined-attribute", undefinedAttributeProblem(tag, placed.name)); + if (definition!.kind === "paragraph") { + const about = `attribute ${JSON.stringify(tag)}: `; + values[tag] = this.#paragraphValue(value, definition!.style, "paragraph", about); + continue; } const problem = typeof value === "string" ? textProblem(value) : "must be a string"; if (problem) refuse("text", `attribute ${JSON.stringify(tag)}: ${problem}`); @@ -5512,6 +5608,75 @@ export class DrawingBuilder< return text; } + /** + * The fields of a definition of paragraph text: its point and value, and the height, rotation, + * style, width, justification and line spacing its options give, each checked as a + * paragraph's. + */ + #paragraphFields( + at: Point, + options: ParagraphAttributeFields & TextOptions, + ): Omit { + const { align, valign, ...rest } = options as unknown as Record; + const placed = this.#textFields(at, "", rest as unknown as TextOptions); + const definition: Record = { + kind: "paragraph", + at: placed.at, + height: placed.height, + rotation: placed.rotation, + ...(placed.style === undefined ? {} : { style: placed.style }), + value: this.#paragraphValue(options.value ?? "", placed.style, "attribute"), + }; + if (options.width !== undefined) definition["width"] = positive(options.width, "width"); + const { lineSpacing, lineSpacingStyle } = options as unknown as Record; + for (const [field, chosen, plain] of [ + ["align", align, "left"], + ["valign", valign, "top"], + ["lineSpacingStyle", lineSpacingStyle, "at-least"], + ] as const) { + if (chosen === undefined) continue; + const choiceProblem = paragraphChoiceProblem(field, chosen); + if (choiceProblem) + refuse(field === "lineSpacingStyle" ? "paragraph" : "text-align", choiceProblem); + if (chosen !== plain) definition[field] = chosen; + } + if (lineSpacing !== undefined) { + const spacingProblem = lineSpacingProblem(lineSpacing); + if (spacingProblem) refuse("paragraph", spacingProblem); + if (lineSpacing !== 1) definition["lineSpacing"] = lineSpacing; + } + return definition as unknown as Omit; + } + + /** + * A value of paragraph text as the drawing holds it, with each line feed as `\P`, checked as a + * paragraph's in the font of `style`, or refused under `rule`. + */ + #paragraphValue(given: unknown, style: string | undefined, rule: LintRule, about = ""): string { + if (typeof given !== "string") + return refuse(rule, `${about}A paragraph's value must be a string`); + // A backslash would escape the `\` of the `\P` a line feed becomes, as the type refuses it. + let backslashes = 0; + for (let i = 0; i < given.length; i++) { + const code = given.charCodeAt(i); + if (code === 92) backslashes++; + else { + if (code === 10 && backslashes % 2 === 1) { + return refuse(rule, `${about}${paragraphUnknownCode("\n")}`); + } + backslashes = 0; + } + } + const value = given.replaceAll("\n", "\\P"); + const font = + style === undefined + ? STANDARD_FONT + : (this.#textStyles.get(layerKey(style))?.font ?? STANDARD_FONT); + const problem = paragraphProblemIn(parseParagraph(value), font); + if (problem) refuse(rule, `${about}${problem}`); + return value; + } + /** * The height and text style of a text with a role, where it is drawn: the role's height in a * block and on a layout, and `view.paper` of it in model space. Undefined for a text with no diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 8cbf6aa..cb1c100 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -5,6 +5,7 @@ import { blockHandles, blocksByKey, placeAttribute, + type PlacedAttribute, } from "./blocks.ts"; import { arrowheadInfo, @@ -37,6 +38,7 @@ import { } from "./dimensions.ts"; import type { AttributeDefinition, + ParagraphAttributeDefinition, Block, DimensionStyle, Drawing, @@ -103,10 +105,11 @@ import { PLOTTER, type PaperInfo, } from "./papers.ts"; -import { fontInfo, STANDARD_TEXT_STYLE } from "./fonts.ts"; +import { fontInfo, STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { ID_HANDLE_SEED, validIdHandle } from "./handles.ts"; import { dxfOnce, dxfText, fifteenDigits, fmt, readable, written, writtenAngle } from "./format.ts"; import { layerKey, layerZeroFirst } from "./layers.ts"; +import { layoutText } from "./measure.ts"; import { layoutParagraph, lineSpacingStyleCode, @@ -608,6 +611,10 @@ export function toDXFR2018( if (paper) g(67, 1); g(8, definition.layer); g(100, "AcDbText"); + if (definition.kind === "paragraph") { + writeParagraphAttribute(g, definition, styleOf(definition.style), placed, undefined); + continue; + } writeTextFields(g, { ...definition, ...placed }, styleOf(definition.style), placed); g(100, "AcDbAttribute"); writeAttributeFields(g, definition, undefined); @@ -663,6 +670,11 @@ export function toDXFR2018( g(100, "AcDbEntity"); g(8, definition.layer); g(100, "AcDbText"); + if (definition.kind === "paragraph") { + const prompt = definition.prompt ?? definition.tag; + writeParagraphAttribute(g, definition, styleOf(definition.style), undefined, prompt); + continue; + } writeTextFields(g, definition, styleOf(definition.style), undefined); g(100, "AcDbAttributeDefinition"); writeAttributeFields(g, definition, definition.prompt ?? definition.tag); @@ -1064,7 +1076,8 @@ function writeInsert( /** * The fields a text, an attribute definition and an attribute share, up to the justification - * across the line. `placed` is what an insert makes of an attribute's definition. + * across the line. `placed` is what an insert makes of an attribute's definition. `start` is a + * first point written in place of `at`. */ function writeTextFields( g: Group, @@ -1073,8 +1086,13 @@ function writeTextFields( placed: | { readonly widthFactor: number; readonly obliqueAngle: number; readonly mirrored: boolean } | undefined, + start?: readonly [x: string, y: string], ): void { - point(g, 10, ...e.at); + if (start) { + g(10, start[0]); + g(20, start[1]); + g(30, 0); + } else point(g, 10, ...e.at); g(40, e.height); g(1, dxfText(e.value)); if (e.rotation !== 0) g(50, e.rotation); @@ -1108,6 +1126,81 @@ function writeAttributeFields( g(280, 1); // the attribute keeps its place in the block } +/** + * Writes an attribute definition of paragraph text, with its prompt, or an insert's attribute of + * one, as `placed` gives it, after its subclass of a text: the text it would be as a line, which + * holds no value, then the paragraph the leading CAD app draws, as an embedded object. The + * attribute's paragraph is in the drawing's coordinates, also where the insert mirrors it. + */ +function writeParagraphAttribute( + g: Group, + definition: ParagraphAttributeDefinition, + style: TextStyle | undefined, + placed: PlacedAttribute | undefined, + prompt: string | undefined, +): void { + const uneven = placed?.paragraph?.uneven === true; + const at = placed?.at ?? definition.at; + const mirrored = placed?.mirrored === true; + const height = placed?.height ?? definition.height; + const rotation = placed?.rotation ?? definition.rotation; + const valign = TEXT_VALIGN_OF[definition.valign ?? "top"]; + // The leading CAD app holds the text where a text of no value starts, worked out from its point + // as written, and keeps that point from a DXF: the height below it at the top, half of it in the + // middle, and the font's descent above it at the bottom. + const font = style?.font ?? STANDARD_FONT; + const up = layoutText({ value: "", height: written(height), font, valign }).baseline; + const turn = written(rotation) / (180 / Math.PI); + const start = [ + fifteenDigits(written(at[0]) - up * Math.sin(turn)), + fifteenDigits(written(at[1]) + up * Math.cos(turn)), + ] as const; + writeTextFields( + g, + { at, height, value: "", rotation, align: definition.align ?? "left", valign }, + style, + { + widthFactor: uneven ? placed.widthFactor : 1, + obliqueAngle: uneven ? placed.obliqueAngle : 0, + mirrored, + }, + start, + ); + g(100, prompt === undefined ? "AcDbAttribute" : "AcDbAttributeDefinition"); + g(280, 0); // version + if (prompt !== undefined) g(3, dxfText(prompt)); + g(2, dxfText(definition.tag)); + g(70, 0); // visible, and asked for on insertion + g(74, TEXT_VERTICAL_ALIGNS.indexOf(valign)); + g(280, 1); // the attribute keeps its place in the block + g(71, prompt === undefined ? 2 : 4); // of paragraph text, an attribute or a definition + g(72, 0); + const [x, y] = mirrored ? [-at[0], at[1]] : at; + point(g, 11, x, y); + g(101, "Embedded Object"); + point(g, 10, x, y); + g(40, height); + g(41, (placed ? placed.paragraph?.width : definition.width) ?? 0); + g(46, 0); // no height of its own + g(71, paragraphAttachment(definition)); + g(72, 1); // left to right + writeMtextValue(g, placed?.paragraph?.value ?? definition.value); + g(7, style?.name ?? STANDARD_TEXT_STYLE); + if (mirrored) point3(g, 210, 0, 0, -1); + const [cos, sin] = paragraphDirection(rotation); + const across = mirrored ? -cos : cos; + if (across !== 1 || sin !== 0) { + g(11, fifteenDigits(across)); + g(21, fifteenDigits(sin)); + g(31, 0); + } + g(73, lineSpacingStyleCode(definition)); + g(44, definition.lineSpacing ?? 1); +} + +/** The vertical justification of the text a paragraph attribute would be as a line. */ +const TEXT_VALIGN_OF = { top: "top", middle: "middle", bottom: "bottom" } as const; + /** * Writes an entity. `style` is the text style of a text that is not in `Standard`, and `paper` * is true for an entity of a layout. diff --git a/src/extents.ts b/src/extents.ts index dae6c4f..663fd9c 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -1,10 +1,13 @@ import { + attributeParagraph, attributeText, blocksByKey, compose, insertMatrix, isDefinition, lookupCost, + placeAttribute, + placeable, type LayerRef, type Matrix, type Referenced, @@ -45,6 +48,8 @@ import { filled } from "./shape.ts"; type Bounds = [number, number, number, number]; +const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0]; + /** * The most work one boxer does again for what a drawing repeats: each attribute an insert places * past its first `FREE`, one more for each 256 characters of a tag it looks up among an insert's @@ -168,8 +173,10 @@ interface Child { readonly held: Held; /** From the inserted block's coordinates to the block's that holds the insert. */ readonly matrix: Matrix; - /** The box of the insert's attributes, in the inserted block's coordinates. */ + /** The box of the insert's attributes of one line, in the inserted block's coordinates. */ readonly attributes: Bounds; + /** The box of its attributes of paragraph text, in the coordinates of the block that holds it. */ + readonly paragraphs: Bounds; } /** @@ -276,7 +283,7 @@ export function boxer( type Add = (x: number, y: number) => void; /** The points that bound what an entity that is no insert draws, given to `add`. */ - const shape = (e: Exclude, from: Names, add: Add): void => { + const shape = (e: Exclude, from: Names, add: Add, made = false): void => { switch (e.kind) { case "line": add(...e.from); @@ -314,14 +321,14 @@ export function boxer( const mask = maskOf(e.mask); if (mask === undefined) { // A long value laid out again is paid for first; a box already kept is mapped alone. - const again = paragraphs.boxAgain(paragraph); + const again = made ? paragraphs.boxMade(paragraph) : paragraphs.boxAgain(paragraph); if (again > 0 && !spend(again)) break; for (const [x, y] of paragraphs.box(paragraph) ?? []) add(x, y); break; } // A mask reaches past the ink, and hides what is drawn before it there. Both boxes come // from one layout, kept for a long value, whose mask's box is read once. - const again = paragraphs.again(paragraph); + const again = made ? paragraphs.made(paragraph) : paragraphs.again(paragraph); if (again > 0 && !spend(again)) break; const layout = paragraphs.layout(paragraph); if (layout.ink) { @@ -543,12 +550,13 @@ export function boxer( return found; }; /** - * Gives `add` the points of the attributes an insert places, in its block's coordinates, the - * first `FREE` of them free of the limit. A value the insert holds is read once for each time - * the insert is, so only a definition's value, which each insert without one repeats, is paid - * for by its length. False when the limit stopped it. + * Gives `add` the points of the attributes an insert places, those of one line in its block's + * coordinates and those of paragraph text to `addPlaced`, in the coordinates of the space the + * insert is in, the first `FREE` of them free of the limit. A value the insert holds is read + * once for each time the insert is, so only a definition's value, which each insert without one + * repeats, is paid for by its length. False when the limit stopped it. */ - const attributes = (insert: Insert, held: Held, add: Add): boolean => { + const attributes = (insert: Insert, held: Held, add: Add, addPlaced: Add): boolean => { if (!held.block) return true; const from = names(held.inside); const listed = definitionsOf(held.block); @@ -560,11 +568,28 @@ export function boxer( const cost = (i < FREE ? 0 : 1) + lookupCost(insert, definition) + - (repeated ? Math.floor(Math.min(value.value.length, LONG) / 32) : 0); + (repeated && typeof value.value === "string" + ? Math.floor(Math.min(value.value.length, LONG) / 32) + : 0); if (cost > 0 && !spend(cost)) return false; const layer = definition.layer; const hidden = layer === "0" ? held.hidden : isHidden(layerOf(layer, held.inside)); - if (!hidden) shape(value, from, add); + if (hidden) continue; + if (definition.kind !== "paragraph") { + shape(value, from, add); + continue; + } + // Laid out where the insert puts it, and mirrored back where the insert mirrors it. + if (!placeable(definition, insert)) continue; + const placed = placeAttribute(definition, undefined, insert, held.block.base); + const flip = placed.mirrored ? -1 : 1; + // Under an uneven scale its value is one the drawing does not hold. + shape( + attributeParagraph(placed)!, + from, + (x, y) => addPlaced(flip * x, y), + placed.paragraph!.uneven, + ); } return true; }; @@ -692,11 +717,18 @@ export function boxer( const inner = placedBy(item, held, false); if (!inner) continue; const box = empty(); - attributes(item, inner, (x, y) => include(box, x, y)); + const placed = empty(); + attributes( + item, + inner, + (x, y) => include(box, x, y), + (x, y) => include(placed, x, y), + ); children.push({ held: inner, matrix: insertMatrix(item, inner.block?.base), attributes: box, + paragraphs: placed, }); } held.children = children; @@ -778,6 +810,7 @@ export function boxer( } if (frame.again && !spend(1)) return undefined; add(frame, child.attributes, child.matrix, sizeOf(child.attributes), 1); + add(frame, child.paragraphs, IDENTITY, sizeOf(child.paragraphs), 0); const inner = flats.get(child.held); if (inner) add(frame, inner.box, child.matrix, inner.size, inner.depth + 1, inner.rough); else { @@ -849,6 +882,7 @@ export function boxer( if (open.has(child.held.held)) continue; const m = compose(at.m, child.matrix); if (child.attributes[0] !== Infinity) mapCorners(into, child.attributes, m); + if (child.paragraphs[0] !== Infinity) mapCorners(into, child.paragraphs, at.m); if (!pay(1)) return false; walkInto(child.held, m, into); continue; @@ -967,7 +1001,12 @@ export function boxer( const matrix = insertMatrix(e, held.block?.base); place(held, matrix, box); const [a, b, c, d, x0, y0] = matrix; - attributes(e, held, (x, y) => include(box, a * x + c * y + x0, b * x + d * y + y0)); + attributes( + e, + held, + (x, y) => include(box, a * x + c * y + x0, b * x + d * y + y0), + (x, y) => include(box, x, y), + ); } boxing = undefined; return box[0] === Infinity ? undefined : box; diff --git a/src/index.ts b/src/index.ts index d4e7364..ec1ae88 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ export { + attributeParagraph, attributeDefinitionHandle, attributeHandle, attributesEndHandle, @@ -8,6 +9,7 @@ export { findXref, placeAttribute, type PlacedAttribute, + type PlacedAttributeParagraph, type XrefDrawing, type XrefDrawings, } from "./blocks.ts"; @@ -60,6 +62,8 @@ export { type AlignedDimensionOptions, type Arc, type AttributeDefinition, + type ParagraphAttributeDefinition, + type TextAttributeDefinition, type AttributeOptions, type Block, type BlockOptions, @@ -377,6 +381,7 @@ export { type ReadArc, type ReadAttribute, type ReadAttributeDefinition, + type ReadAttributeParagraph, type ReadBlock, type ReadCensus, type ReadCensusDimension, diff --git a/src/inspect.ts b/src/inspect.ts index 3a1403c..aff7140 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -267,6 +267,7 @@ export function inspectWithin( matrix?: Matrix, from?: Referenced, attribute?: string, + made?: boolean, ): void => { const { id, layer } = entities[index]!; const place = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); @@ -326,10 +327,12 @@ export function inspectWithin( // pays first: by its value's length to lay a long value out again, and by its lines to // read them again. const paragraph = paragraphInStyle(drawn, styleOf(drawn, from)); - const again = paragraphs.again(paragraph); + // A value the drawing does not hold, as an uneven insert makes of an attribute, is no + // first place of anything. + const again = made ? paragraphs.made(paragraph) : paragraphs.again(paragraph); if (again > 0 && !spend(again)) return; const layout = paragraphs.layout(paragraph); - const repeated = again > 0 || expanded.has(drawn) || expanded.has(layout); + const repeated = again > 0 || made === true || expanded.has(drawn) || expanded.has(layout); expanded.add(drawn); expanded.add(layout); if (repeated && !walk(layout.lines.length)) return; @@ -430,7 +433,7 @@ export function inspectWithin( return; } if (!wanted(drawn) || hidden(placement.layer)) return; - keep(drawn, index, placement.matrix, placement.from, placement.attribute); + keep(drawn, index, placement.matrix, placement.from, placement.attribute, placement.made); }, xrefs, step, diff --git a/src/lint.ts b/src/lint.ts index e7c5370..5be9b21 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -95,7 +95,10 @@ import { imagePixelsProblem, arcIsWrittenAsPoint, arcProblem, + ATTRIBUTE_KIND, ATTRIBUTES_SHAPE, + PARAGRAPH_ONLY, + paragraphOnlyProblem, attributeTagProblem, blockCycleProblem, blockNameProblem, @@ -981,6 +984,17 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) // The leading CAD app compares text style names as it compares layer names. const textStyles = new Set(); const stylesByKey = new Map(); + /** + * The font a paragraph's value is checked in: its style's, which decides what `%%c` draws. A + * style that is not found has an error of its own. + */ + const fontOf = (style: unknown): unknown => + style === undefined + ? STANDARD_FONT + : typeof style === "string" + ? (stylesByKey.get(layerKey(style))?.font ?? + (isStandardTextStyle(style) ? STANDARD_FONT : undefined)) + : undefined; const unreadStyles = new Set(); const textStylesAudited = new Map([ [layerAuditKey(STANDARD_TEXT_STYLE), STANDARD_TEXT_STYLE], @@ -1467,6 +1481,8 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) TextStyle | undefined, string, ][]; + /** The font of each definition of paragraph text, by its tag. */ + readonly paragraphs: ReadonlyMap; } >(); const placingOf = (block: Block) => { @@ -1476,7 +1492,12 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const tags = new Set(); for (const tag of read.tags) if (tag !== undefined) tags.add(tag); const placed: [AttributeDefinition & { tag: string }, TextStyle | undefined, string][] = []; + /** The font of each definition of paragraph text, by its tag, which its values are read in. */ + const paragraphs = new Map(); for (const definition of read.definitions) { + if (definition?.kind === "paragraph" && typeof definition.tag === "string") { + paragraphs.set(definition.tag, fontOf(definition.style)); + } if ( !definition || typeof definition.tag !== "string" || @@ -1494,7 +1515,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) JSON.stringify(definition.tag), ]); } - placing.set(block, (found = { tags, placed })); + placing.set(block, (found = { tags, placed, paragraphs })); return found; }; each(listed("blocks", "block"), "blocks", "block", TYPED.block, (block, i) => { @@ -1667,8 +1688,19 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (clash) add("id-handle", "error", clash); } if (!definition) return; + const kind: unknown = definition.kind; + const paragraph = kind === "paragraph"; + if (kind !== undefined && kind !== "text" && !paragraph) + add("attribute", "error", ATTRIBUTE_KIND); + if (paragraph && r12) add("paragraph", "error", R12_ONLY.paragraphs); + const given = definition as unknown as Readonly>; + if (!paragraph) { + for (const field of PARAGRAPH_ONLY) { + if (given[field] !== undefined) add("attribute", "error", paragraphOnlyProblem(field)); + } + } for (const [field, value] of [ - ["its value", definition.value], + ["its value", paragraph ? "" : definition.value], ["its prompt", definition.prompt ?? ""], ] as const) { const [problem, warning] = @@ -1681,7 +1713,37 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) for (const problem of geometryProblems(asText(definition))) { add("geometry", "error", problem); } - for (const [rule, found] of textProblems(definition)) add(rule, "error", found); + if (paragraph) { + const value: unknown = definition.value; + const font = fontOf(definition.style); + const [problem, columnBreak] = + typeof value === "string" + ? checkParagraph(value, font) + : [paragraphValueProblem(value, font), false]; + if (problem) add("paragraph", "error", `its value: ${problem}`); + else if (columnBreak) add("paragraph", "warning", `its value: ${PARAGRAPH_COLUMN_BREAK}`); + const width: unknown = given["width"]; + if (width !== undefined) { + const size = + typeof width === "number" && Number.isFinite(width) + ? sizeProblem(width) + : "This value must be finite"; + if (size) add("geometry", "error", `width: ${size}`); + } + for (const [rule, field, chosen] of [ + ["text-align", "align", given["align"]], + ["text-align", "valign", given["valign"]], + ["paragraph", "lineSpacingStyle", given["lineSpacingStyle"]], + ] as const) { + const choice = chosen === undefined ? undefined : paragraphChoiceProblem(field, chosen); + if (choice) add(rule, "error", choice); + } + const spacing = given["lineSpacing"]; + const spaced = spacing === undefined ? undefined : lineSpacingProblem(spacing); + if (spaced) add("paragraph", "error", spaced); + const styled = definition.style === undefined ? {} : { style: definition.style }; + for (const [rule, found] of textProblems(styled)) add(rule, "error", found); + } else for (const [rule, found] of textProblems(definition)) add(rule, "error", found); mark(TYPED.attribute, definition, `${at}.attributes[${index}]`, from); }); }; @@ -1933,7 +1995,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const cost = (count++ >= FREE ? 1 : 0) + lookupCost(entity, definition) + - (repeated ? Math.floor(definition.value.length / 32) : 0); + (repeated && typeof definition.value === "string" + ? Math.floor(definition.value.length / 32) + : 0); if (cost > 0 && !spend(cost, here)) break; const problem = placedAttributeProblem( definition.tag, @@ -1947,6 +2011,18 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (placed && !tags.has(tag) && !unreadDefinitions.has(placed)) { add("undefined-attribute", "error", undefinedAttributeProblem(tag, placed.name)); } + if (read?.paragraphs.has(tag)) { + const font = read.paragraphs.get(tag); + const [problem, columnBreak] = + typeof value === "string" + ? checkParagraph(value, font) + : [paragraphValueProblem(value, font), false]; + const about = `attribute ${shown(tag)}`; + if (problem) add("paragraph", "error", `${about}: ${problem}`); + else if (columnBreak) + add("paragraph", "warning", `${about}: ${PARAGRAPH_COLUMN_BREAK}`); + continue; + } const [problem, warning] = typeof value === "string" ? checkText(value) : ["must be a string", undefined]; if (problem) add("text", "error", `attribute ${shown(tag)}: ${problem}`); @@ -2047,16 +2123,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) add("paragraph", "error", R12_ONLY.paragraphs); return; } - // A value is checked in its style's font, which decides what `%%c` draws. A style that is - // not found has an error of its own. - const style: unknown = entity.style; - const font = - style === undefined - ? STANDARD_FONT - : typeof style === "string" - ? (stylesByKey.get(layerKey(style))?.font ?? - (isStandardTextStyle(style) ? STANDARD_FONT : undefined)) - : undefined; + const font = fontOf(entity.style); const [problem, columnBreak] = typeof entity.value === "string" ? checkParagraph(entity.value, font) diff --git a/src/paragraphs.ts b/src/paragraphs.ts index b1155a1..2d76ad8 100644 --- a/src/paragraphs.ts +++ b/src/paragraphs.ts @@ -40,7 +40,8 @@ import { Strings } from "./shape.ts"; // the factor below it, and the bottom of the box h/3 below the last. // - The style's width factor scales everything along a line. Its oblique angle moves where a line // starts by its first character's bottom times the angle's tangent, and where it ends by its A -// times it. It is measured for a TrueType font, and an estimate for an SHX font. +// times it. A leaned word wraps as if its ink reached twice its last character's lean further, +// whatever its width factor. It is measured for a TrueType font, and an estimate for an SHX font. // - An underline runs along a run from its first point to where its advances end, `UNDERLINE_SHX` // below the baseline in an SHX font and the font's descent, `below`, in a TrueType font; a // strike-through `STRIKE_THROUGH` above it. An overline, refused, is drawn `OVERLINE` above it. @@ -1280,7 +1281,8 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { trial.started = pen.started; trial.tabbed = pen.tabbed; place(spaces, trial); - if (words > 0 && overflows(place(word, trial), trial)) { + // A leaned word reaches past its ink by twice its last character's lean. + if (words > 0 && overflows(place(word, trial) + 2 * trial.leaned, trial)) { endLine(); restart(false); } else place(spaces, pen, line); @@ -2123,6 +2125,14 @@ export interface ParagraphMeasurer { again(paragraph: ParagraphToMeasure): number; /** What `box` costs before it lays a paragraph out, as `again` gives it for `layout`. */ boxAgain(paragraph: ParagraphToMeasure): number; + /** + * What laying out a value the drawing does not hold costs, such as an attribute's with the code + * an uneven insert puts before it: a long value's length the first time, as a long value laid + * out again costs, since no place of the drawing paid for it, and `again` after that. + */ + made(paragraph: ParagraphToMeasure): number; + /** As `made`, for `box`. */ + boxMade(paragraph: ParagraphToMeasure): number; } /** A key of a paragraph's settings. */ @@ -2165,6 +2175,11 @@ export function paragraphMeasurer(): ParagraphMeasurer { kept.clashes(value) || (found !== undefined && !has(found, keyOf(settingsIn(paragraph)))); return again ? value.length : 0; }; + /** A long value's length when it has not been laid out, or undefined. */ + const firstTime = (paragraph: ParagraphToMeasure): number | undefined => { + const value = paragraph.value; + return long(value) && kept.get(value) === undefined ? value.length : undefined; + }; const entry = (value: string): Kept => { let found = kept.get(value); if (!found) kept.set(value, (found = { boxes: undefined, last: undefined })); @@ -2200,6 +2215,10 @@ export function paragraphMeasurer(): ParagraphMeasurer { box, again: (paragraph) => cost(paragraph, (found, key) => found.last?.key === key), boxAgain: (paragraph) => cost(paragraph, (found, key) => found.boxes?.has(key) ?? false), + made: (paragraph) => + firstTime(paragraph) ?? cost(paragraph, (found, key) => found.last?.key === key), + boxMade: (paragraph) => + firstTime(paragraph) ?? cost(paragraph, (found, key) => found.boxes?.has(key) ?? false), }; } diff --git a/src/read/check.ts b/src/read/check.ts index fd8cdce..f2797f0 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -100,12 +100,27 @@ const PLACEMENT: Fields = { "upsideDown?": "boolean", }; +const ATTRIBUTE_PARAGRAPH: Type = { + fields: { + at: "point", + height: "number", + width: "number", + attachment: "number", + rotation: "number", + style: "string", + lineSpacing: "number", + lineSpacingStyle: { oneOf: ["at-least", "exactly"] }, + "mirrored?": "boolean", + }, +}; + const ATTRIBUTE: Fields = { ...BASE, ...PLACEMENT, tag: "string", value: "string", "invisible?": "boolean", + "paragraph?": ATTRIBUTE_PARAGRAPH, }; const INSERT: Fields = { @@ -444,6 +459,7 @@ const DRAWING_READ: Fields = { layer: "string", invisible: "boolean", constant: "boolean", + "paragraph?": ATTRIBUTE_PARAGRAPH, }, }, }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 52f30cd..a35205d 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -9,6 +9,7 @@ import { DxfDocumentReader, type DxfDocument } from "./document.ts"; import { attributeCost, attributeOf, + attributeParts, baseOf, brokenNumber, costOf, @@ -1008,17 +1009,25 @@ class DxfReader { add(this.unread.malformed, "ATTDEF with a number that is not finite"); return; } - const flags = num(r, 70) ?? 0; - const prompt = name(r, 3) === undefined ? undefined : textTwice(first(r, 3)!); - const value = textTwice(first(r, 1) ?? ""); - const tag = textTwice(first(r, 2) ?? ""); - const cost = 4 + Math.floor((tag.length + value.length + (prompt?.length ?? 0)) / 32); + const { text, paragraph } = attributeParts(r); + if (paragraph === null) { + add(block.other, "ATTDEF of paragraph text in 3D"); + return; + } + const flags = num(text, 70) ?? 0; + const prompt = name(text, 3) === undefined ? undefined : textTwice(first(text, 3)!); + const value = paragraph ? paragraph.value : textTwice(first(text, 1) ?? ""); + const tag = textTwice(first(text, 2) ?? ""); + const cost = + 4 + + (paragraph ? 2 + nameCost(paragraph.paragraph.style) : 0) + + Math.floor((tag.length + value.length + (prompt?.length ?? 0)) / 32); if (cost > this.#room(block)) { add(block.other, "past the limit"); return; } this.#blockItems += cost; - const { placement, pending } = placementOf(r, face, value, 74); + const { placement, pending } = placementOf(text, face, value, 74); const definition = { handle, ...placement, @@ -1028,8 +1037,9 @@ class DxfReader { layer, invisible: (flags & 1) !== 0 || hidden(r), constant: (flags & 2) !== 0, + ...(paragraph && { paragraph: paragraph.paragraph }), }; - if (pending) this.#starts.push({ ...pending, placement: definition }); + if (pending && !paragraph) this.#starts.push({ ...pending, placement: definition }); block.attributeDefinitions.push(definition); return; } @@ -1156,7 +1166,8 @@ class DxfReader { owner.tags++; owner.cost += 1 + Math.floor(tag.length / 32); } - owner.insert.tags[tag] = (first(r, 1) ?? "") !== ""; + const { text, paragraph } = attributeParts(r); + owner.insert.tags[tag] = paragraph ? paragraph.value !== "" : (first(text, 1) ?? "") !== ""; } const target = this.#target(); if (!owner.attributes || owner.over || !target) return; diff --git a/src/read/entities.ts b/src/read/entities.ts index 6584270..d32f0df 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -6,6 +6,7 @@ import { textOnce, textTwice } from "./groups.ts"; import { wholeImageClip } from "../images.ts"; import type { ReadAttribute, + ReadAttributeParagraph, ReadDimension, ReadRadialDimension, ReadAngularDimension, @@ -1008,20 +1009,89 @@ export function attributeOf( if (brokenNumber(r)) return { malformed: "ATTRIB with a number that is not finite" }; const face = facing(r); if (face === 0) return { other: "ATTRIB in 3D" }; - const value = textTwice(first(r, 1) ?? ""); - const { placement, pending } = placementOf(r, face, value, 74); + const { text, paragraph } = attributeParts(r); + if (paragraph === null) return { other: "ATTRIB of paragraph text in 3D" }; + const value = paragraph ? paragraph.value : textTwice(first(text, 1) ?? ""); + const { placement, pending } = placementOf(text, face, value, 74); const attribute = { ...base, ...placement, - tag: textTwice(first(r, 2) ?? ""), + tag: textTwice(first(text, 2) ?? ""), value, // Its own flag, group 70, or the entity's, group 60, as a dynamic block's state hides it. - ...((((num(r, 70) ?? 0) & 1) !== 0 || num(r, 60) === 1) && { invisible: true }), + ...((((num(text, 70) ?? 0) & 1) !== 0 || num(text, 60) === 1) && { invisible: true }), + ...(paragraph && { paragraph: paragraph.paragraph }), }; - if (pending) later.start({ ...pending, placement: attribute }); + if (pending && !paragraph) later.start({ ...pending, placement: attribute }); return attribute; } +/** + * The parts of an `ATTRIB` or an `ATTDEF`: its text's groups, without the paragraph's flags its + * subclass holds, and for one of paragraph text the paragraph after group 101, its embedded + * object, with its value. Its paragraph is null where it lies off the plane. + */ +export function attributeParts(r: Rec): { + readonly text: Rec; + readonly paragraph: + | { readonly paragraph: ReadAttributeParagraph; readonly value: string } + | undefined + | null; +} { + const from = r.codes.indexOf(101); + if (from < 0) return { text: r, paragraph: undefined }; + // Groups 71 and 72 after the subclass of the attribute say it is of paragraph text. + const subclass = r.codes.findIndex( + (code, i) => + code === 100 && + (r.values[i] === "AcDbAttribute" || r.values[i] === "AcDbAttributeDefinition"), + ); + const codes: number[] = []; + const values: string[] = []; + for (let i = 0; i < from; i++) { + if (subclass >= 0 && i > subclass && (r.codes[i] === 71 || r.codes[i] === 72)) continue; + codes.push(r.codes[i]!); + values.push(r.values[i]!); + } + const text: Rec = { type: r.type, codes, values }; + const after: Rec = { + type: r.type, + codes: r.codes.slice(from + 1), + values: r.values.slice(from + 1), + }; + const z = num(after, 230) ?? 1; + if (Math.abs(num(after, 210) ?? 0) > 1e-9 || Math.abs(num(after, 220) ?? 0) > 1e-9) { + return { text, paragraph: null }; + } + let value = ""; + for (let i = 0; i < after.codes.length; i++) { + if (after.codes[i] === 3 || after.codes[i] === 1) value += after.values[i]; + } + const dx = num(after, 11); + const dy = num(after, 21); + const rotation = + dx !== undefined && dy !== undefined && (dx !== 0 || dy !== 0) + ? degrees((Math.atan2(dy, dx) * 180) / Math.PI) + : 0; + return { + text, + paragraph: { + value: textOnce(value), + paragraph: { + at: point(after, 10), + height: num(after, 40) ?? 0, + width: num(after, 41) ?? 0, + attachment: num(after, 71) ?? 1, + rotation, + style: name(after, 7) ?? "Standard", + lineSpacing: num(after, 44) ?? 1, + lineSpacingStyle: num(after, 73) === 2 ? "exactly" : "at-least", + ...(z < 0 && { mirrored: true }), + }, + }, + }; +} + /** The characters a string costs against a budget: one item for each 32. */ export const nameCost = (value: string | undefined): number => value === undefined ? 0 : Math.floor(value.length / 32); @@ -1033,7 +1103,13 @@ const placementCost = (p: ReadTextPlacement): number => /** What an attribute costs against a budget. */ export const attributeCost = (a: ReadAttribute): number => - 1 + placementCost(a) + chars(a.tag) + chars(a.value) + chars(a.layer) + chars(a.linetype); + 1 + + placementCost(a) + + chars(a.tag) + + chars(a.value) + + chars(a.layer) + + chars(a.linetype) + + (a.paragraph ? 2 + chars(a.paragraph.style) : 0); /** * What an entity costs against `BLOCK_ITEMS` or `GEOMETRY_ITEMS`: one, and one more for each of diff --git a/src/read/model.ts b/src/read/model.ts index 68616c6..250bcd8 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -204,10 +204,40 @@ export interface ReadAttributeDefinition extends ReadTextPlacement { readonly handle?: string | undefined; readonly tag: string; readonly prompt?: string; + /** Of one of paragraph text, its paragraph's value, with its codes. */ readonly default?: string; readonly layer: string; readonly invisible: boolean; readonly constant: boolean; + /** The paragraph of a definition of paragraph text, which the leading CAD app draws. */ + readonly paragraph?: ReadAttributeParagraph; +} + +/** + * The paragraph text an attribute or a definition of more than one line holds, which the leading + * CAD app draws in the place of its text: an MTEXT of its own, whose value is the attribute's. + */ +export interface ReadAttributeParagraph { + /** The point of its box that `attachment` names, in the world's coordinates. */ + readonly at: Point; + /** The height its text starts at. */ + readonly height: number; + /** The width it wraps at, or 0 when it does not wrap. */ + readonly width: number; + /** 1 top left, 2 top center, 3 top right, 4 to 6 the middle, 7 to 9 the bottom. */ + readonly attachment: number; + /** The direction of its lines, in degrees counterclockwise. */ + readonly rotation: number; + /** Its text style, `Standard` when the file names none. */ + readonly style: string; + /** The factor of its line spacing, 1 when the file states none. */ + readonly lineSpacing: number; + readonly lineSpacingStyle: "at-least" | "exactly"; + /** + * True when it is seen from below, as an insert that mirrors its block holds it: its lines run + * along `rotation` with their tops to its right. + */ + readonly mirrored?: boolean; } /** @@ -319,9 +349,12 @@ export interface ReadText extends ReadEntityBase, ReadTextPlacement { /** An attribute of an insert, where the file places it. */ export interface ReadAttribute extends ReadEntityBase, ReadTextPlacement { readonly tag: string; + /** Of one of paragraph text, its paragraph's value, with its codes. */ readonly value: string; /** True for an attribute that does not show. */ readonly invisible?: boolean; + /** The paragraph of an attribute of paragraph text, which the leading CAD app draws. */ + readonly paragraph?: ReadAttributeParagraph; } export interface ReadInsert extends ReadEntityBase { diff --git a/src/rules.ts b/src/rules.ts index 2149217..cabca9a 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -2714,6 +2714,7 @@ export function placedAttributeProblem( readonly height: number; readonly widthFactor: number; readonly obliqueAngle: number; + readonly paragraph?: { readonly width: number | undefined }; }, quoted?: string, ): string | undefined { @@ -2727,6 +2728,9 @@ export function placedAttributeProblem( } const height = sizeProblem(placed.height); if (height) return `${about()} ${placed.height} high. ${height}`; + const width = placed.paragraph?.width; + const wide = width === undefined ? undefined : sizeProblem(width); + if (wide) return `${about()} wrap at a width of ${width}. ${wide}`; if (Math.abs(written(placed.obliqueAngle)) > 85) { return `${about()} slant by ${written(placed.obliqueAngle)} degrees. ${OBLIQUE}. Scale the insert more evenly`; } @@ -2746,6 +2750,17 @@ export function duplicateAttributeProblem(tag: string): string { return `The block already has an attribute with the tag ${JSON.stringify(tag)}. An insert sets an attribute by its tag, and the tag gives the definition its handle: the leading CAD app discards a drawing in which two objects have one handle`; } +/** What an attribute definition's `kind` must be. */ +export const ATTRIBUTE_KIND = 'An attribute definition\'s kind must be "text" or "paragraph"'; + +/** The fields only an attribute definition of paragraph text has. */ +export const PARAGRAPH_ONLY = ["width", "lineSpacing", "lineSpacingStyle"] as const; + +/** What is wrong with a field of paragraph text on an attribute definition of one line. */ +export function paragraphOnlyProblem(field: (typeof PARAGRAPH_ONLY)[number]): string { + return `${field} belongs to an attribute definition of paragraph text, which has kind "paragraph"`; +} + /** What an insert's `attributes` must be. */ export const ATTRIBUTES_SHAPE = "attributes must be an object of values by tag"; diff --git a/src/shape.ts b/src/shape.ts index e6194c0..38c34b0 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -4,7 +4,8 @@ import type { AlignedDimension, Arc, - AttributeDefinition, + ParagraphAttributeDefinition, + TextAttributeDefinition, Block, Circle, DimensionStyle, @@ -318,6 +319,10 @@ export interface Shapes { readonly entity: Check; } +/** An attribute definition, every field of each kind at once, as its shape is checked. */ +type AttributeShape = Omit & + Omit & { readonly kind?: string }; + /** A paragraph's columns, every field of each kind at once, as their shape is checked. */ interface ColumnsShape { readonly height?: number; @@ -769,7 +774,7 @@ function shapes(all: boolean, typed = all): Shapes { ), ); const attribute = record( - fields( + fields( { tag: ruled(string), value: ruled(string), @@ -778,7 +783,14 @@ function shapes(all: boolean, typed = all): Shapes { height: number, rotation: number, }, - { prompt: string, ...justified }, + { + prompt: string, + ...justified, + kind: ruled(string), + width: number, + lineSpacing: number, + lineSpacingStyle: ruled(string), + }, ), ); const block = record( diff --git a/src/standard/lint.ts b/src/standard/lint.ts index 37c3055..48fc9d2 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -1502,15 +1502,29 @@ function lettering( rotation: text.rotation, ...justified(text), }; - const definitionOf = (definition: AttributeDefinition): AttributeDefinition => ({ - tag: definition.tag, - value: definition.value, - layer: layer(definition.layer), - at: definition.at, - height: definition.height, - rotation: definition.rotation, - ...justified(definition), - }); + const definitionOf = (definition: AttributeDefinition): AttributeDefinition => + ({ + tag: definition.tag, + value: definition.value, + layer: layer(definition.layer), + at: definition.at, + height: definition.height, + rotation: definition.rotation, + ...justified(definition), + // One of paragraph text is drawn as the paragraph each insert lays out again. + ...(definition.kind === "paragraph" + ? { + kind: "paragraph", + ...(definition.width === undefined ? {} : { width: definition.width }), + ...(definition.lineSpacing === undefined + ? {} + : { lineSpacing: definition.lineSpacing }), + ...(definition.lineSpacingStyle === undefined + ? {} + : { lineSpacingStyle: definition.lineSpacingStyle }), + } + : {}), + }) as AttributeDefinition; const tokens = new Map(); let entered: Entered | undefined; diff --git a/test/blocks.test.ts b/test/blocks.test.ts index bf87765..7af2826 100644 --- a/test/blocks.test.ts +++ b/test/blocks.test.ts @@ -9,7 +9,9 @@ import { DrawingError, fromJSON, idHandle, + inspectText, lint, + attributeParagraph, placeAttribute, toDXF, toJSON, @@ -19,7 +21,8 @@ import { type Entity, type Insert, } from "../src/index.ts"; -import { extents } from "../src/extents.ts"; +import { boxer, extents } from "../src/extents.ts"; +import { inspectWithin } from "../src/inspect.ts"; /** A tree with a tag, inserted three ways, and a block that holds an insert of it. */ function sample(): Drawing { @@ -307,6 +310,113 @@ test("an insert gives an attribute the text the leading CAD app holds for it", ( assert.deepEqual([mirrored.at, mirrored.mirrored, mirrored.value], [[-50, 10], true, "ELM"]); }); +test("an insert gives an attribute of paragraph text the paragraph the leading CAD app holds for it", () => { + const style = { name: "SLANT", font: "Arial", widthFactor: 0.8, obliqueAngle: 10 }; + const definition = { + kind: "paragraph", + tag: "NB", + value: "ONE TWO THREE FOUR FIVE SIX", + layer: "0", + at: [1, 1], + height: 0.2, + rotation: 15, + style: "SLANT", + width: 2.5, + align: "center", + valign: "middle", + lineSpacing: 1.5, + lineSpacingStyle: "exactly", + } as const; + const near = (actual: number, expected: number) => + assert.ok(Math.abs(actual - expected) < 1e-9, `${actual} is not ${expected}`); + // What the leading CAD app's -INSERT made of this definition: scaled 2 and turned 30, its + // height and width twice the definition's, turned with it, and its value as it is. + const even = placeAttribute( + definition, + style, + insert("B", { at: [20, 20], scale: [2, 2], rotation: 30 }), + undefined, + ); + near(even.at[0], 20.73205080756888); + near(even.at[1], 22.73205080756888); + near(even.height, 0.4); + near(even.rotation, 45); + near(even.paragraph!.width!, 5); + assert.equal(even.paragraph!.value, definition.value); + // Scaled 2 by 0.5: its height as a text's, its width the same share of the definition's, and + // its characters at the text's own width factor, to four decimals, without the style's. + const uneven = placeAttribute( + definition, + style, + insert("B", { at: [40, 20], scale: [2, 0.5] }), + [0, 0], + ); + near(uneven.height, 0.1032961172179533); + near(uneven.rotation, 3.832363985964412); + near(uneven.widthFactor, 3.748797632095823); + near(uneven.obliqueAngle, 316.8476102659945 - 360); + near(uneven.paragraph!.width!, 1.291201465224416); + assert.equal(uneven.paragraph!.value, `\\W3.7488;${definition.value}`); + // Mirrored: placed where X runs the other way, as a text of one line is. + const mirrored = placeAttribute( + definition, + style, + insert("B", { at: [60, 20], scale: [-1, 1] }), + [0, 0], + ); + assert.deepEqual([mirrored.at, mirrored.mirrored], [[-59, 21], true]); + near(mirrored.rotation, 15); + const paragraph = attributeParagraph(mirrored)!; + const round = (v: number) => Math.round(v * 1e9) / 1e9; + assert.deepEqual( + { + ...paragraph, + at: paragraph.at.map(round), + width: round(paragraph.width!), + height: round(paragraph.height), + }, + { + kind: "paragraph", + layer: "0", + style: "SLANT", + width: 2.5, + align: "center", + valign: "middle", + lineSpacing: 1.5, + lineSpacingStyle: "exactly", + at: [-59, 21], + height: 0.2, + rotation: mirrored.rotation, + value: definition.value, + }, + ); + // The picture and the extents take each where its insert holds it: the uneven one wraps at + // its narrower width into more lines, and the mirrored one reads backward. + const d = createDrawing({ units: "in" }); + d.textStyle(style); + d.block("B", {}, () => d.attribute("NB", [1, 1], { ...definition, tag: undefined } as never)); + d.insert("B", [0, 0]) + .insert("B", [10, 0], { scale: [2, 0.5] }) + .insert("B", [20, 0], { scale: [-1, 1] }); + const drawing = d.build(); + assert.deepEqual(lint(drawing), []); + const svg = toSVG(drawing); + assert.match(svg, /scale\(3\.7488 1\)/); + assert.match(svg, /matrix\(-1 0 0 1 0 0\)/); + const [plain, narrow, backward] = drawing.entities.map((e) => + extents([e], drawing.textStyles, drawing.blocks)!, + ); + // Each is centered on its point, the definition's (1, 1) where the insert puts it. + for (const [box, x] of [ + [plain!, 1], + [narrow!, 12], + [backward!, 19], + ] as const) { + assert.ok(Math.abs((box[0] + box[2]) / 2 - x) < 0.1, `${box} about ${x}`); + } + assert.ok(narrow![3] - narrow![1] > plain![3] - plain![1]); +}); + test("a drawing with blocks goes to JSON and back, and the parser knows each new field", () => { const drawing = sample(); const json = toJSON(drawing); @@ -386,3 +496,71 @@ test("SVG draws an insert's block where the insert puts it, on the layers the le const cyclic = toSVG(withBlocks([{ name: "A", entities: [insert("A")] }], [insert("A")])); assert.match(cyclic, /<\/g>/); }); + +test("an attribute of one line has no paragraph, and a \\N in one of paragraph text is warned of", () => { + const d = createDrawing({ units: "in" }); + d.block("B", {}, () => { + d.attribute("ONE", [0, 0], { value: "A" }); + d.attribute("NOTE", [0, 1], { kind: "paragraph", value: "A\\NB", width: 2 }); + }); + d.insert("B", [0, 0], { attributes: { NOTE: "C\\ND" } }); + const drawing = d.build(); + const one = drawing.blocks![0]!.attributes![0]!; + const insert = drawing.entities[0] as Insert; + assert.equal(attributeParagraph(placeAttribute(one, undefined, insert, undefined)), undefined); + const breaks = lint(drawing).filter((w) => w.message.includes("\\N starts the next column")); + assert.deepEqual( + breaks.map((w) => w.severity), + ["warning", "warning"], + ); +}); + +test("an attribute of paragraph text of the wrong shape is drawn as none, and uneven inserts pay", () => { + const d = createDrawing({ units: "in" }); + d.block("B", {}, () => d.attribute("A", [0, 0], { kind: "paragraph", width: 2 })); + d.insert("B", [0, 0], { scale: [2, 1] }); + const built = d.build(); + const block = built.blocks![0]!; + const definition = block.attributes![0]!; + const withDefinition = (changed: object, insert: object = {}): Drawing => ({ + ...built, + blocks: [{ ...block, attributes: [{ ...definition, ...changed } as typeof definition] }], + entities: [{ ...(built.entities[0] as Insert), ...insert }], + }); + // A value that is no string, of the definition or of an insert, is an error and no throw. + const odd = { toString: null }; + for (const drawing of [ + withDefinition({ value: odd }), + withDefinition({}, { attributes: { A: odd } }), + ]) { + assert.ok(lint(drawing).some((w) => w.severity === "error")); + } + // A width that is no number is laid out as none by the preview and the checks. + const wide = withDefinition({ width: "12" }); + assert.ok(lint(wide).some((w) => w.severity === "error")); + toSVG(wide); + inspectText(wide); + // An insert that scales its block unevenly makes a value the drawing does not hold, which pays + // its length the first time it is laid out, as a long value laid out again does; inserts of + // one scale share it, and a box kept is mapped alone. + // Codes alone but a character, so that what it costs is its layout and no check of its lines. + const shared = { A: "\\L\\l".repeat(5000) + "X" }; + const inserts = (scale: (i: number) => [number, number]) => + Array.from({ length: 20 }, (_, i): Insert => ({ + ...(built.entities[0] as Insert), + at: [i * 100, 0], + scale: scale(i), + attributes: shared, + })); + const scales = inserts((i) => [2 + i / 10, 1]); + const one = inserts(() => [2, 1]); + const capped = (entities: Insert[]) => { + const box = boxer([], [block], undefined, undefined, undefined, [], [], 100_000); + box(entities); + return box.capped !== undefined; + }; + assert.deepEqual([capped(scales), capped(one)], [true, false]); + const checked = (entities: Insert[]) => + inspectWithin({ ...built, entities }, {}, 400_000).some((w) => w.rule === "text-check-capped"); + assert.deepEqual([checked(scales), checked(one)], [true, false]); +}); diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 802c0f1..23634a6 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2068,27 +2068,48 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint (drawing.entities as Data[]).push({ ...tree.top, block: `T${Math.floor(depth / 2)}` }); } if (random() < 0.4) { + // Of one line, or of paragraph text: long, of many lines, of deep braces, or wrapped at a + // width past what can be drawn, one definition shared by every place or each its own. + const paragraphs = random() < 0.5; + const shared = { + kind: "paragraph", + tag: "P", + value: pick([long, "WORD\\P".repeat(20_000), `${"{".repeat(50_000)}x`, "A B C"]), + layer: "0", + at: [0, 0] as Point, + height: 1, + rotation: 30, + width: pick([1e-6, 2, 1e90]), + lineSpacing: 4, + }; (tree.blocks[0] as { attributes?: unknown }).attributes = Array.from( { length: pick([1, 100, 300]) }, - (_, i) => ({ - tag: i === 0 && random() < 0.5 ? "T".repeat(2_000_000) : `A${i}`, - value: pick(["V", long]), - layer: "0", - at: [0, 0] as Point, - height: 1, - rotation: 0, - ...(i === 0 && random() < 0.2 ? fields() : {}), - }), + (_, i) => + paragraphs && random() < 0.5 + ? { ...shared, tag: `P${i}` } + : { + tag: i === 0 && random() < 0.5 ? "T".repeat(2_000_000) : `A${i}`, + value: pick(["V", long]), + layer: "0", + at: [0, 0] as Point, + height: 1, + rotation: 0, + ...(paragraphs ? { kind: "paragraph", width: 3 } : {}), + ...(i === 0 && random() < 0.2 ? fields() : {}), + }, ); } blocks.push(...(tree.blocks as unknown as Data[])); // Values each insert holds, long or not. const values = random() < 0.3 ? { A0: pick(["V", long]), A1: long } : undefined; + // Scaled unevenly or mirrored, which places an attribute of paragraph text again in each. + const scale = pick([undefined, [2, 0.5], [-1, 1], [1e-6, 1e6]]); const inserts = Array.from({ length: pick([1, 300]) }, (_, i) => ({ ...tree.top, at: [i, 0], ...(random() < 0.5 ? { id: `I${i}` } : {}), ...(values ? { attributes: values } : {}), + ...(scale ? { scale } : {}), rotation: random() * 360, })); (random() < 0.5 ? (drawing.entities as Data[]) : (layout.entities as Data[])).push(...inserts); diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index ceb6413..ae96844 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -740,6 +740,55 @@ test("a paragraph is placed in the direction the DXF holds: its rotation within assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); }); +test("an attribute of paragraph text is written and read as the leading CAD app's -INSERT makes it", async () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "NOTES", font: "Arial", widthFactor: 0.8 }); + d.block("NOTE", {}, () => + d.attribute("NOTE", [1, 1], { + kind: "paragraph", + value: "ALL WORK SHALL COMPLY\nWITH THE CODES", + width: 3, + height: 0.25, + style: "NOTES", + align: "right", + valign: "bottom", + lineSpacing: 2, + }), + ); + d.insert("NOTE", [0, 0]); + d.insert("NOTE", [10, 0], { scale: [2, 0.5], rotation: 30, attributes: { NOTE: "OWN\nVALUE" } }); + d.insert("NOTE", [20, 0], { scale: [-1.5, 1.5], rotation: 45 }); + const drawing = d.build(); + const dxf = toDXF(drawing); + // The text the attribute would be as a line holds no value, and its paragraph follows it. + assert.ok(dxf.includes("\r\n71\r\n 4\r\n") || dxf.includes("\r\n71\r\n4\r\n")); + assert.ok(dxf.includes("\r\n101\r\nEmbedded Object\r\n")); + assert.ok(dxf.includes("\\W4.0000;OWN\\PVALUE"), "an uneven scale widens by a code"); + const read = await readDXF(dxf, { geometry: true }); + assert.deepEqual(checkDrawingRead(JSON.parse(JSON.stringify(read))), []); + assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); + const [definition] = read.blocks.find((b) => b.name === "NOTE")!.attributeDefinitions; + assert.equal(definition!.default, "ALL WORK SHALL COMPLY\\PWITH THE CODES"); + // Its text starts where a text of no value does: at the bottom, Arial's descent above the point. + assert.equal(definition!.startFrom, "file"); + assert.equal(definition!.at[0], 1); + assert.ok(Math.abs(definition!.at[1] - (1 + 0.29604365621 * 0.25)) < 1e-14); + assert.deepEqual(definition!.paragraph, { + at: [1, 1], + height: 0.25, + width: 3, + attachment: 9, + rotation: 0, + style: "NOTES", + lineSpacing: 2, + lineSpacingStyle: "at-least", + }); + const inserts = read.model.entities!.filter((e) => e.kind === "insert"); + const mirrored = inserts[2]!.kind === "insert" ? inserts[2]!.attributes![0]! : undefined; + assert.equal(mirrored?.paragraph?.mirrored, true); + assert.equal(mirrored?.value, "ALL WORK SHALL COMPLY\\PWITH THE CODES"); +}); + test("a run and a text in a TrueType font are plotted from their first point at their advances", () => { const d = createDrawing({ units: "in" }); d.textStyle({ name: "NOTES", font: "Arial" }); @@ -799,3 +848,37 @@ test("under a standard a paragraph is held to its role's text style and height, assert.deepEqual(rules(changed({ height: 0.2 })), ["height-off-role"]); assert.deepEqual(rules(changed({ style: undefined })), ["text-style-outside-standard"]); }); + +test("a leaned word wraps as if its ink reached twice its last character's lean further", () => { + // The least width that holds two words on one line, in Arial capitals of height 1. + const least = (obliqueAngle: number, widthFactor = 1) => { + let [lo, hi] = [0, 20]; + for (let i = 0; i < 50; i++) { + const width = (lo + hi) / 2; + const { lines } = layoutParagraph({ + value: "HHH HHH", + height: 1, + width, + font: "Arial", + obliqueAngle, + widthFactor, + }); + [lo, hi] = lines.length === 1 ? [lo, width] : [width, hi]; + } + return hi; + }; + for (const [angle, factor] of [ + [15, 1], + [30, 1], + [15, 0.5], + ] as const) { + const further = least(angle, factor) - least(0, factor); + // Within the rounding of a width as written. + assert.ok( + Math.abs(further - 2 * Math.tan((angle * Math.PI) / 180)) < 1e-5, + `${angle}, ${factor}`, + ); + } + // A left lean wraps as an upright word does. + assert.equal(least(-15), least(0)); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index c363563..ce43c4a 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -17,6 +17,7 @@ import type { Block, Drawing, Entity, + ParagraphAttributeDefinition, Point, TextStyle, } from "../src/drawing.ts"; @@ -26,11 +27,12 @@ import { findLeaderStyle, leaderPicture } from "../src/leaders.ts"; import { fromImagePixels, imageClip, imageVectors, writtenImagePath } from "../src/images.ts"; import { layerKey } from "../src/layers.ts"; import { entityLinetype, lineweightCode } from "../src/linetypes.ts"; -import { paragraphAttachment, paragraphTurn } from "../src/paragraphs.ts"; +import { paragraphAttachment, paragraphDirection, paragraphTurn } from "../src/paragraphs.ts"; import { textOnce, textTwice } from "../src/read/groups.ts"; import type { DrawingRead, ReadAttribute, + ReadAttributeParagraph, ReadEntity, ReadTextPlacement, } from "../src/read/model.ts"; @@ -103,6 +105,8 @@ export function readProblems( readonly widthFactor: number; readonly obliqueAngle: number; readonly mirrored: boolean; + /** True for the text of an attribute of paragraph text, whose file holds where it starts. */ + readonly paragraph?: boolean; }, label: string, ): void => { @@ -117,7 +121,7 @@ export function readProblems( const at = justified ? got.alignAt : got.at; if (!nearPoint(at, want.at)) say(`${label}: placed at ${at}, expected ${want.at}`); if (!justified && got.startFrom !== "file") say(`${label}: starts from ${got.startFrom}`); - if (justified && by === "tsdraft" && got.startFrom === "file") { + if (justified && by === "tsdraft" && got.startFrom === "file" && !want.paragraph) { say(`${label}: starts from the file, which holds its alignment point there`); } if (!near(got.height, want.height)) @@ -168,26 +172,90 @@ export function readProblems( const style = styleOf(definition.style); const placed = placeAttribute(definition, style, insert, block.base); if (got.tag !== twice(definition.tag)) say(`${label}: tag ${got.tag}`); - if (got.value !== twice(placed.value)) say(`${label}: reads ${JSON.stringify(got.value)}`); + const value = placed.paragraph?.value; + if (value === undefined ? got.value !== twice(placed.value) : !paragraphValue(got.value, value)) + say(`${label}: reads ${JSON.stringify(got.value)}`); if (!sameName(got.layer, definition.layer)) say(`${label}: on layer ${got.layer}`); // The file holds a mirrored insert's attribute seen from below, which mirrors X. const at: Point = placed.mirrored ? [-placed.at[0], placed.at[1]] : placed.at; + const uneven = placed.paragraph?.uneven ?? true; placement( got, { - ...definition, + ...lineOf(definition), at: point(at), height: written(placed.height), rotation: written(placed.mirrored ? -placed.rotation : placed.rotation), - widthFactor: written(placed.widthFactor), - obliqueAngle: written(placed.obliqueAngle), + widthFactor: uneven ? written(placed.widthFactor) : 1, + obliqueAngle: uneven ? written(placed.obliqueAngle) : 0, mirrored: placed.mirrored, + paragraph: placed.paragraph !== undefined, }, label, ); + if (placed.paragraph) { + const [cos, sin] = paragraphDirection(placed.rotation); + paragraphOf(got.paragraph, definition as ParagraphAttributeDefinition, { + at: point(at), + height: written(placed.height), + width: placed.paragraph.width ?? 0, + turn: (Math.atan2(sin, placed.mirrored ? -cos : cos) * 180) / Math.PI, + mirrored: placed.mirrored, + label, + }); + return; + } start(got, mine, got.value, label); }; + /** A paragraph's value as a reader holds it: a DWG keeps a `\U+XXXX` as written. */ + const paragraphValue = (got: string, want: string): boolean => got === once(want) || got === want; + + /** A definition of paragraph text as the text of one line its file holds with it. */ + const lineOf = (definition: AttributeDefinition): AttributeDefinition => + definition.kind === "paragraph" + ? { + ...definition, + kind: "text", + align: definition.align ?? "left", + valign: definition.valign ?? "top", + } + : definition; + + /** The paragraph of an attribute or a definition of paragraph text, against what it must be. */ + const paragraphOf = ( + got: ReadAttributeParagraph | undefined, + definition: ParagraphAttributeDefinition, + want: { + readonly at: Point; + readonly height: number; + readonly width: number; + readonly turn: number; + readonly mirrored: boolean; + readonly label: string; + }, + ): void => { + const { label } = want; + if (!got) return say(`${label}: holds no paragraph`); + if (!sameName(got.style, definition.style ?? "Standard")) say(`${label}: style ${got.style}`); + if (!nearPoint(got.at, want.at)) say(`${label}: paragraph at ${got.at}, expected ${want.at}`); + for (const [what, a, b] of [ + ["height", got.height, want.height], + ["width", got.width, want.width], + ["attachment", got.attachment, paragraphAttachment(definition)], + ["line spacing", got.lineSpacing, written(definition.lineSpacing ?? 1)], + ] as const) { + if (!near(a, b)) say(`${label}: paragraph ${what} ${a}, expected ${b}`); + } + if (got.lineSpacingStyle !== (definition.lineSpacingStyle ?? "at-least")) { + say(`${label}: line spacing ${got.lineSpacingStyle}`); + } + // Its direction is written with 15 digits, which give its turn back within their rounding. + const turned = (((got.rotation - want.turn) % 360) + 360) % 360; + if (Math.min(turned, 360 - turned) > 1e-9) say(`${label}: paragraph turned ${got.rotation}`); + if ((got.mirrored ?? false) !== want.mirrored) say(`${label}: mirrored ${got.mirrored}`); + }; + const entity = ( got: ReadEntity | undefined, mine: ReadEntity | undefined, @@ -648,7 +716,12 @@ export function readProblems( if (!read) return say(`${label}: missing`); const style = styleOf(definition.style); if (read.tag !== twice(definition.tag)) say(`${label}: tag ${read.tag}`); - if (read.default !== twice(definition.value)) + const paragraph = definition.kind === "paragraph"; + if ( + paragraph + ? !paragraphValue(read.default ?? "", definition.value) + : read.default !== twice(definition.value) + ) say(`${label}: reads ${JSON.stringify(read.default)}`); if (read.prompt !== twice(definition.prompt ?? definition.tag)) say(`${label}: asks ${read.prompt}`); @@ -656,17 +729,27 @@ export function readProblems( placement( read, { - ...definition, + ...lineOf(definition), at: point(definition.at), height: written(definition.height), rotation: written(definition.rotation), - widthFactor: written(style?.widthFactor ?? 1), - obliqueAngle: written(style?.obliqueAngle ?? 0), + widthFactor: paragraph ? 1 : written(style?.widthFactor ?? 1), + obliqueAngle: paragraph ? 0 : written(style?.obliqueAngle ?? 0), mirrored: false, + paragraph, }, label, ); - start(read, mine?.attributeDefinitions[i], read.default ?? "", label); + if (definition.kind === "paragraph") { + paragraphOf(read.paragraph, definition, { + at: point(definition.at), + height: written(definition.height), + width: written(definition.width ?? 0), + turn: paragraphTurn(definition.rotation), + mirrored: false, + label, + }); + } else start(read, mine?.attributeDefinitions[i], read.default ?? "", label); }); } if (Object.keys(read.unread.malformed).length > 0) { diff --git a/test/read.test.ts b/test/read.test.ts index daefca9..a464c1f 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -1206,3 +1206,14 @@ test("a hatch with a group that is not a number is counted, not read as NaN", as assert.deepEqual(plain(read.unread.malformed), { "HATCH with a number that is not finite": 1 }); } }); + +test("a definition of paragraph text pays for its style's name against the block's items", async () => { + const d = createDrawing({ units: "in" }); + const style = "A" + "X".repeat(199); + d.textStyle({ name: style, font: "Arial" }); + d.block("B", {}, () => d.attribute("A", [0, 0], { kind: "paragraph", value: "A", style })); + const read = await readDXFWithin(toDXF(d.build()), {}, { ...READ_LIMITS, blockItems: 8 }); + const block = read.blocks.find((b) => b.name === "B")!; + assert.equal(block.attributeDefinitions.length, 0); + assert.equal(block.other["past the limit"], 1); +}); diff --git a/test/rules.test.ts b/test/rules.test.ts index 91a77be..b3f80f6 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -1495,3 +1495,81 @@ test("a hatch's pattern named SOLID is refused: a solid hatch has none", () => { /SOLID is the name/, ); }); + +test("an attribute of paragraph text and each insert's value of it are checked as a paragraph", () => { + const d = createDrawing(); + const at: Point = [0, 0]; + d.textStyle({ name: "HAND", font: "romans.shx" }); + d.block("NOTE", {}, () => { + d.attribute("NOTE", at, { kind: "paragraph", value: "ONE\nTWO \LTHREE\l", width: 2 }); + d.attribute("HAND", at, { kind: "paragraph", style: "HAND", valign: "bottom" }); + // @ts-expect-error: a brace is never closed. + assert.throws(() => d.attribute("A", at, { kind: "paragraph", value: "{\LA" }), /never closed/); + // @ts-expect-error: a width must be greater than 0. + assert.throws(() => d.attribute("B", at, { kind: "paragraph", width: 0 }), /greater than 0/); + assert.throws( + // @ts-expect-error: the leading CAD app takes a line spacing from 0.25 to 4. + () => d.attribute("C", at, { kind: "paragraph", lineSpacing: 5 }), + /from 0.25 to 4/, + ); + // @ts-expect-error: a paragraph is not set on its baseline. + assert.throws(() => d.attribute("D", at, { kind: "paragraph", valign: "baseline" }), /valign/); + // @ts-expect-error: nor is a width one of a line of text's. + assert.throws(() => d.attribute("E", at, { width: 2 }), Error); + // Nor beside a field a line of text has, nor in options held apart from the call. + // @ts-expect-error: a width beside a value. + assert.throws(() => d.attribute("F", at, { value: "x", width: 2 }), /width belongs/); + // @ts-expect-error: a line spacing beside a prompt. + assert.throws(() => d.attribute("G", at, { prompt: "p", lineSpacing: 2 }), /lineSpacing/); + const options = { kind: "text" as const, width: 12 }; + // @ts-expect-error: a width on options of one line. + assert.throws(() => d.attribute("H", at, options), /width belongs/); + }); + d.insert("NOTE", [0, 0], { attributes: { NOTE: "A\nB", HAND: "%%d" } }); + assert.deepEqual(d.build().entities[0], { + kind: "insert", + layer: "0", + block: "NOTE", + at: [0, 0], + attributes: { NOTE: "A\\PB", HAND: "%%d" }, + }); + // An insert's value is read in the definition's font, which the type does not know. + assert.throws( + () => d.insert("NOTE", [0, 0], { attributes: { HAND: "%%c6" } }), + /attribute "HAND": .*%%c in an SHX font/, + ); + assert.throws( + () => d.insert("NOTE", [0, 0], { attributes: { NOTE: "{x" } }), + /attribute "NOTE": .*never closed/, + ); + // lint holds a drawing written by hand to the same rules, and R12, which holds no block. + const drawing = d.build(); + const block = drawing.blocks![0]!; + const definition = block.attributes![0]!; + const broken = (changed: Record, values?: Record) => + lint({ + ...drawing, + blocks: [ + { ...block, attributes: [{ ...definition, ...changed } as never, block.attributes![1]!] }, + ], + entities: [{ ...drawing.entities[0]!, ...(values ? { attributes: values } : {}) } as never], + }).map((diagnostic) => diagnostic.message); + assert.deepEqual(broken({}), []); + assert.match(broken({ value: "\\Zx" }).join(), /code \\Z is not one tsdraft knows/); + assert.match(broken({ width: -1 }).join(), /width: .*greater than 0/); + assert.match(broken({ align: "fit" }).join(), /align must be/); + assert.match(broken({ kind: "lines" }).join(), /kind must be "text" or "paragraph"/); + assert.match( + broken({ kind: "text" }).join(), + /width belongs to an attribute definition of paragraph text/, + ); + assert.match(broken({}, { NOTE: "{x" }).join(), /attribute "NOTE": .*never closed/); + assert.match( + lint({ ...drawing, dxf: "R12" }) + .map((x) => x.message) + .join(), + /no blocks to R12/, + ); + // An insert that scales its block so unevenly that its width factor leaves the range is refused. + assert.throws(() => d.insert("NOTE", [0, 0], { scale: [1000, 0.001] }), /times as wide/); +}); diff --git a/test/shape.test.ts b/test/shape.test.ts index 49575c8..39619d8 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -12,7 +12,8 @@ import { toDXF, toJSON, toSVG, - type AttributeDefinition, + type ParagraphAttributeDefinition, + type TextAttributeDefinition, type Block, type Diagnostic, type DimensionStyle, @@ -333,7 +334,12 @@ const full: Required & { readonly layers: readonly [Layer, Required]; readonly blocks: readonly [ Block, - Required & { readonly attributes: readonly [Required] }, + Required & { + readonly attributes: readonly [ + Required, + Required, + ]; + }, ]; readonly xrefs: readonly [Required]; readonly layouts: readonly [ @@ -456,6 +462,7 @@ const full: Required & { base: [1, 2], attributes: [ { + kind: "text", tag: "TAG", prompt: "Tree tag", value: "T-0", @@ -465,6 +472,22 @@ const full: Required & { rotation: 0, ...justified, }, + { + kind: "paragraph", + tag: "NOTE", + prompt: "Note", + value: "PLANT IN\\PSPRING", + layer: "0", + at: [0, -4], + height: 0.5, + rotation: 0, + style: "NOTES", + width: 6, + align: "center", + valign: "middle", + lineSpacing: 1.5, + lineSpacingStyle: "exactly", + }, ], entities: [ { kind: "arc", layer: "0", center: [0, 0], radius: 3, startAngle: 0, endAngle: 90 }, From b97cd87fbaba24fae4b0ed54c1c3114d124ae463 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 17:06:09 -0500 Subject: [PATCH 17/35] Gradient hatches: written, read and plotted as CAD programs draw them Gradient hatches, in R2018 drawings. - `d.hatch(boundary, { gradient })` fills a hatch from one color to another: `linear`, `cylinder`, `spherical`, `hemispherical` or `curved`, or the `inverted-` form of the last four. `angle` turns it, in degrees, and `centered: false` moves it off the middle. Give two `colors`, or one `color` and a `tint` from 0, black, to 1, white. A color is an `Rgb`, `[red, green, blue]`, each a whole number from 0 to 255. - Both writers write a gradient as CAD programs hold it. A file cannot hold pure black as a gradient's color, so black is written as `[0, 0, 1]`. - `toSVG` draws a gradient as a `linearGradient` or a `radialGradient`, and `toPDF` as a shading inside the hatch's loops, in its own colors whatever the plot style table. `gradientPicture` gives what a gradient draws. A picture of a layout is now of format 2, which `svgToPDF` reads. - `readDXF` reads a hatch's `gradient`: its name as the file holds it, its angle, whether it is centered, its first two colors, and the tint of one color. - `lint` and the builder refuse, under the rule `hatch-gradient`, a gradient with a pattern, a name not of the nine, a field it does not have, an angle that is not a finite number under 1e100, a color that is not three whole numbers from 0 to 255, and a tint outside 0 to 1. Written as a literal, each of these is a compile error, apart from an angle of `NaN` or `Infinity`. - `readDXF` counts as malformed a hatch whose gradient angle or tint is too large to hold once read, rather than reading it as Infinity. - [Gradients](docs/fills.md#gradients) describes them. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 6 +- CHANGELOG.md | 12 ++ GUIDE.md | 4 +- README.md | 12 +- docs/fills.md | 86 +++++++++- docs/format.md | 8 +- docs/reading.md | 11 +- docs/rules.md | 4 + src/drawing.ts | 100 ++++++++++-- src/dxf-r2018.ts | 20 +++ src/fills.ts | 357 ++++++++++++++++++++++++++++++++++++++++- src/index.ts | 15 ++ src/lint.ts | 20 +++ src/pdf.ts | 158 +++++++++++++++++- src/read/check.ts | 9 ++ src/read/entities.ts | 67 +++++++- src/read/model.ts | 26 +++ src/rules.ts | 154 +++++++++++++++++- src/shape.ts | 4 +- src/svg.ts | 81 +++++++++- test/bounded.test.ts | 141 ++++++++++++++++ test/gradients.test.ts | 58 +++++++ test/pdf.test.ts | 61 ++++++- test/read.test.ts | 37 +++++ test/rules.test.ts | 190 ++++++++++++++++++++++ test/shape.test.ts | 43 ++++- 26 files changed, 1632 insertions(+), 52 deletions(-) create mode 100644 test/gradients.test.ts diff --git a/AGENTS.md b/AGENTS.md index d719a00..370979a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -387,7 +387,11 @@ a name, and `patternDrawnProblem` is the one check of what its lines draw, which `lint`, the builder and `toSVG` share: a pattern that would draw more than `HATCH_LINES` lines across the box of its loops, or place a number of 1e100 or more, is refused, and `toSVG` draws none of its - lines. + lines. A gradient is `gradientPicture`, from its loops and numbers as written: colors along a + line or out from a point in a frame mapped onto the hatch, which `toSVG` writes as a + `linearGradient` or `radialGradient` in the picture's definitions and `toPDF` as a shading in the + loops' clip. It plots in its own colors whatever the plot style table, and black is written as + `0,0,1`, since the leading CAD app reads a 421 of 0 as no color. - `src/pdf.ts` plots layouts to PDF from the pictures `toSVG` draws of them, and decides nothing about a drawing: every rule of what a sheet plots stays in `toSVG`, so the preview and the plot cannot part. It reads the closed set of elements and attributes `toSVG` writes diff --git a/CHANGELOG.md b/CHANGELOG.md index 12d9632..7b92456 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,18 @@ that names a pattern the drawing does not have, a scale or spacing not greater than 0, a pattern's definition that cannot be written, and a hatch whose pattern would draw more than 1,000,000 lines across its loops; two patterns of one name are a `duplicate-hatch-pattern`. +- Gradient hatches, in R2018 drawings. A hatch's `gradient` fills it from one color to another: + `linear`, `cylinder`, `spherical`, `hemispherical` or `curved`, or the `inverted-` form of the + last four, turned by `angle` and moved off the middle unless `centered`, with two `colors` or one + `color` and its `tint`. A color is an `Rgb`, `[red, green, blue]`, each a whole number from 0 + to 255. Both writers write it as CAD programs hold it, black as `[0, 0, 1]`, which a file can + hold, and `toSVG` and `toPDF` draw it as CAD programs plot it, in its own colors whatever the plot + style table: a `linearGradient` or `radialGradient`, and a shading. `gradientPicture` gives what + a gradient draws. `readDXF` and `readDWG` read a hatch's `gradient`. `lint` and the builder + refuse, under the rule `hatch-gradient`, a gradient with a pattern, a name of another kind, a + field it does not know, an angle that is not a finite number under 1e100, a color that is not + three whole numbers from 0 to 255 and a tint outside 0 to 1. `toSVG`'s pictures + of layouts are now of format 2, which `svgToPDF` reads. - `readDXF` and `readDWG` read a hatch, its loops of polylines or of lines and arcs as points and bulges, its pattern and its island style; a wipeout; an `MTEXT`'s background mask; the order a file's sort table draws a space or a block in, `drawOrder`; and whether wipeouts' frames show, diff --git a/GUIDE.md b/GUIDE.md index 1bf6bc3..12b521f 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -69,7 +69,7 @@ folder for the pictures, and warns of one that is missing. [docs/images.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/images.md) has them. `hatch` fills one outline, or a list of loops `{ points, bulges? }` where a loop inside another is a hole, solid in the layer's color, or with `pattern` draws a pattern `patterns()` added from the -firm's pattern file, or lines `spacing` apart; `wipeout` hides what is drawn before it behind a polygon; and +firm's pattern file, or lines `spacing` apart, or with `gradient` runs from one color to another; `wipeout` hides what is drawn before it behind a polygon; and a paragraph's `mask: true` hides what is drawn before it behind its text. Draw a fill before the lines over it. [docs/fills.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/fills.md) has them. @@ -623,7 +623,7 @@ writeFileSync("plan.dxf", toDXF(drawing)); ## What tsdraft cannot draw yet -- Gradient fills, and angular, arc length and ordinate dimensions. +- Arc length and ordinate dimensions. - A block read from another file. A block is drawn in the drawing that inserts it. An xref references a whole DWG file, as an overlay, and the pictures draw it only from a drawing you give. diff --git a/README.md b/README.md index 0aedb6a..0d934a3 100644 --- a/README.md +++ b/README.md @@ -198,8 +198,8 @@ toPDF(drawing, { images: { "aerial.png": readFileSync("aerial.png") } }); [Images](docs/images.md) has clips, frames and transparency, and what `lint` refuses. -A hatch fills the area inside its loops solid, a loop inside another a hole, or draws a pattern -of the firm's pattern file there. A wipeout hides what is drawn before it, and a paragraph's mask +A hatch fills the area inside its loops solid, a loop inside another a hole, draws a pattern +of the firm's pattern file there, or runs from one color to another as a gradient. A wipeout hides what is drawn before it, and a paragraph's mask hides it behind the text: ```ts @@ -224,7 +224,7 @@ d.hatch([ d.paragraph("VERIFY IN FIELD", { at: [40, 20], height: 3, mask: true }); ``` -[Fills, wipeouts and masks](docs/fills.md) has holes and arcs, patterns, wipeouts' frames, a +[Fills, wipeouts and masks](docs/fills.md) has holes and arcs, patterns, gradients, wipeouts' frames, a dimension style's mask and the draw order. A dimension measures between two points and writes what it measures. In the file it is a @@ -303,7 +303,7 @@ feet and inches with stacked fractions, words below the line and text on a leade layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have overlines in paragraph text, ellipses, splines or points, gradients, tables, color or transparency set on one +It does not yet have overlines in paragraph text, ellipses, splines or points, tables, color or transparency set on one entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit @@ -409,8 +409,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, transparency, how the plot draws one, and what `lint` refuses. -- [Fills, wipeouts and masks](docs/fills.md) covers hatches with holes, solid or of a pattern - file's patterns, wipeouts, the masks of paragraphs, leaders and dimensions, the draw order, and +- [Fills, wipeouts and masks](docs/fills.md) covers hatches with holes, solid, of a pattern + file's patterns or of a gradient, wipeouts, the masks of paragraphs, leaders and dimensions, the draw order, and what `lint` refuses. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. diff --git a/docs/fills.md b/docs/fills.md index 70d5666..0611d2d 100644 --- a/docs/fills.md +++ b/docs/fills.md @@ -3,7 +3,8 @@ A solid fill is a hatch: an area filled in its pen's color, which CAD programs hold as one entity a drafter selects, edits and measures as one. Wall poché, filled arrowheads, bar dots and the filled parts of symbols are hatches. A hatch with a pattern draws the pattern's lines inside its loops -instead, as for concrete, earth or brick. A wipeout is a polygon filled with the paper's color, which hides +instead, as for concrete, earth or brick, and a hatch with a gradient runs from one color to +another, as for a sky or a shaded roof. A wipeout is a polygon filled with the paper's color, which hides what is drawn before it. A mask hides what is drawn before a text, behind the text's box: a paragraph, a leader's note and a dimension's text each take one. @@ -62,7 +63,7 @@ A hatch is filled in its layer's color, with no outline whatever its lineweight. as a polyline of its own where the sheet shows one. In a block, an insert's scale and rotation place a hatch as they place the rest of the block, and a negative scale mirrors it. -Gradients come later. +A hatch can also be filled with a gradient: see [Gradients](#gradients). ## Patterns @@ -131,6 +132,80 @@ angle with the pattern's added, its base point scaled, turned and moved to the o scaled and turned to the line, and its dashes scaled. A firm's patterns can be read back from its drawings this way. +## Gradients + +A hatch with a `gradient` is filled from one color to another in place of its pen's color: a +sky behind an elevation, a shaded roof or a lawn on a site plan. Each color is a true color, +`[red, green, blue]`, each a whole number from 0 to 255. Give two colors, or one color and its +`tint`, from 0 for black to 1 for white, which gives the second as the color with its lightness set +to the tint, as CAD programs do: + +```ts +const d = createDrawing({ units: "ft" }); +d.hatch( + [ + [0, 10], + [40, 10], + [40, 20], + [0, 20], + ], + { + gradient: { + name: "linear", + angle: 90, + colors: [ + [255, 255, 255], + [30, 120, 200], + ], + }, + }, +); +d.hatch( + [ + [0, 0], + [40, 0], + [40, 8], + [0, 8], + ], + { gradient: { name: "spherical", color: [60, 160, 60], tint: 0.8 } }, +); +``` + +`name` is one of nine. `linear` runs from the first color to the second across the box of the +loops. `cylinder` runs from the first color at both sides to the second along the middle. +`spherical` runs from a spot of the second color out to the first, `hemispherical` from a spot half +the box's larger side below its middle, and `curved` from an oval along the bottom. Each `inverted-` name, +`inverted-cylinder`, `inverted-spherical`, `inverted-hemispherical` and `inverted-curved`, swaps its +pair's colors. `angle` turns the gradient about the middle of the box, in degrees counterclockwise, +and `centered: false` moves it off the middle, in the gradient's own directions before `angle` turns +it: a linear gradient or a cylinder then reaches half way at 0.3 of the way across, a spherical spot +moves left and up by a quarter of the box's larger side, a hemispherical one left by half of it, and +a curved oval left by a quarter of the box's width. They are 0 and `true` unless given. + +A gradient is worked out on the box of the loops, its arcs at their full extent, as CAD programs +work it out. At an angle that is not a quarter turn, a linear, cylinder or curved gradient spans the +box turned back by the angle; a spot keeps the size of the box's larger side, and the turned box's +at an odd multiple of 45 degrees. A box with no width or height draws nothing. + +A gradient plots in its own colors whatever the plot style table, `monochrome.ctb` included: `toSVG` +and `toPDF` draw it so. `toSVG` fills the loops with a `linearGradient` or a `radialGradient` and +`toPDF` with a shading, each with enough colors along a curve that it strays less than a level from +the gradient. The leading CAD app plots a gradient as a picture made of triangles between points it +chooses, so its colors stray from the gradient's between them, a few levels for most gradients and +more where a spot meets the corner of a box turned at an angle that is not a quarter turn. + +A file cannot hold pure black as a gradient's color: the leading CAD app reads it as no color and +takes another in its place. tsdraft writes black as `[0, 0, 1]`, and draws it so. + +`lint` and the builder refuse a gradient with a pattern, a name not of the nine, a field it does not +know, a color that is not three whole numbers from 0 to 255, a tint outside 0 to 1, two colors with +a tint, and an angle that is not a finite number under 1e100. A literal one of these is a compile +error, but for an angle of `NaN` or `Infinity`, which TypeScript types as any number. + +`readDXF` and `readDWG` read a hatch's gradient back as `gradient`: its `name` as the file holds +it, such as `LINEAR` or `INVSPHERICAL`, its `angle` in degrees, `centered`, the first two `colors`, +each `0xRRGGBB`, and for one color its `tint`, as single precision holds it. + ## Wipeouts `d.wipeout(points)` draws a polygon of three or more corners in the paper's color, which hides @@ -198,7 +273,12 @@ for lines of its own, 70 0, 76 its type, 2 for a pattern of the drawing's and 0 own, 52 its angle, 41 its scale or its spacing, 77 1 where its lines are crossed, and 78 the number of its lines. Each line follows, placed in the drawing: 53 its angle, 43 and 44 its base point, 45 and 46 its offset, 79 the number of its dashes and a 49 for each dash, with 15 -significant digits. A wipeout is a `WIPEOUT`, a square picture of one pixel clipped by its polygon, and +significant digits. A gradient is groups 450 to 470 after the seed point: 450 1, 451 0, 460 its angle in radians +with 15 significant digits, 461 0 when centered and 1 when not, 452 1 for one color, 462 its tint, +or 1 for two colors, 453 2, then for each color 463 0 or 1, 63 the index nearest it and 421 the +color, and 470 its name in capitals with no hyphen, such as `INVSPHERICAL`. For one color the second +is the color its tint gives. A wipeout is a `WIPEOUT`, a square picture of one pixel clipped by its +polygon, and the drawing holds `WIPEOUTVARIABLES` and the dictionary variable `WIPEOUTFRAME`, which is what CAD programs read of whether frames show. A mask is the background of an `MTEXT`, and a dimension style's is its `DIMTFILL` and `DIMTFILLCLR` and the background of the `MTEXT` of its picture. diff --git a/docs/format.md b/docs/format.md index 5e6fec1..af2e4b7 100644 --- a/docs/format.md +++ b/docs/format.md @@ -97,12 +97,14 @@ A drawing with no image has the JSON it had before images existed. [Images](imag them. A hatch is an entity of kind `"hatch"`, with its `layer` and its `loops`, each `{ points }` and -where a side is an arc its `bulges`, one for each side, its `pattern` where it is not solid, and -the `linetype` and `lineweight` of every entity. A pattern is `{ name }` of one of the drawing's +where a side is an arc its `bulges`, one for each side, its `pattern` or its `gradient` where it +is not solid, and the `linetype` and `lineweight` of every entity. A pattern is `{ name }` of one of the drawing's `patterns`, with its `scale`, `angle` and `origin` where they are set, or `{ spacing }` of lines of its own, with its `angle`, `crossed` and `origin`. `patterns` on the drawing holds its hatch patterns, each `{ name, description, lines }` and each line `{ angle, base, offset, dashes }`, the -dashes where it has them. A wipeout is an entity of kind `"wipeout"`, with its `layer` and its `points`. +dashes where it has them. A gradient is `{ name, angle, centered }` where they are set, with its +`colors`, two `[red, green, blue]`, or its `color` and `tint`. A wipeout is an entity of kind +`"wipeout"`, with its `layer` and its `points`. `wipeoutFrame: false` on the drawing hides every wipeout's frame. A paragraph's `mask` and a dimension style's `textMask` are written where they are set. A drawing with none of them has the JSON it had before they existed. [Fills, wipeouts and masks](fills.md) describes them. diff --git a/docs/reading.md b/docs/reading.md index 67367ae..7b1ae97 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -179,7 +179,16 @@ leader: `patternLines`, each `{ angle, base, offset, dashes? }` as the file holds it: placed in the drawing, with the pattern's angle added, the base point scaled, turned and moved to the origin, and the offset and dashes scaled, the offset turned to the line. [Patterns](fills.md#patterns) - says how a firm's patterns are read back this way. + says how a firm's patterns are read back this way. A hatch with a gradient holds `gradient`, left + out where group 450 is 0: its `name` as the file holds it, such as `LINEAR`, a name tsdraft does + not know included, its `angle` in degrees, `centered` where group 461 is 0, the first two + `colors`, each group 421 as `0xRRGGBB`, and, where it has one color, its `tint` as single + precision holds it. To build a `Hatch.gradient` from one, find the name whose `GRADIENT_NAMES` + entry is the file's `name`, and take each color apart as `[c >> 16, (c >> 8) & 255, c & 255]`; a + name with no entry is one tsdraft does not write. A hatch seen from below reads its gradient's + angle as 180 less the file's, as a pattern line's is; where that gradient is not centered, the + angle and `centered: false` do not give its mirror image, because its shift does not mirror with + the angle. - `wipeout`: its `points` in the world's coordinates, without the first again at the end. - An `mtext` with a background holds `mask`: its `offsetFactor`, and its `color` or `trueColor` where it is not in the drawing's background. diff --git a/docs/rules.md b/docs/rules.md index 7d50590..0567a15 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -73,6 +73,10 @@ it would take `1e+100` for `1e+10` and report nothing. alone, and its `angle` and `origin` are finite. The lines it places hold no number of 1e100 or more, and it draws at most 1,000,000 lines across the box of its loops. The rule of these is `hatch-pattern`. [Patterns](fills.md#patterns) has the rest. +- A hatch's `gradient` goes with no `pattern`. Its `name` is one of `GRADIENT_KINDS`, its `angle` + a finite number under 1e100 and `centered` true or false, and it has two `colors` or a `color` + and a `tint` from 0 to 1, each color three whole numbers from 0 to 255, and no other field. The rule of these is + `hatch-gradient`. [Gradients](fills.md#gradients) has the rest. - Arc angles are stored from 0 up to 360, so -90 becomes 270. An arc cannot come within 0.000001 degrees of a full turn, because its two angles would be written the same and the leading CAD app holds such an arc as having no length. Draw a diff --git a/src/drawing.ts b/src/drawing.ts index 2238c84..d03f0df 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -227,8 +227,12 @@ import { type LEADER_VERTICAL_ATTACHMENTS, HATCH_LOOP_POINTS, HATCH_NO_LOOPS, + GRADIENT_WITH_PATTERN, + type GRADIENT_KINDS, + readGradient, hatchPatternChoiceProblem, hatchPatternProblem, + type GradientOf, shown, undefinedHatchPatternProblem, textMaskProblem, @@ -874,18 +878,48 @@ export type HatchPatternChoice = readonly origin?: Point; }; +/** A true color: its red, green and blue, each a whole number from 0 to 255. */ +export type Rgb = readonly [red: number, green: number, blue: number]; + +/** + * How a gradient runs from its first color to its second. `linear` runs across the box of the + * loops; `cylinder` from the first color at both sides to the second along the middle; `spherical` + * from a spot of the second color out to the first; `hemispherical` from a spot half the box's + * larger side below its middle; `curved` from an oval along the bottom. Each `inverted-` name swaps + * its pair's colors. + */ +export type GradientName = (typeof GRADIENT_KINDS)[number]; + /** - * A hatch: an area filled solid in its pen's color, or with a pattern's lines in its pen, which - * the leading CAD app holds as one entity a drafter edits and measures as one. The area inside an - * odd number of its loops is filled, so a loop inside another is a hole, and a loop inside a hole - * fills again. R2018 only. + * A hatch's gradient: two colors, or one color and its tint, which gives the second as the color + * with its lightness set to the tint, from 0 for black to 1 for white. It is turned by `angle` + * about the middle of the box of the loops, and moved off the middle unless `centered`. CAD programs plot a gradient in its own colors, whatever the plot style table. + */ +export type HatchGradient = { + readonly name: GradientName; + /** Degrees counterclockwise. Defaults to 0. */ + readonly angle?: number; + /** Defaults to true. */ + readonly centered?: boolean; +} & ( + | { readonly colors: readonly [Rgb, Rgb]; readonly color?: never; readonly tint?: never } + | { readonly color: Rgb; readonly tint: number; readonly colors?: never } +); + +/** + * A hatch: an area filled solid in its pen's color, with a pattern's lines in its pen, or with a + * gradient, which the leading CAD app holds as one entity a drafter edits and measures as one. The + * area inside an odd number of its loops is filled, so a loop inside another is a hole, and a loop + * inside a hole fills again. R2018 only. */ export interface Hatch extends EntityBase { readonly kind: "hatch"; /** Its loops, in any order and either way round. */ readonly loops: readonly HatchLoop[]; - /** Its pattern. Missing, it is solid. */ + /** Its pattern. Missing, it is solid or a gradient. */ readonly pattern?: HatchPatternChoice; + /** Its gradient, never with a pattern. Missing, it is solid or a pattern. */ + readonly gradient?: HatchGradient; } /** @@ -1479,6 +1513,13 @@ export interface EntityOptions< readonly pen?: Z extends Standard ? PenOfStandard : PenWithoutStandard; } +/** Checks a hatch's gradient as `lint` does, and returns the copy it checked. */ +function hatchGradientCopy(given: unknown): HatchGradient { + const read = readGradient(given); + if ("problem" in read) return refuse("hatch-gradient", capitalized(read.problem)); + return read.gradient; +} + /** * A hatch's pattern as `hatch()` takes it: a `HatchPatternChoice` whose scale or spacing is greater * than 0 and not written as 0, with no field of the other kind. @@ -1506,11 +1547,12 @@ export type HatchPatternOf = }; /** - * The options of `hatch()`: its pattern, and the options of every entity. + * The options of `hatch()`: its pattern or its gradient, and the options of every entity. * * @typeParam S - The pattern's scale or spacing as written. + * @typeParam G - The gradient as written. */ -export interface HatchOptions< +export type HatchOptions< V extends DxfVersion = "R2018", T extends string = string, W extends number = number, @@ -1519,13 +1561,27 @@ export interface HatchOptions< Z extends Standard | undefined = undefined, P extends string = string, S extends number = number, -> extends EntityOptions { - /** - * The lines it is drawn with in its pen: a pattern that `patterns()` added, by its name, with its - * `scale`, `angle` and `origin`, or lines of its own, `spacing` apart. Solid when left out. - */ - readonly pattern?: HatchPatternOf; -} + G extends HatchGradient = HatchGradient, +> = EntityOptions & + ( + | { + /** + * The lines it is drawn with in its pen: a pattern that `patterns()` added, by its name, + * with its `scale`, `angle` and `origin`, or lines of its own, `spacing` apart. Solid when + * left out. + */ + readonly pattern?: HatchPatternOf; + readonly gradient?: never; + } + | { + /** + * Its gradient: two colors, or one color and its tint, never with a pattern. Each color + * is `[red, green, blue]`, each a whole number from 0 to 255. + */ + readonly gradient: GradientOf; + readonly pattern?: never; + } + ); /** * How wide a polyline is drawn: the width of every side, in drawing units, 0 or more. CAD @@ -3257,6 +3313,15 @@ export class DrawingBuilder< * }); * d.hatch([[10, 1], [12, 1], [12, 3], [10, 3]], { pattern: { spacing: 0.125, crossed: true } }); * ``` + * + * With `gradient`, it is filled from one color to another: two colors, or one color and its + * tint, `linear` across the loops or in one of the other kinds, turned by `angle`. + * + * ```ts + * d.hatch([[0, 4], [8, 4], [8, 6], [0, 6]], { + * gradient: { name: "linear", angle: 90, colors: [[30, 120, 200], [255, 255, 255]] }, + * }); + * ``` */ hatch< T extends string = string, @@ -3265,9 +3330,10 @@ export class DrawingBuilder< I extends string = string, P extends string = string, S extends number = number, + const G extends HatchGradient = HatchGradient, >( boundary: readonly Point[] | readonly HatchLoop[], - options: HatchOptions = {}, + options: HatchOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.hatch, options, () => { if (this.dxf === "R12") refuse("hatch", R12_ONLY.hatches); @@ -3293,11 +3359,15 @@ export class DrawingBuilder< return { points, ...(bulges === undefined ? {} : { bulges: [...bulges] }) }; }); const choice: unknown = options.pattern; + const shade: unknown = options.gradient; + if (choice !== undefined && shade !== undefined) + refuse("hatch-gradient", capitalized(GRADIENT_WITH_PATTERN)); return { kind: "hatch", layer: this.#current, loops, ...(choice === undefined ? {} : { pattern: this.#hatchPattern(choice, loops) }), + ...(shade === undefined ? {} : { gradient: hatchGradientCopy(shade) }), }; }); } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index cb1c100..5d9b418 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -57,8 +57,12 @@ import type { HatchPattern, } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; +import { nearestColorIndex } from "./svg.ts"; import { dimensionMask, + GRADIENT_NAMES, + gradientWritten, + rgbNumber, hatchLines, patternFinder, loopBulged, @@ -1359,6 +1363,22 @@ function writeEntity( g(98, 1); g(10, 0); g(20, 0); + const gradient = gradientWritten(e.gradient); + if (gradient !== undefined) { + g(450, 1); + g(451, 0); + g(460, fifteenDigits(gradient.angle)); + g(461, gradient.centered ? 0 : 1); + g(452, gradient.single ? 1 : 0); + g(462, gradient.tint); + g(453, 2); + gradient.colors.forEach((color, k) => { + g(463, k); + g(63, nearestColorIndex(color)); + g(421, rgbNumber(color)); + }); + g(470, GRADIENT_NAMES[gradient.name]); + } return; } case "wipeout": { diff --git a/src/fills.ts b/src/fills.ts index 59c7856..8c81fdf 100644 --- a/src/fills.ts +++ b/src/fills.ts @@ -7,23 +7,32 @@ // lower-left corner the polygon's least X and Y and its side the larger of the polygon's width and // height, clipped by the polygon in that pixel's axes, y down from its top. It plots a text's mask // as the text's box grown by the mask's factor less one times its height, each side. +import type { Matrix } from "./blocks.ts"; import type { Drawing, Entity, + GradientName, Hatch, HatchLoop, HatchPattern, PatternLine, Point, Polyline, + Rgb, } from "./drawing.ts"; import { placedLines, userLines, type PlacedLine } from "./patterns.ts"; -import { written } from "./format.ts"; +import { fifteenDigits, written } from "./format.ts"; import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; import { placer, type ParagraphLayout, type ParagraphToMeasure } from "./paragraphs.ts"; -import { direction, polylineSides, type PolylineSide } from "./polylines.ts"; -import { HATCH_LINES, PATTERN_ITEMS, PATTERN_REACH, patternDensityProblem } from "./rules.ts"; +import { direction, polylineSides, sideArc, type PolylineSide } from "./polylines.ts"; +import { + HATCH_LINES, + PATTERN_ITEMS, + PATTERN_REACH, + patternDensityProblem, + rgbOf, +} from "./rules.ts"; import { filled } from "./shape.ts"; /** @@ -310,6 +319,348 @@ export function patternDrawnProblem(box: LoopsBox, spread: PatternSpread): strin return count <= HATCH_LINES ? undefined : patternDensityProblem(count); } +/** The name a file holds for each gradient, group 470. */ +export const GRADIENT_NAMES: Readonly> = { + linear: "LINEAR", + cylinder: "CYLINDER", + "inverted-cylinder": "INVCYLINDER", + spherical: "SPHERICAL", + "inverted-spherical": "INVSPHERICAL", + hemispherical: "HEMISPHERICAL", + "inverted-hemispherical": "INVHEMISPHERICAL", + curved: "CURVED", + "inverted-curved": "INVCURVED", +}; + +/** A gradient as both writers write it, from its numbers as written. */ +export interface GradientWritten { + readonly name: GradientName; + /** Group 460: radians, as `fifteenDigits` writes them. */ + readonly angle: number; + readonly centered: boolean; + /** Group 452: true for one color and its tint. */ + readonly single: boolean; + /** Group 462: the tint as written for one color, and 1 for two. */ + readonly tint: number; + /** The two colors of groups 421: for one color, the color and `tintColor` of it. */ + readonly colors: readonly [Rgb, Rgb]; +} + +/** + * A hatch's gradient as written, or undefined for none and for one whose name, colors or tint the + * rules refuse. An angle that is not finite is taken as 0, and a centering other than false as true. + */ +export function gradientWritten(gradient: unknown): GradientWritten | undefined { + if (typeof gradient !== "object" || gradient === null || Array.isArray(gradient)) return; + // Each field is read once, and each color copied, so what is checked is what is written. + const { name, angle, centered, colors, color, tint } = gradient as Record; + if (typeof name !== "string" || !Object.hasOwn(GRADIENT_NAMES, name)) return; + const degrees = typeof angle === "number" && Number.isFinite(angle) ? written(angle) : 0; + const base = { + name: name as GradientName, + angle: Number(fifteenDigits((degrees * Math.PI) / 180)), + centered: centered !== false, + }; + if (colors !== undefined) { + if (!Array.isArray(colors) || colors.length !== 2) return; + const [first, second] = [rgbOf(colors[0]), rgbOf(colors[1])]; + if (!first || !second) return; + return { ...base, single: false, tint: 1, colors: [held(first), held(second)] }; + } + const one = rgbOf(color); + if (!one || typeof tint !== "number" || !(tint >= 0 && tint <= 1)) return; + const shade = written(tint); + return { + ...base, + single: true, + tint: shade, + colors: [held(one), held(tintColor(one, shade))], + }; +} + +/** + * A gradient's color as a file holds it: black as 0,0,1, since the leading CAD app reads a true + * color of 0 as none and takes the index's color in its place. + */ +const held = (color: Rgb): Rgb => + color[0] === 0 && color[1] === 0 && color[2] === 0 ? [0, 0, 1] : [color[0], color[1], color[2]]; + +/** A true color as one number, `0xRRGGBB`, as group 421 holds it. */ +export const rgbNumber = ([r, g, b]: Rgb): number => (r << 16) | (g << 8) | b; + +/** + * The second color of a gradient of one color, as the leading CAD app stores it for a tint: the + * color with its lightness, in hue, lightness and saturation, set to the tint, its hue in whole + * degrees and its saturation in whole hundredths. + */ +export function tintColor([r, g, b]: Rgb, tint: number): Rgb { + const [max, min] = [Math.max(r, g, b), Math.min(r, g, b)]; + const lightness = (max + min) / 510; + const spread = + max === min + ? 0 + : lightness <= 0.5 + ? (max - min) / (max + min) + : (max - min) / (510 - max - min); + const saturation = Math.round(spread * 100) / 100; + let hue = 0; + if (max !== min) { + if (max === r) hue = (g - b) / (max - min); + else if (max === g) hue = 2 + (b - r) / (max - min); + else hue = 4 + (r - g) / (max - min); + } + hue = ((Math.round(hue * 60) % 360) + 360) % 360; + const high = tint <= 0.5 ? tint * (1 + saturation) : tint + saturation - tint * saturation; + const low = 2 * tint - high; + const channel = (at: number): number => { + const x = ((at % 360) + 360) % 360; + const v = + x < 60 + ? low + ((high - low) * x) / 60 + : x < 180 + ? high + : x < 240 + ? low + ((high - low) * (240 - x)) / 60 + : low; + return Math.round(v * 255); + }; + return [channel(hue + 120), channel(hue), channel(hue - 120)]; +} + +/** A color of a gradient's picture, where it lies from 0 to 1 along the picture. */ +export interface GradientStop { + readonly offset: number; + readonly color: Rgb; +} + +/** + * What a gradient draws, as the leading CAD app plots it: its colors along a line, `linear`, or + * out from a point, `radial`, each in a frame that `frame` maps onto the hatch's coordinates. A + * linear picture runs from x 0 to x 1 of its frame, and a radial one from its frame's origin to the + * circle of radius 1 about it; past either end it keeps the end's color. The colors between two + * stops run straight from one to the other. + */ +export interface GradientPicture { + readonly kind: "linear" | "radial"; + readonly frame: Matrix; + readonly stops: readonly GradientStop[]; +} + +const translate = (x: number, y: number): Matrix => [1, 0, 0, 1, x, y]; +const scale = (x: number, y: number): Matrix => [x, 0, 0, y, 0, 0]; +const turn = (a: number): Matrix => [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]; +const times = (...ms: Matrix[]): Matrix => + ms.reduce((m, n): Matrix => [ + m[0] * n[0] + m[2] * n[1], + m[1] * n[0] + m[3] * n[1], + m[0] * n[2] + m[2] * n[3], + m[1] * n[2] + m[3] * n[3], + m[0] * n[4] + m[2] * n[5] + m[4], + m[1] * n[4] + m[3] * n[5] + m[5], + ]); + +/** + * How many colors a curve's picture holds, each rounded to a whole level: enough that it strays + * less than a level from the curve. + */ +const FALLOFF_STOPS = 33; +const CYLINDER_STOPS = 33; +/** The most colors a gradient's picture holds, which `svgToPDF` reads no more than. */ +export const GRADIENT_STOPS = Math.max(FALLOFF_STOPS, CYLINDER_STOPS); +/** Where a gradient that is not centered is half way along t, and where its spots move. */ +const SHIFTED_MIDDLE = 0.3; +const SPOT_SHIFT = 0.25; +/** How much a curved gradient's oval is squeezed across, centered and not. */ +const CURVED_ACROSS = { centered: 2 / 3, shifted: 4 / 5 } as const; + +/** + * Walks a gradient hatch's sides and gives its picture. The leading CAD app works a gradient out + * in two frames, each a unit square about the middle of the box of the loops, its arcs at their + * full extent, turned by the gradient's angle a: the box frame scaled by W and H, the sides of the + * box of the loops turned by minus a reduced by quarter turns to -45 to 45 degrees; and the square + * frame scaled by L both ways, the box's larger side, or the turned box's at an odd multiple of 45 + * degrees. A box with no width or height draws nothing. + */ +export function gradientBoxer(g: GradientWritten): { + side(from: Point, to: Point, bulge: number): void; + picture(): GradientPicture | undefined; +} { + const quarter = Math.PI / 2; + const reduced = g.angle - quarter * Math.round(g.angle / quarter); + const [c, s] = [Math.cos(reduced), Math.sin(reduced)]; + // Across, up, and the two of the turned box. + const axes: readonly Point[] = [ + [1, 0], + [0, 1], + [c, s], + [-s, c], + ]; + const low = [Infinity, Infinity, Infinity, Infinity]; + const high = [-Infinity, -Infinity, -Infinity, -Infinity]; + const include = (p: Point) => { + for (let k = 0; k < 4; k++) { + const along = p[0] * axes[k]![0] + p[1] * axes[k]![1]; + if (along < low[k]!) low[k] = along; + if (along > high[k]!) high[k] = along; + } + }; + return { + side(from, to, bulge) { + include(from); + include(to); + const arc = sideArc(from, to, bulge); + if (!arc) return; + // The arc's farthest point along each axis, either way, where it lies inside its sweep. + const span = Math.abs(arc.sweep); + for (const [x, y] of axes) + for (const sign of [1, -1]) { + const at = Math.atan2(sign * y, sign * x); + const gone = arc.sweep > 0 ? at - arc.start : arc.start - at; + const turned = ((gone % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI); + if (turned <= span) + include([arc.center[0] + sign * x * arc.radius, arc.center[1] + sign * y * arc.radius]); + } + }, + picture() { + const [w, h, W, H] = [0, 1, 2, 3].map((k) => high[k]! - low[k]!) as [ + number, + number, + number, + number, + ]; + if (!(w > 0 && h > 0 && W > 0 && H > 0) || !Number.isFinite(w + h + W + H)) return; + const middle: Point = [(low[0]! + high[0]!) / 2, (low[1]! + high[1]!) / 2]; + const diagonal = Math.abs(Math.abs(reduced) - Math.PI / 4) < 1e-9; + const side = diagonal ? Math.max(W, H) : Math.max(w, h); + const box = times(translate(...middle), scale(W, H), turn(g.angle)); + const square = times(translate(...middle), scale(side, side), turn(g.angle)); + return pictured(g, { box, square, middle, w, h, W, H }); + }, + }; +} + +/** The frames of a gradient's box, and the sides they are made from. */ +interface Frames { + readonly box: Matrix; + readonly square: Matrix; + readonly middle: Point; + readonly w: number; + readonly h: number; + readonly W: number; + readonly H: number; +} + +/** A gradient's picture in its frames. */ +function pictured(g: GradientWritten, f: Frames): GradientPicture { + const inverted = g.name.startsWith("inverted-"); + const [from, to] = inverted ? [g.colors[1], g.colors[0]] : g.colors; + const mix = (t: number): Rgb => + [0, 1, 2].map((k) => Math.round(from[k]! + (to[k]! - from[k]!) * t)) as unknown as Rgb; + const shift = g.centered ? 0 : 1; + // A falloff from the second color at the middle of a spot, r 0, to the first at its edge, r 1. + const falloff = (): GradientStop[] => + Array.from({ length: FALLOFF_STOPS }, (_, k) => { + const r = k / (FALLOFF_STOPS - 1); + return { offset: r, color: mix(Math.cos((Math.PI / 2) * r)) }; + }); + // Where t falls for a fraction of the way along a gradient that is not centered. + const unbent = (t: number): number => + g.centered + ? t + : t <= 0.5 + ? 2 * SHIFTED_MIDDLE * t + : SHIFTED_MIDDLE + 2 * (1 - SHIFTED_MIDDLE) * (t - 0.5); + const across = times(f.box, translate(-0.5, 0)); + switch (g.name) { + case "linear": { + if (!g.centered) { + return { + kind: "linear", + frame: across, + stops: [ + { offset: 0, color: mix(0) }, + { offset: SHIFTED_MIDDLE, color: mix(0.5) }, + { offset: 1, color: mix(1) }, + ], + }; + } + // The plane through the middle and the box's corners, each held to 0 to 1: the gradient + // itself unless a corner falls past an end of it. + const u = (x: number, y: number) => + Math.min( + 1, + Math.max(0, 0.5 + (Math.cos(g.angle) * x) / f.W + (Math.sin(g.angle) * y) / f.H), + ) - 0.5; + const [a, b] = [u(f.w / 2, f.h / 2), u(-f.w / 2, f.h / 2)]; + const [gx, gy] = [(a - b) / f.w, (a + b) / f.h]; + const size = gx * gx + gy * gy; + const [ex, ey] = [gx / size, gy / size]; + return { + kind: "linear", + frame: [ex, ey, -ey, ex, f.middle[0] - ex / 2, f.middle[1] - ey / 2], + stops: [ + { offset: 0, color: mix(0) }, + { offset: 1, color: mix(1) }, + ], + }; + } + case "cylinder": + case "inverted-cylinder": + return { + kind: "linear", + frame: across, + stops: Array.from({ length: CYLINDER_STOPS }, (_, k) => { + const t = k / (CYLINDER_STOPS - 1); + return { offset: unbent(t), color: mix(Math.sin(Math.PI * t)) }; + }), + }; + case "spherical": + case "inverted-spherical": + return { + kind: "radial", + frame: times(f.square, translate(-SPOT_SHIFT * shift, SPOT_SHIFT * shift), scale(0.5, 0.5)), + stops: falloff(), + }; + case "hemispherical": + case "inverted-hemispherical": + return { + kind: "radial", + frame: times(f.square, translate(-2 * SPOT_SHIFT * shift, -0.5)), + stops: falloff(), + }; + case "curved": + case "inverted-curved": { + const k = g.centered ? CURVED_ACROSS.centered : CURVED_ACROSS.shifted; + return { + kind: "radial", + frame: times(f.box, translate(-SPOT_SHIFT * shift, -0.5), scale(1 / k, 1)), + stops: falloff(), + }; + } + } +} + +/** + * The picture of a hatch's gradient, from its loops and gradient as written: undefined for a hatch + * with no gradient, for one the rules refuse, and for loops whose box has no width or height. + */ +export function gradientPicture( + hatch: Pick, +): GradientPicture | undefined { + const g = gradientWritten(hatch.gradient); + if (g === undefined) return undefined; + const boxer = gradientBoxer(g); + for (const loop of drawnLoops(hatch.loops)) { + for (const side of loopSides(loop)) { + boxer.side(writtenPoint(side.from), writtenPoint(side.to), written(side.bulge)); + } + } + return boxer.picture(); +} + +/** A point as the writers write it. */ +export const writtenPoint = ([x, y]: Point): Point => [written(x), written(y)]; + /** The sides of a hatch's loop, as a closed polyline's. */ export function loopSides(loop: HatchLoop): PolylineSide[] { return polylineSides(loopOutline(loop, "")); diff --git a/src/index.ts b/src/index.ts index ec1ae88..e39e1a0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -79,7 +79,9 @@ export { type DxfVersion, type Entity, type EntityOptions, + type GradientName, type Hatch, + type HatchGradient, type HatchLoop, type HatchOptions, type HatchPattern, @@ -122,6 +124,7 @@ export { type ParagraphOptions, type ParagraphVerticalAlign, type Point, + type Rgb, type Polyline, type PolylineOptions, type RadiusDimension, @@ -178,10 +181,15 @@ export { } from "./images.ts"; export { dimensionMask, + GRADIENT_NAMES, + gradientPicture, + gradientWritten, hatchLines, loopBulged, maskOf, patternFinder, + rgbNumber, + tintColor, variableDictionaryHandle, WIPEOUT_APPLICATION, wipeoutClip, @@ -189,6 +197,9 @@ export { wipeoutFrameVariableHandle, wipeoutPicture, wipeoutVariablesHandle, + type GradientPicture, + type GradientStop, + type GradientWritten, } from "./fills.ts"; export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; export { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; @@ -321,6 +332,7 @@ export type { ObliqueAngle, PaperLength, PaperOf, + GradientOf, LineSpacing, ParagraphValue, Pattern, @@ -334,6 +346,7 @@ export type { XrefPath, } from "./rules.ts"; export { + GRADIENT_KINDS, LEADER_ATTACHMENTS, LEADER_DIRECTIONS, LEADER_SHAFT_KINDS, @@ -375,6 +388,7 @@ export { BLOCK_ITEMS, CENSUS_LIMIT, dimensionTextParts, + gradientDegrees, GEOMETRY_ITEMS, READ_FORMAT, type DrawingRead, @@ -398,6 +412,7 @@ export { type ReadEntityBase, type ReadField, type ReadHatch, + type ReadGradient, type ReadHatchLoop, type ReadHeader, type ReadImage, diff --git a/src/lint.ts b/src/lint.ts index 5be9b21..24f91c6 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -188,6 +188,8 @@ import { WIPEOUT_FLAT, WIPEOUT_FRAME, WIPEOUT_POINTS, + GRADIENT_WITH_PATTERN, + hatchGradientProblem, hatchPatternChoiceProblem, hatchPatternNameProblem, PATTERN_ITEMS, @@ -250,6 +252,7 @@ export type LintRule = | "image" | "hatch" | "hatch-pattern" + | "hatch-gradient" | "duplicate-hatch-pattern" | "wipeout" | "zero-length" @@ -971,6 +974,20 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (drawn) add("hatch-pattern", "error", drawn); }; + /** What is wrong with each object a hatch gives as its gradient, worked out once. */ + const gradients = new WeakMap(); + /** Checks a hatch's gradient: its fields, and that the hatch has no pattern beside it. */ + const lintHatchGradient = (hatch: Hatch, add: Add): void => { + if (hatch.pattern !== undefined) return add("hatch-gradient", "error", GRADIENT_WITH_PATTERN); + const gradient: unknown = hatch.gradient; + let problem: string | undefined; + if (typeof gradient === "object" && gradient !== null) { + if (gradients.has(gradient)) problem = gradients.get(gradient); + else gradients.set(gradient, (problem = hatchGradientProblem(gradient))); + } else problem = hatchGradientProblem(gradient); + if (problem) add("hatch-gradient", "error", problem); + }; + /** What is wrong with a reference to a linetype, which the leading CAD app discards a drawing over. */ const missing = (name: unknown): string | undefined => { if (typeof name !== "string") return "a linetype is named by a string"; @@ -2069,6 +2086,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (entity.kind === "hatch" && entity.pattern !== undefined) { lintHatchPattern(entity, add, problems.length === 0, here); } + if (entity.kind === "hatch" && entity.gradient !== undefined) { + lintHatchGradient(entity, add); + } // Each side against each other one, paid for by the pairs past the first 4,096. if (entity.kind === "wipeout" && entity.points.length > 3 && problems.length === 0) { const n = entity.points.length; diff --git a/src/pdf.ts b/src/pdf.ts index ee7f8d5..b0009a7 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -3,6 +3,7 @@ // drawing: it turns the elements of that picture into the operators of a page. import type { XrefDrawings } from "./blocks.ts"; import type { Drawing } from "./drawing.ts"; +import { GRADIENT_STOPS } from "./fills.ts"; import { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; import { FONTS, fontInfo, type Font, capHeightOf } from "./fonts.ts"; import { paperInfo } from "./papers.ts"; @@ -253,6 +254,9 @@ const ELEMENTS = new Set([ "defs", "image", "use", + "linearGradient", + "radialGradient", + "stop", ]); /** The attributes it writes on them, apart from `data-` ones, which say what an element is. */ @@ -293,8 +297,41 @@ const ATTRIBUTES = new Set([ "preserveAspectRatio", "clip-rule", "fill-rule", + "gradientUnits", + "gradientTransform", + "spreadMethod", + "offset", + "stop-color", ]); +/** A gradient a picture holds in its definitions: its kind, its frame and its colors. */ +interface Gradient { + readonly kind: "linear" | "radial"; + readonly frame: Matrix; + readonly stops: { readonly offset: number; readonly color: readonly number[] }[]; +} + +/** Where a gradient's stop lies, as its function's bounds are written. */ +const stopOffset = (offset: number): string => real(offset, 9); + +/** + * A gradient's colors as a PDF function of 0 to 1: one linear function between each two stops, + * stitched. The stops run from 0 to 1, each past the last. + */ +function gradientFunction(stops: Gradient["stops"]): string { + const rgb = (color: readonly number[]) => color.map((c) => real(c / 255, 5)).join(" "); + const parts = stops + .slice(1) + .map( + (stop, i) => + `<< /FunctionType 2 /Domain [0 1] /C0 [${rgb(stops[i]!.color)}] /C1 [${rgb(stop.color)}] /N 1 >>`, + ); + if (parts.length === 1) return parts[0]!; + const bounds = stops.slice(1, -1).map((stop) => stopOffset(stop.offset)); + const encode = parts.map(() => "0 1").join(" "); + return `<< /FunctionType 3 /Domain [0 1] /Functions [${parts.join(" ")}] /Bounds [${bounds.join(" ")}] /Encode [${encode}] >>`; +} + /** * Text with the four entities `toSVG` escapes with, and the line feed and the tab it writes as * ` ` and ` `, in their place. Any other `&` is refused. @@ -1175,6 +1212,12 @@ class PdfWriter { >(); /** Each raster file the picture holds, by its id. */ const rasters = new Map(); + /** Each gradient the picture holds, by its id, and the one being read. */ + const gradients = new Map(); + let gradient: { id: string; tag: string; held: Gradient } | undefined; + /** The shadings the page paints, by their names in its resources, and the name of each gradient's. */ + const shadings = new Map(); + const shaded = new Map(); /** The clip path being read, whose rectangles are kept and not drawn. */ let inClip: string | undefined; /** The layer of the marked content open, and the pen last set at this depth of `q`. */ @@ -1264,7 +1307,9 @@ class PdfWriter { : text === undefined && (tag === "clipPath" ? inClip !== undefined - : inClip === undefined && names.at(-1) === tag); + : tag === "linearGradient" || tag === "radialGradient" + ? gradient?.tag === tag + : inClip === undefined && gradient === undefined && names.at(-1) === tag); // What the picture holds in its definitions is kept there, and drawn where a use names it. const inDefs = names.includes("defs"); if ( @@ -1294,7 +1339,21 @@ class PdfWriter { } text = undefined; } else if (tag === "clipPath") inClip = undefined; - else if (tag === "defs") names.pop(); + else if (gradient !== undefined) { + const { stops } = gradient.held; + // The stops run from 0 to 1, each past the last as the function's bounds are written. + const at = stops.map((stop) => Number(stopOffset(stop.offset))); + if ( + stops.length < 2 || + at[0] !== 0 || + at.at(-1) !== 1 || + at.some((offset, i) => i > 0 && !(offset > at[i - 1]!)) + ) { + throw refuse(`the stops of the gradient ${JSON.stringify(gradient.id)}`, where(tag)); + } + gradients.set(gradient.id, gradient.held); + gradient = undefined; + } else if (tag === "defs") names.pop(); else if (tag === "g" || tag === "svg") { names.pop(); ended = names.length === 0; @@ -1379,6 +1438,56 @@ class PdfWriter { if (!selfClosing) names.push("defs"); continue; } + if (inDefs && gradient !== undefined) { + if (tag !== "stop" || !selfClosing || gradient.held.stops.length === GRADIENT_STOPS) + throw refuse(`<${tag}> in a gradient`, where(tag)); + const extra = Object.keys(element).find( + (name) => name !== "offset" && name !== "stop-color", + ); + if (extra !== undefined) throw refuse(`the attribute ${extra} of a stop`, where(tag)); + const color = /^#([0-9a-f]{6})$/.exec(element["stop-color"] ?? "")?.[1]; + if (color === undefined) + throw refuse(`the stop-color ${JSON.stringify(element["stop-color"])}`, where(tag)); + gradient.held.stops.push({ + offset: number("offset"), + color: [0, 2, 4].map((k) => Number.parseInt(color.slice(k, k + 2), 16)), + }); + continue; + } + if (inDefs && (tag === "linearGradient" || tag === "radialGradient")) { + const linear = tag === "linearGradient"; + // The unit frame of `gradientPicture`, which the gradient's transform maps. + const own = linear ? { x1: "0", y1: "0", x2: "1", y2: "0" } : { cx: "0", cy: "0", r: "1" }; + const expected = { ...own, gradientUnits: "userSpaceOnUse", spreadMethod: "pad" }; + const extra = Object.keys(element).find( + (name) => + name !== "id" && + name !== "gradientTransform" && + element[name] !== expected[name as keyof typeof expected], + ); + // One matrix, as `toSVG` writes it: an empty list would be read as no transform. + const transform = element.gradientTransform ?? ""; + if ( + selfClosing || + element.id === undefined || + !/^matrix\([^()]*\)$/.test(transform) || + gradients.has(element.id) || + extra !== undefined || + Object.keys(expected).some((name) => element[name] === undefined) + ) { + throw refuse("a gradient that is not one of gradientPicture's", where(tag)); + } + gradient = { + id: element.id, + tag, + held: { + kind: linear ? "linear" : "radial", + frame: transformOf(transform, where(tag)), + stops: [], + }, + }; + continue; + } if (inDefs) { if (tag !== "image" || !selfClosing || element.id === undefined) { throw refuse(`<${tag}> in the definitions`, where(tag)); @@ -1508,6 +1617,47 @@ class PdfWriter { } // The hidden rectangle of a view, and the white of the paper, put no ink on the page. if (element.visibility === "hidden" || element["data-paper-sheet"] !== undefined) continue; + const named = /^url\(#([^)]+)\)$/.exec(element.fill ?? "")?.[1]; + if (named !== undefined) { + // A hatch's gradient: its shading, one for each gradient, painted inside its loops. + const held = gradients.get(named); + if (tag !== "path" || held === undefined || element.stroke !== "none") { + throw refuse(`the fill ${JSON.stringify(element.fill)}`, where(tag)); + } + const rule = element["fill-rule"]; + if (rule !== undefined && rule !== "evenodd") + throw refuse(`the fill rule ${JSON.stringify(rule)}`, where(tag)); + const m = compose(inherited.matrix, held.frame); + if (!(m[0] * m[3] - m[1] * m[2] !== 0) || !m.every(Number.isFinite)) continue; + let key = shaded.get(named); + if (key === undefined) { + key = `Sh${shadings.size + 1}`; + const object = this.reserve(); + shadings.set(key, object); + shaded.set(named, key); + const coords = held.kind === "linear" ? "[0 0 1 0]" : "[0 0 0 0 0 1]"; + this.object( + object, + `<< /ShadingType ${held.kind === "linear" ? 2 : 3} /ColorSpace /DeviceRGB /Coords ${coords} /Function ${gradientFunction(held.stops)} /Extend [true true] >>`, + ); + } + mark(inherited.layer); + content.add("q"); + const p = (point: readonly [number, number]) => + apply(inherited.matrix, point[0], point[1]).map(num).join(" "); + for (const piece of pathPieces(element.d ?? "", where(tag), stretchOf(inherited.matrix))) { + if (piece.kind === "move") content.add(`${p(piece.to)} m`); + else if (piece.kind === "line") content.add(`${p(piece.to)} l`); + else if (piece.kind === "curve") + content.add(`${p(piece.c1)} ${p(piece.c2)} ${p(piece.to)} c`); + else content.add("h"); + } + content.add(rule === "evenodd" ? "W* n" : "W n"); + content.add(`${m.map((v, i) => (i < 4 ? real(v, 9) : num(v))).join(" ")} cm`); + content.add(`/${key} sh`); + content.add("Q"); + continue; + } const stroke = colorOf(inherited.stroke, where(tag)); const fill = colorOf(inherited.fill, where(tag)); // The thinnest line, which `toSVG` marks, plots 0 wide: the thinnest the printer draws. @@ -1577,7 +1727,7 @@ class PdfWriter { } paint(pieces, inherited.matrix, state); } - if (!paper || stack.length > 0 || text || inClip !== undefined) { + if (!paper || stack.length > 0 || text || inClip !== undefined || gradient !== undefined) { throw refuse("a picture that ends before its last element closes", `picture ${page}`); } close(); @@ -1600,10 +1750,12 @@ class PdfWriter { ); const layerList = [...marks].map(([layer, key]) => `/${key} ${this.layers.get(layer)} 0 R`); const imageList = [...images].map((key) => `/${key} ${this.images.get(key)!.object} 0 R`); + const shadingList = [...shadings].map(([key, object]) => `/${key} ${object} 0 R`); const resources = [ fontList.length > 0 ? `/Font << ${fontList.join(" ")} >>` : "", layerList.length > 0 ? `/Properties << ${layerList.join(" ")} >>` : "", imageList.length > 0 ? `/XObject << ${imageList.join(" ")} >>` : "", + shadingList.length > 0 ? `/Shading << ${shadingList.join(" ")} >>` : "", ] .filter(Boolean) .join(" "); diff --git a/src/read/check.ts b/src/read/check.ts index f2797f0..c22db66 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -339,6 +339,15 @@ const ENTITY: Readonly> = { fields: { angle: "number", base: "point", offset: "point", "dashes?": { list: "number" } }, }, }, + "gradient?": { + fields: { + name: "string", + angle: "number", + centered: "boolean", + colors: { list: "number" }, + "tint?": "number", + }, + }, }, wipeout: { ...BASE, kind: { oneOf: ["wipeout"] }, points: { list: "point" } }, }; diff --git a/src/read/entities.ts b/src/read/entities.ts index d32f0df..c7326bf 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -13,6 +13,7 @@ import type { ReadArcLengthDimension, ReadEntity, ReadEntityBase, + ReadGradient, ReadHatchLoop, ReadImage, ReadPatternLine, @@ -21,7 +22,7 @@ import type { ReadPolyline, ReadTextPlacement, } from "./model.ts"; -import { dimensionTextParts } from "./model.ts"; +import { dimensionTextParts, gradientDegrees } from "./model.ts"; import { facing, first, @@ -73,9 +74,15 @@ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadE }; } -/** The group codes of the doubles an entity holds: its points, sizes, angles and direction. */ +/** + * The group codes of the doubles an entity holds: its points, sizes, angles and direction, and a + * hatch's gradient. + */ const isDouble = (code: number): boolean => - (code >= 10 && code <= 59) || (code >= 110 && code <= 149) || (code >= 210 && code <= 239); + (code >= 10 && code <= 59) || + (code >= 110 && code <= 149) || + (code >= 210 && code <= 239) || + (code >= 460 && code <= 469); /** True when a double of the record does not read as a finite number. */ export function brokenNumber(r: Rec): boolean { @@ -456,6 +463,11 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { }; } if (broken) return { malformed: "HATCH with a number that is not finite" }; + const gradient = hatchGradient(codes, values, i, face); + // A finite angle in radians can be past the doubles in degrees, and a tint in single + // precision, as readDWG counts them too. + if (gradient && !(Number.isFinite(gradient.angle) && Number.isFinite(gradient.tint ?? 0))) + return { malformed: "HATCH with a number past the doubles" }; return { entity: { ...base, @@ -466,10 +478,58 @@ function hatch(r: Rec, base: ReadEntityBase, face: Facing): Reading { ...(num(s, 71) === 1 && { associative: true as const }), loops, ...pattern, + ...(gradient && { gradient }), }, }; } +/** + * A hatch's gradient, from its group 450 on, after its loops: undefined where 450 is missing or 0. + * Seen from below, its angle is mirrored as a pattern line's is. + */ +function hatchGradient( + codes: readonly number[], + values: readonly string[], + from: number, + face: Facing, +): ReadGradient | undefined { + const at = codes.indexOf(450, from); + if (at < 0 || !(Number(values[at]) !== 0)) return undefined; + let [label, radians, shift, single, tint] = ["", 0, 0, 0, 0]; + const colors: number[] = []; + for (let k = at + 1; k < codes.length; k++) { + const value = values[k]!; + switch (codes[k]) { + case 460: + radians = Number(value) || 0; + break; + case 461: + shift = Number(value) || 0; + break; + case 452: + single = Number(value) || 0; + break; + case 462: + tint = Number(value) || 0; + break; + case 421: + if (colors.length < 2) colors.push((Number(value) || 0) & 0xffffff); + break; + case 470: + label = value; + break; + } + } + const angle = gradientDegrees(radians); + return { + name: label, + angle: face === -1 ? 180 - angle : angle, + centered: shift === 0, + colors, + ...(single === 1 && { tint: Math.fround(tint) }), + }; +} + /** * A wipeout: its clip, which the file holds in the axes of its picture of one pixel, in the * world's coordinates, a polygon without its first point again at its end, or a rectangle's four @@ -1172,6 +1232,7 @@ export function costOf(e: ReadEntity): number { let points = 0; for (const loop of e.loops) points += 1 + loop.points.length + (loop.bulges?.length ?? 0); for (const line of e.patternLines ?? []) points += 3 + (line.dashes?.length ?? 0); + if (e.gradient) points += 4 + e.gradient.colors.length + chars(e.gradient.name); return own + points + chars(e.pattern); } case "wipeout": diff --git a/src/read/model.ts b/src/read/model.ts index 250bcd8..ffc5615 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -730,8 +730,34 @@ export interface ReadHatch extends ReadEntityBase { * scaled. A firm's patterns can be read back from its drawings this way. */ readonly patternLines?: readonly ReadPatternLine[]; + /** Its gradient, groups 450 to 470. Left out when group 450 is 0. */ + readonly gradient?: ReadGradient; } +/** A hatch's gradient, as the file holds it. */ +export interface ReadGradient { + /** Group 470, such as `LINEAR`, a name tsdraft does not know included. */ + readonly name: string; + /** Group 460, in degrees counterclockwise. */ + readonly angle: number; + /** True when group 461 is 0. */ + readonly centered: boolean; + /** + * Group 421 of its first two colors, each `0xRRGGBB`. The leading CAD app plots the first two + * whatever the count, and from blue to white with fewer. + */ + readonly colors: readonly number[]; + /** Group 462, as single precision holds it, where group 452 says one color and its tint. */ + readonly tint?: number; +} + +/** + * A gradient's angle in degrees, with 12 significant digits, from its radians: a DXF holds them as + * written, and a DWG as the leading CAD app parsed them, which can differ in the last bit. + */ +export const gradientDegrees = (radians: number): number => + Number((radians * (180 / Math.PI)).toPrecision(12)); + /** A line of a hatch's pattern, as `ReadHatch.patternLines` holds it. */ export interface ReadPatternLine { readonly angle: number; diff --git a/src/rules.ts b/src/rules.ts index cabca9a..f4602bd 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -4,7 +4,7 @@ // // That app discards the whole drawing over most names that break the name rules. import type { XrefProblem } from "./blocks.ts"; -import type { DxfVersion, Point, Units } from "./drawing.ts"; +import type { DxfVersion, HatchGradient, Point, Rgb, Units } from "./drawing.ts"; import type { PaperUnit } from "./paper.ts"; import { paperInfo, PLOT_STYLE_TABLES, type Paper, type PlotStyleTable } from "./papers.ts"; import { @@ -1830,6 +1830,158 @@ export function hatchPatternChoiceProblem(value: unknown): string | undefined { return c.origin === undefined ? undefined : finitePointProblem(c.origin, "pattern's origin"); } +/** The gradients a hatch can have, by name. */ +export const GRADIENT_KINDS = [ + "linear", + "cylinder", + "inverted-cylinder", + "spherical", + "inverted-spherical", + "hemispherical", + "inverted-hemispherical", + "curved", + "inverted-curved", +] as const; + +const GRADIENT_CHOICE = + "gradient must be { name, angle?, centered?, colors } for two colors, or { name, angle?, centered?, color, tint } for one color and its tint"; +const GRADIENT_NAME = `gradient's name must be one of ${GRADIENT_KINDS.map((k) => `"${k}"`).join(", ")}`; +const GRADIENT_COLOR = + "a gradient's color must be [red, green, blue], each a whole number from 0 to 255"; +const GRADIENT_TINT = "a gradient's tint must be a number from 0, for black, to 1, for white"; +/** What is wrong with a hatch that has a pattern and a gradient. */ +export const GRADIENT_WITH_PATTERN = "a hatch has a pattern or a gradient, not both"; + +/** The fields a gradient may have. */ +const GRADIENT_KEYS = ["name", "angle", "centered", "colors", "color", "tint"] as const; + +/** + * A true color copied from `value`, each channel read once, or undefined where it is not three + * whole numbers from 0 to 255. + */ +export function rgbOf(value: unknown): Rgb | undefined { + if (!Array.isArray(value) || value.length !== 3) return undefined; + const rgb: [unknown, unknown, unknown] = [value[0], value[1], value[2]]; + for (const c of rgb) if (!Number.isInteger(c) || (c as number) < 0 || (c as number) > 255) return; + return rgb as unknown as Rgb; +} + +/** + * A hatch's gradient read once: what is wrong with it, or a copy of it in plain data. Each field + * and each channel is read once, so what is checked is what is kept. + */ +export function readGradient( + value: unknown, +): { readonly problem: string } | { readonly gradient: HatchGradient } { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return { problem: GRADIENT_CHOICE }; + } + for (const key of Object.keys(value)) { + if (!(GRADIENT_KEYS as readonly string[]).includes(key)) return { problem: GRADIENT_CHOICE }; + } + const { name, angle, centered, colors, color, tint } = value as Record; + if (!(GRADIENT_KINDS as readonly unknown[]).includes(name)) return { problem: GRADIENT_NAME }; + if (angle !== undefined) { + const problem = finiteAngleProblem(angle, "gradient's angle"); + if (problem) return { problem }; + } + if (centered !== undefined && typeof centered !== "boolean") { + return { problem: "gradient's centered must be true or false" }; + } + const base = { + name: name as HatchGradient["name"], + ...(angle === undefined ? {} : { angle: angle as number }), + ...(centered === undefined ? {} : { centered }), + }; + if (colors !== undefined) { + if (color !== undefined || tint !== undefined) return { problem: GRADIENT_CHOICE }; + if (!Array.isArray(colors) || colors.length !== 2) return { problem: GRADIENT_CHOICE }; + const [first, second] = [rgbOf(colors[0]), rgbOf(colors[1])]; + if (!first || !second) return { problem: GRADIENT_COLOR }; + return { gradient: { ...base, colors: [first, second] } }; + } + if (color === undefined || tint === undefined) return { problem: GRADIENT_CHOICE }; + const one = rgbOf(color); + if (!one) return { problem: GRADIENT_COLOR }; + if (!(typeof tint === "number" && tint >= 0 && tint <= 1)) return { problem: GRADIENT_TINT }; + return { gradient: { ...base, color: one, tint } }; +} + +/** Returns what is wrong with a hatch's gradient, or undefined. */ +export function hatchGradientProblem(value: unknown): string | undefined { + const read = readGradient(value); + return "problem" in read ? read.problem : undefined; +} + +/** True for a channel of a true color as a literal: a whole number from 0 to 255. */ +type Channel = number extends N ? true : N extends Enumerate<256> ? true : false; + +/** True for a true color whose literal channels are each a whole number from 0 to 255. */ +type ColorChecked = C extends readonly [ + infer R extends number, + infer G extends number, + infer B extends number, +] + ? [Channel, Channel, Channel] extends [true, true, true] + ? true + : false + : true; + +/** True for a tint whose literal is a number from 0 to 1. */ +type TintChecked = T extends number + ? number extends T + ? true + : `${T}` extends `-${string}` + ? false + : `${T}` extends "0" | "1" | `0.${string}` | `${string}e-${string}` + ? true + : false + : true; + +/** The fields of any member of `G` that a gradient does not have. */ +type UnknownKeys = G extends unknown ? Exclude : never; + +/** True for a member of an angle's literal of 1e100 or more, where the compiler prints a third exponent digit. */ +type LargeAngle = A extends number + ? `${A}` extends `${string}e+${Digit}${Digit}${Digit}` + ? true + : never + : never; + +/** True when no member of `G` has an angle of 1e100 or more. */ +type AngleChecked = [G extends { readonly angle?: infer A } ? LargeAngle : never] extends [ + never, +] + ? true + : false; + +type CheckedGradient = [UnknownKeys] extends [never] + ? AngleChecked extends true + ? CheckedColors + : typeof TOO_LARGE + : typeof GRADIENT_CHOICE; + +type CheckedColors = G extends { readonly colors: readonly [infer A, infer B] } + ? [ColorChecked, ColorChecked] extends [true, true] + ? G + : typeof GRADIENT_COLOR + : G extends { readonly color: infer C; readonly tint: infer T } + ? ColorChecked extends true + ? TintChecked extends true + ? G + : typeof GRADIENT_TINT + : typeof GRADIENT_COLOR + : G; + +/** + * Resolves to `G` when it is a hatch's gradient whose fields, angle, colors and tint are written as + * they may be, and to the error message otherwise. The false branch is never taken: it is there so that the + * compiler infers `G` from the literal. + */ +export type GradientOf = [G] extends [HatchGradient] + ? CheckedGradient + : G; + /** * Returns what is wrong with a hatch that names a pattern the drawing does not have. tsdraft has * none of its own, so the message says where a firm's come from. The rule depends on the drawing, diff --git a/src/shape.ts b/src/shape.ts index 38c34b0..89dd907 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -628,10 +628,10 @@ function shapes(all: boolean, typed = all): Shapes { transparent: ruled(boolean), }, ), - // A rule of `lint` reports the pattern, whatever its type. + // A rule of `lint` reports the pattern and the gradient, whatever their types. hatch: fields( { kind, layer: string, loops: list(record(loop)) }, - { ...shared, pattern: LEFT }, + { ...shared, pattern: LEFT, gradient: LEFT }, ), wipeout: fields({ kind, layer: string, points: list(point) }, shared), } satisfies Record; diff --git a/src/svg.ts b/src/svg.ts index 0e7ba8a..3d30149 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -1,5 +1,6 @@ import { blocksByKey, + compose, eachDrawn, mapPoint, referencedByKey, @@ -33,6 +34,9 @@ import { import { dimensionMask, drawnLoops, + gradientBoxer, + type GradientPicture, + gradientWritten, hatchLines, type HatchLines, hatchSpread, @@ -43,6 +47,7 @@ import { patternDrawnProblem, patternSizes, type PatternSizes, + writtenPoint, } from "./fills.ts"; import { patternPieces } from "./patterns.ts"; import { @@ -205,6 +210,22 @@ const VIRTUAL_PENS: readonly string[] = [ .join(" ") .split(" "); +/** + * The index nearest a true color, which a file holds beside it: index 7 counted as white, which + * the leading CAD app holds it as. The first of two as near. + */ +export function nearestColorIndex([r, g, b]: readonly [number, number, number]): number { + let best = 1; + let nearest = Infinity; + for (let i = 0; i < ACI.length; i++) { + const hex = i === 6 ? "ffffff" : ACI[i]!; + const [pr, pg, pb] = [0, 2, 4].map((k) => Number.parseInt(hex.slice(k, k + 2), 16)); + const distance = (pr! - r) ** 2 + (pg! - g) ** 2 + (pb! - b) ** 2; + if (distance < nearest) [best, nearest] = [i + 1, distance]; + } + return best; +} + /** * The color a plot style table plots an ACI index in, on paper, where index 7 is black. Under a * table that gives each pen a color of its own, an index outside 1 to 255 plots as 7 does. @@ -262,7 +283,7 @@ const JOINED = 1024; * The format of a picture of a layout, which `svgToPDF` reads: it goes up whenever an element or * an attribute of such a picture changes what it means. */ -export const SHEET_PICTURE = 1; +export const SHEET_PICTURE = 2; /** The mark of a line drawn as the thinnest the printer draws: a lineweight of 0, or a border. */ const THINNEST = ` data-thinnest=""`; @@ -571,6 +592,26 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const clipsChecked = new WeakMap(); const defs: string[] = []; let clips = 0; + let gradients = 0; + /** + * 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 frame = (matrix ? compose(matrix, picture.frame) : picture.frame).map(precise).join(" "); + const stops = picture.stops + .map(({ offset, color }) => ``) + .join(""); + const shape = + picture.kind === "linear" + ? `linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"` + : `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); + return id; + }; /** * The raster file of an image's path, read once for the picture, or null for none it draws. An * image of a referenced drawing, `from`, takes its file from that drawing's files alone. @@ -751,7 +792,9 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): if (sizes !== undefined) step(Math.floor(sizes.items / 16)); return sizes; }; - return hatchToSvg(e, mark, drawnPen, look, matrix, room, patternOf, placing, step); + return hatchToSvg(e, mark, drawnPen, look, matrix, room, patternOf, placing, step, (p) => + shade(p, matrix), + ); } if (e.kind === "wipeout") { const frame = (from?.drawing ?? drawing).wipeoutFrame !== false; @@ -1554,9 +1597,11 @@ function maskToSvg( } /** - * A hatch: its loops as one path, filled in its pen's color by the parity of the loops around each - * point, as the leading CAD app fills them, with no outline. Its arcs are drawn as `matrix` puts - * them, and it stops once it passes the room left in the picture. + * A hatch: its loops as one path, filled by the parity of the loops around each point, as the + * leading CAD app fills them, with no outline: in its pen's color, or with its gradient, which + * `shade` holds in the picture's definitions, in its own colors whatever the plot style table. Its + * arcs are drawn as `matrix` puts them, and it stops once it passes the room left in the picture. + * A gradient the rules refuse, or whose loops' box has no width or height, draws nothing. */ function hatchToSvg( e: Hatch, @@ -1568,6 +1613,7 @@ function hatchToSvg( patternOf: (name: string) => HatchPattern | undefined, sizesOf: (pattern: HatchPattern) => PatternSizes | undefined, step: (cost: number) => boolean, + shade: (picture: GradientPicture) => string | undefined, ): string { const spread = hatchSpread(e, patternOf, sizesOf); if (spread !== undefined) { @@ -1581,19 +1627,29 @@ function hatchToSvg( const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; return `${fmt(px)} ${fmt(py)}`; }; + const gradient = e.gradient === undefined ? undefined : gradientWritten(e.gradient); + if (e.gradient !== undefined && gradient === undefined) return ``; + const boxer = gradient && gradientBoxer(gradient); // Each loop is one string once made, and each side is paid for from the room, so that what the // hatch holds stays near what it writes: the loop that passes the room ends there. The loops are // added on, not joined, so that a path past the room is not copied before `write` refuses it. + // Each loop is paid for before the walk as an item that may draw nothing, since many hatches can + // share one list of loops, and the sides of a path that is not drawn where it is left out. + const loops = filled(e.loops); + step(loops.length); let d = ""; let left = room; - for (const loop of drawnLoops(e.loops)) { + let walked = 0; + for (const loop of drawnLoops(loops)) { if (left < 0) break; const sides = loopSides(loop); + walked += sides.length; if (sides.length === 0) continue; const parts = [`M ${place(...sides[0]!.from)}`]; let used = parts[0]!.length; for (const side of sides) { if (used > left) break; + boxer?.side(writtenPoint(side.from), writtenPoint(side.to), written(side.bulge)); const arc = sideArc(side.from, side.to, side.bulge); if (!arc) parts.push(`L ${place(...side.to)}`); else { @@ -1616,9 +1672,22 @@ function hatchToSvg( left -= path.length + 1; } if (d === "") return ``; + if (boxer) { + const picture = boxer.picture(); + const id = picture && shade(picture); + if (id === undefined) { + step(walked); + return ``; + } + return ``; + } return ``; } +/** A true color as `#rrggbb`. */ +const hex = (color: readonly number[]): string => + `#${color.map((c) => c.toString(16).padStart(2, "0")).join("")}`; + /** * A hatch's pattern: each dash and dot its lines draw inside its loops, as one path in its pen, * a dot as a piece of no length, which the plot's round ends draw. It stops once it passes the diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 23634a6..0e7c9ef 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2659,3 +2659,144 @@ test("a long paragraph value many places share is laid out once in each of its s const [paid] = within(1000, () => inspectWithin(wrapped, {}, words.length + 1000)); assert.match(paid!.message, /stopped short at entity #1 of model space/); }); + +test("gradients that many hatches share, and a gradient of many fields, are checked and drawn in a bounded time", () => { + const loops = [ + { + points: [ + [0, 0], + [10, 0], + [10, 5], + ] as Point[], + }, + ]; + // One gradient of many fields, which lint reads once however many hatches give it. + const crowded: Record = { name: "linear", color: [1, 2, 3], tint: 0.5 }; + for (let k = 0; k < 100_000; k++) crowded[`f${k}`] = k; + const shared = { + name: "spherical", + centered: false, + colors: [ + [1, 2, 3], + [4, 5, 6], + ], + }; + const drawing: Drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: Array.from({ length: 20_000 }, (_, k) => ({ + kind: "hatch", + layer: "0", + loops, + gradient: (k % 2 === 0 ? crowded : shared) as never, + })), + }; + const found = within(3000, () => lint(drawing)); + assert.equal(found.filter((d) => d.rule === "hatch-gradient").length, 10_000); + const drawn = settled(3000, () => svgWithin(drawing, {}, 50_000)); + assert.ok(typeof drawn === "string" || drawn instanceof RangeError, String(drawn)); +}); + +test("a gradient that draws nothing pays for the sides it walked, and a gradient whose fields change as they are read is read once", () => { + // A long flat loop, whose box has no height, that many hatches of a sheet share. + const flat = [{ points: Array.from({ length: 10_000 }, (_, k): Point => [k, 0]) }]; + const gradient = { name: "linear", color: [1, 2, 3], tint: 0.5 } as const; + const sheet: Drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [], + layouts: [ + { + name: "S", + paper: "ANSI B", + viewports: [], + entities: Array.from({ length: 25 }, () => ({ + kind: "hatch" as const, + layer: "0", + loops: flat, + gradient, + })), + }, + ], + }; + assert.ok(settled(3000, () => svgWithin(sheet, { layout: "S" }, 5000)) instanceof RangeError); + // As many empty loops, which draw nothing, are paid for too. + const empty = Array.from({ length: 10_000 }, () => ({ points: [] as Point[] })); + const hollow: Drawing = { + ...sheet, + layouts: [ + { + ...sheet.layouts![0]!, + entities: sheet.layouts![0]!.entities.map((h) => ({ ...h, loops: empty })), + }, + ], + }; + assert.ok(settled(3000, () => svgWithin(hollow, { layout: "S" }, 5000)) instanceof RangeError); + // Colors that are two colors the first three times they are read, and nothing after. + let reads = 0; + const changing = new Proxy( + { name: "linear" }, + { + get: (target, key, receiver) => + key === "colors" + ? reads++ < 3 + ? [ + [1, 2, 3], + [4, 5, 6], + ] + : undefined + : Reflect.get(target, key, receiver), + ownKeys: () => ["name", "colors"], + getOwnPropertyDescriptor: () => ({ enumerable: true, configurable: true }), + }, + ); + const drawing: Drawing = { + ...sheet, + layouts: [], + entities: [ + { + kind: "hatch", + layer: "0", + loops: [ + { + points: [ + [0, 0], + [1, 0], + [1, 1], + ], + }, + ], + gradient: changing as never, + }, + ], + }; + assert.deepEqual( + within(1000, () => lint(drawing)), + [], + ); + const drawn = settled(1000, () => toSVG(drawing)); + assert.ok(typeof drawn === "string", String(drawn)); + // The builder keeps the copy it checked. + reads = 0; + const built = createDrawing({ units: "in" }) + .hatch( + [ + [0, 0], + [1, 0], + [1, 1], + ], + { gradient: changing as never }, + ) + .build(); + assert.deepEqual((built.entities[0] as Extract).gradient, { + name: "linear", + colors: [ + [1, 2, 3], + [4, 5, 6], + ], + }); +}); diff --git a/test/gradients.test.ts b/test/gradients.test.ts new file mode 100644 index 0000000..c261fe5 --- /dev/null +++ b/test/gradients.test.ts @@ -0,0 +1,58 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { createDrawing, readDXF, tintColor, toDXF, type Point } from "../src/index.ts"; + +const triangle: Point[] = [ + [0, 0], + [1, 0], + [1, 1], +]; + +test("a gradient is written as CAD programs hold it, black as 0,0,1, and read back", async () => { + const d = createDrawing({ units: "in" }); + d.hatch(triangle, { + gradient: { + name: "inverted-spherical", + angle: 30, + centered: false, + colors: [ + [0, 0, 0], + [255, 255, 255], + ], + }, + }); + d.hatch(triangle, { gradient: { name: "cylinder", color: [255, 0, 0], tint: 0.25 } }); + const dxf = toDXF(d.build()); + const groups = (n: number) => { + let at = -1; + for (let k = 0; k <= n; k++) at = dxf.indexOf("\r\n450\r\n", at + 1); + const end = dxf.indexOf("\r\n", dxf.indexOf("\r\n470\r\n", at) + 7); + return dxf.slice(at + 2, end).split("\r\n"); + }; + // After the seed point: whether a gradient, its angle in radians, its shift, one color or two, + // the tint, then each color's index and true color, then its name. + assert.deepEqual( + groups(0), + ["450", "1", "451", "0", "460", "0.523598775598299", "461", "1", "452", "0", "462", "1"] + .concat(["453", "2", "463", "0", "63", "178", "421", "1"]) + .concat(["463", "1", "63", "7", "421", "16777215", "470", "INVSPHERICAL"]), + ); + // One color and its tint: the second color is the first with its lightness set to the tint. + assert.deepEqual( + groups(1).filter((_, k, all) => ["452", "462", "421"].includes(all[k - 1] ?? "")), + ["1", "0.25", String(0xff0000), String(0x800000)], + ); + const read = await readDXF(dxf, { geometry: true }); + assert.deepEqual( + read.model.entities!.map((e) => (e.kind === "hatch" ? e.gradient : undefined)), + [ + { name: "INVSPHERICAL", angle: 30, centered: false, colors: [1, 0xffffff] }, + { name: "CYLINDER", angle: 0, centered: true, colors: [0xff0000, 0x800000], tint: 0.25 }, + ], + ); +}); + +test("a tint's second color is the color with its lightness set to the tint, as CAD programs store it", () => { + assert.deepEqual(tintColor([255, 0, 0], 0.25), [128, 0, 0]); + assert.deepEqual(tintColor([30, 120, 200], 0.5), [33, 134, 222]); +}); diff --git a/test/pdf.test.ts b/test/pdf.test.ts index 7109e2d..d988bc3 100644 --- a/test/pdf.test.ts +++ b/test/pdf.test.ts @@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"; import { test } from "node:test"; import { deflateSync, inflateSync } from "node:zlib"; import { createDrawing, pdfFace, svgToPDF, toPDF, toSVG } from "../src/index.ts"; +import { GRADIENT_STOPS } from "../src/fills.ts"; import { readTrueType, type TrueType } from "../src/truetype.ts"; import exampleSheet from "../examples/site-plan.ts"; import set, { xrefs } from "../examples/plan-set/set.ts"; @@ -66,7 +67,7 @@ test("svgToPDF refuses what toSVG does not draw of a layout", () => { const d = createDrawing().line([0, 0], [1, 1]).build(); assert.throws( () => svgToPDF([toSVG(d)]), - /a picture of format null, where this copy of tsdraft reads format 1/, + /a picture of format null, where this copy of tsdraft reads format 2/, ); assert.throws(() => svgToPDF([]), RangeError); const sheet = toSVG(exampleSheet, { layout: exampleSheet.layouts![0]!.name }); @@ -83,6 +84,64 @@ test("svgToPDF refuses what toSVG does not draw of a layout", () => { } }); +test("a gradient is a shading painted inside its loops, and a gradient toSVG does not draw is refused", () => { + const d = createDrawing({ units: "in" }); + d.layout("G", { paper: "ANSI B" }, () => + d.hatch( + [ + [1, 1], + [5, 1], + [5, 3], + [1, 3], + ], + { + gradient: { + name: "spherical", + colors: [ + [0, 0, 255], + [255, 255, 0], + ], + }, + }, + ), + ); + const drawing = d.build(); + const pdf = latin1(toPDF(drawing)); + holdsTogether(pdf); + assert.match( + pdf, + /\/ShadingType 3 \/ColorSpace \/DeviceRGB \/Coords \[0 0 0 0 0 1\] \/Function << \/FunctionType 3/, + ); + assert.match(pdf, /h\nW\* n\n[-\d. ]+ cm\n\/Sh1 sh\nQ/); + const sheet = toSVG(drawing, { layout: "G" }); + const path = /]*data-gradient=""\/>/.exec(sheet)![0]; + // Stops from 0 to 1, as many as toSVG writes at most, and one more. + const stops = (n: number) => + sheet.replace( + /(]*>).*?(<\/radialGradient>)/, + `$1${Array.from({ length: n }, (_, k) => ``).join("")}$2`, + ); + svgToPDF([stops(GRADIENT_STOPS)]); + for (const changed of [ + sheet.replace('spreadMethod="pad"', 'spreadMethod="reflect"'), + sheet.replace(']*>).*?(<\/radialGradient>)/, + `$1${[0, 0.5, 0.5000000001, 1].map((k) => ``).join("")}$2`, + ), + stops(GRADIENT_STOPS + 1), + ]) { + assert.throws(() => svgToPDF([changed]), RangeError); + } + // A gradient that many paths fill with is one shading. + const many = latin1(svgToPDF([sheet.replace(path, path.repeat(50))])); + assert.equal(many.match(/\/ShadingType/g)?.length, 1); + assert.equal(many.match(/\/Sh1 sh/g)?.length, 50); +}); + test("a page sets the thinnest pen 0 wide, turns ARCH E as the plotter holds it, and says what it lacks", () => { const d = createDrawing({ units: "in" }); d.textStyle({ name: "NOTE", font: "Arial" }); diff --git a/test/read.test.ts b/test/read.test.ts index a464c1f..6075253 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -1217,3 +1217,40 @@ test("a definition of paragraph text pays for its style's name against the block assert.equal(block.attributeDefinitions.length, 0); assert.equal(block.other["past the limit"], 1); }); + +test("a gradient whose angle or tint is past the doubles once read is counted, not read as Infinity", async () => { + const d = createDrawing({ units: "in" }); + d.hatch( + [ + [0, 0], + [1, 0], + [1, 1], + ], + { + gradient: { + name: "linear", + colors: [ + [0, 0, 255], + [255, 255, 0], + ], + }, + }, + ); + d.hatch( + [ + [2, 0], + [3, 0], + [3, 1], + ], + { gradient: { name: "linear", color: [0, 0, 255], tint: 0.5 } }, + ); + const dxf = toDXF(d.build()); + // The first's angle in radians, past the doubles in degrees, and the second's tint, past + // single precision. + const bent = dxf + .replace(/\r\n460\r\n[^\r]*\r\n/, "\r\n460\r\n1e307\r\n") + .replace(/\r\n462\r\n0\.5\r\n/, "\r\n462\r\n1e39\r\n"); + assert.ok(bent.includes("\r\n460\r\n1e307\r\n") && bent.includes("\r\n462\r\n1e39\r\n")); + const read = await readDXF(bent, { geometry: true }); + assert.deepEqual(plain(read.unread.malformed), { "HATCH with a number past the doubles": 2 }); +}); diff --git a/test/rules.test.ts b/test/rules.test.ts index b3f80f6..7e16789 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -1573,3 +1573,193 @@ test("an attribute of paragraph text and each insert's value of it are checked a // An insert that scales its block so unevenly that its width factor leaves the range is refused. assert.throws(() => d.insert("NOTE", [0, 0], { scale: [1000, 0.001] }), /times as wide/); }); + +test("a hatch's gradient is checked by the builder and by lint", () => { + const box: Point[] = [ + [0, 0], + [8, 0], + [8, 4], + [0, 4], + ]; + const d = createDrawing({ units: "in" }); + d.hatch(box, { + gradient: { + name: "linear", + angle: 30, + colors: [ + [200, 40, 30], + [20, 90, 180], + ], + }, + }); + d.hatch(box, { + gradient: { name: "inverted-spherical", centered: false, color: [0, 0, 0], tint: 0.5 }, + }); + const built = d.build(); + assert.deepEqual(built.entities[1], { + kind: "hatch", + layer: "0", + loops: [{ points: box }], + gradient: { name: "inverted-spherical", centered: false, color: [0, 0, 0], tint: 0.5 }, + }); + assert.deepEqual(lint(built), []); + assert.deepEqual(fromJSON(toJSON(built)), built); + + const shaded = (gradient: unknown, pattern?: unknown): Drawing => ({ + ...built, + entities: [ + { + kind: "hatch", + layer: "0", + loops: [{ points: box }], + gradient: gradient as never, + ...(pattern ? { pattern: pattern as never } : {}), + }, + ], + }); + const both = (gradient: unknown, expected: RegExp) => { + assert.throws(() => d.hatch(box, { gradient: gradient as never }), expected); + const found = lint(shaded(gradient)).map((x) => `${x.rule}: ${x.message}`); + assert.equal(found.length, 1, found.join("\n")); + assert.match(found[0]!, /^hatch-gradient: hatch #0: /); + assert.match(found[0]!, expected); + }; + both( + { + name: "radial", + colors: [ + [0, 0, 0], + [1, 1, 1], + ], + }, + /name must be one of "linear"/, + ); + both( + { + name: "linear", + colors: [ + [0, 0, 256], + [1, 1, 1], + ], + }, + /whole number from 0 to 255/, + ); + both( + { + name: "linear", + colors: [ + [0, 0.5, 0], + [1, 1, 1], + ], + }, + /whole number from 0 to 255/, + ); + both({ name: "linear", color: [0, 0, 0], tint: 1.5 }, /tint must be a number from 0/); + both({ name: "linear", color: [0, 0, 0] }, /radient must be \{ name/); + both( + { + name: "linear", + colors: [ + [0, 0, 0], + [1, 1, 1], + ], + tint: 0.5, + }, + /radient must be \{ name/, + ); + both({ name: "linear", angle: NaN, color: [0, 0, 0], tint: 0 }, /angle must be a finite number/); + both( + { name: "linear", centered: 1, color: [0, 0, 0], tint: 0 }, + /centered must be true or false/, + ); + const found = lint(shaded({ name: "linear", color: [0, 0, 0], tint: 0 }, { spacing: 1 })); + assert.deepEqual( + found.map((x) => x.rule), + ["hatch-gradient"], + ); + // The literal mistakes are compile errors too. + assert.throws( + () => + d.hatch(box, { + // @ts-expect-error: a channel is a whole number from 0 to 255. + gradient: { + name: "linear", + colors: [ + [0, 0, 300], + [0, 0, 0], + ], + }, + }), + /0 to 255/, + ); + assert.throws( + () => + d.hatch(box, { + // @ts-expect-error: and a tint from 0 to 1. + gradient: { name: "linear", color: [0, 0, 0], tint: 2 }, + }), + /tint/, + ); + assert.throws( + () => + d.hatch(box, { + gradient: { name: "linear", color: [0, 0, 0], tint: 0 }, + // @ts-expect-error: a gradient never goes with a pattern. + pattern: { spacing: 1 }, + }), + /not both/, + ); + assert.throws( + () => + d.hatch(box, { + // @ts-expect-error: and is one of nine. + gradient: { name: "radial", color: [0, 0, 0], tint: 0 }, + }), + /one of/, + ); + assert.throws( + () => + d.hatch(box, { + // @ts-expect-error: a field it does not know. + gradient: { name: "linear", color: [0, 0, 0], tint: 1, tnit: 0 }, + }), + /radient must be \{ name/, + ); + assert.throws( + () => + d.hatch(box, { + // @ts-expect-error: an angle of 1e100 or more. + gradient: { name: "linear", angle: 1e100, color: [0, 0, 0], tint: 1 }, + }), + /angle: .*1e100/, + ); + // A member of a union is checked as a literal is. + const large = (huge: boolean) => (huge ? 1e100 : 0); + assert.throws( + () => + d.hatch(box, { + // @ts-expect-error: one member's angle is 1e100. + gradient: { name: "linear", angle: large(true) as 0 | 1e100, color: [0, 0, 0], tint: 1 }, + }), + /angle: .*1e100/, + ); + const either = (odd: boolean) => + odd + ? ({ name: "linear", color: [0, 0, 0], tint: 1, tnit: 0 } as const) + : ({ name: "linear", color: [0, 0, 0], tint: 1 } as const); + assert.throws( + () => + d.hatch(box, { + // @ts-expect-error: one member has a field a gradient does not. + gradient: either(true), + }), + /radient must be \{ name/, + ); + assert.throws( + () => + createDrawing({ dxf: "R12" }).hatch(box, { + gradient: { name: "linear", color: [0, 0, 0], tint: 0 }, + } as never), + /R2018/, + ); +}); diff --git a/test/shape.test.ts b/test/shape.test.ts index 39619d8..c33851a 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -22,6 +22,7 @@ import { type Layer, type Layout, type LeaderStyle, + type Hatch, type HatchPattern, type Linetype, type PatternLine, @@ -39,14 +40,16 @@ const justified = { style: "NOTES", align: "center", valign: "middle" } as const /** * Each kind of entity with every field it can have: a field left out is a compile error. A * polyline has a width or widths for each side, and `wide` has the other. A leader has a note, - * and `keyed` a block in its place. + * and `keyed` a block in its place. A hatch has a pattern, and `shaded` and `tinted` a gradient. */ const kinds: { readonly [K in Entity["kind"]]: K extends "polyline" ? Required> : K extends "leader" ? Required> - : Required>; + : K extends "hatch" + ? Required> + : Required>; } = { line: { kind: "line", layer: "WALL", from: [0, 0], to: [10, 0], id: "a", ...styled }, polyline: { @@ -289,6 +292,40 @@ const wide: Required> = { ...styled, }; +/** A hatch with a gradient of two colors, with every field the hatch of `kinds` leaves out. */ +const shaded: Required> = { + kind: "hatch", + layer: "0", + loops: kinds.hatch.loops, + gradient: { + name: "spherical", + angle: 30, + centered: false, + colors: [ + [200, 40, 30], + [20, 90, 180], + ], + }, + id: "w3", + ...styled, +}; + +/** A hatch with a gradient of one color and its tint. */ +const tinted: Required> = { + kind: "hatch", + layer: "0", + loops: kinds.hatch.loops, + gradient: { + name: "inverted-curved", + angle: 200, + centered: true, + color: [30, 120, 200], + tint: 0.4, + }, + id: "w4", + ...styled, +}; + const keyed: Required< Omit< Leader, @@ -501,6 +538,8 @@ const full: Required & { { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }, wide, keyed, + shaded, + tinted, ], layouts: [ { From 03188e499479802d06591c0251fc8aaa5528cc80 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Fri, 20 Nov 2026 23:43:42 -0500 Subject: [PATCH 18/35] An attribute's text starts where CAD programs start it, and the checks hold it there An attribute of paragraph text, and its definition, also hold the text it would be as one line, with no value. CAD programs keep that text where a text of no value starts. The new `attributeTextStart(definition, style, placed?)` gives that point as the R2018 DXF writes it: with 15 significant digits, and under 1e100. The DXF writer now uses it, and `docs/blocks.md` describes it. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 5 +++-- docs/blocks.md | 6 ++++++ src/blocks.ts | 29 ++++++++++++++++++++++++++++- src/dxf-r2018.ts | 16 ++++------------ src/format.ts | 11 +++++++++++ src/index.ts | 1 + test/paragraphs.test.ts | 34 ++++++++++++++++++++++++++++++++++ test/read-agreement.ts | 23 ++++++++++++++++------- 8 files changed, 103 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b92456..0cbc5b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,8 +51,9 @@ programs' own insert does: at its height in the insert, wrapped at the width times the same share, and, where the insert scales its block unevenly, with its characters widened by a code of the attribute's width factor before its value, in place of the style's. `placeAttribute` - gives that paragraph in `paragraph`, and `attributeParagraph` the `Paragraph` drawn. The R2018 - DXF writes it, `readDXF` reads it back as `ReadAttributeParagraph`, and `toSVG`, `toPDF`, + gives that paragraph in `paragraph`, `attributeParagraph` the `Paragraph` drawn, and + `attributeTextStart` where the attribute's text of no value starts, which CAD programs hold + with it and keep from a DXF. The R2018 DXF writes it, `readDXF` reads it back as `ReadAttributeParagraph`, and `toSVG`, `toPDF`, `inspectText`, the extents and `lint` lay it out where CAD programs plot it. `lint` and the builder refuse a width, a line spacing or a style of paragraph text on a definition of one line, and R12 holds no blocks. diff --git a/docs/blocks.md b/docs/blocks.md index bcf12e1..b3b8d85 100644 --- a/docs/blocks.md +++ b/docs/blocks.md @@ -103,6 +103,12 @@ style's width factor. It keeps the style's oblique angle, and slants no letter b `Paragraph` drawn, which `toSVG`, `toPDF`, `inspectText` and the extents lay out as a paragraph where the insert holds it. +Each attribute of paragraph text, and its definition, also holds the text it would be as one line, +with no value. CAD programs keep that text where a text of no value starts: the height below the +attribute's point at the top, half of it in the middle, and the font's descent above it at the +bottom. `attributeTextStart(definition, style, placed)` gives that point as the DXF writes it, +with 15 significant digits, for an insert's attribute or, without `placed`, for the definition. + ## Inserting a block `d.insert(block, at, options)` places a block with its base point at `at`, on the current diff --git a/src/blocks.ts b/src/blocks.ts index e14b42c..e9050bd 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -15,7 +15,9 @@ import type { } from "./drawing.ts"; import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; -import { written } from "./format.ts"; +import { STANDARD_FONT } from "./fonts.ts"; +import { readableFifteenDigits, written } from "./format.ts"; +import { layoutText } from "./measure.ts"; import { attributeTagProblem, blockNameProblem, @@ -338,6 +340,31 @@ export function attributeParagraph(placed: PlacedAttribute): Paragraph | undefin return paragraph as unknown as Paragraph; } +/** + * Where the text of a definition of paragraph text starts, or with `placed` the text of an + * insert's attribute of one, in the coordinates `placeAttribute` gives, as the writers write it: + * with 15 significant digits, and under 1e100, which the leading CAD app reads. That app holds + * the text where a text of no value starts, worked out from the attribute's point as written, + * and keeps that point from a DXF: the height below the point at the top, half of it in the + * middle, and the font's descent above it at the bottom. + * + * @param style - The definition's text style, unless it is `Standard`. + */ +export function attributeTextStart( + definition: ParagraphAttributeDefinition, + style: TextStyle | undefined, + placed?: PlacedAttribute, +): Point { + const at = placed?.at ?? definition.at; + const height = written(placed?.height ?? definition.height); + const turn = written(placed?.rotation ?? definition.rotation) / (180 / Math.PI); + const valign = definition.valign ?? "top"; + const up = layoutText({ value: "", height, font: style?.font ?? STANDARD_FONT, valign }).baseline; + // Each part of the sum is under 1e100, but the sum need not be. + const held = (n: number): number => Number(readableFifteenDigits(n)); + return [held(written(at[0]) - up * Math.sin(turn)), held(written(at[1]) + up * Math.cos(turn))]; +} + /** The fields of a paragraph that a definition of paragraph text gives the one an insert draws. */ const PARAGRAPH_FIELDS = [ "layer", diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 5d9b418..a4d2465 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -1,4 +1,5 @@ import { + attributeTextStart, definitionHandle, insertAttributeHandle, insertEndHandle, @@ -109,11 +110,10 @@ import { PLOTTER, type PaperInfo, } from "./papers.ts"; -import { fontInfo, STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; +import { fontInfo, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { ID_HANDLE_SEED, validIdHandle } from "./handles.ts"; import { dxfOnce, dxfText, fifteenDigits, fmt, readable, written, writtenAngle } from "./format.ts"; import { layerKey, layerZeroFirst } from "./layers.ts"; -import { layoutText } from "./measure.ts"; import { layoutParagraph, lineSpacingStyleCode, @@ -1149,16 +1149,8 @@ function writeParagraphAttribute( const height = placed?.height ?? definition.height; const rotation = placed?.rotation ?? definition.rotation; const valign = TEXT_VALIGN_OF[definition.valign ?? "top"]; - // The leading CAD app holds the text where a text of no value starts, worked out from its point - // as written, and keeps that point from a DXF: the height below it at the top, half of it in the - // middle, and the font's descent above it at the bottom. - const font = style?.font ?? STANDARD_FONT; - const up = layoutText({ value: "", height: written(height), font, valign }).baseline; - const turn = written(rotation) / (180 / Math.PI); - const start = [ - fifteenDigits(written(at[0]) - up * Math.sin(turn)), - fifteenDigits(written(at[1]) + up * Math.cos(turn)), - ] as const; + const [sx, sy] = attributeTextStart(definition, style, placed); + const start = [fifteenDigits(sx), fifteenDigits(sy)] as const; writeTextFields( g, { at, height, value: "", rotation, align: definition.align ?? "left", valign }, diff --git a/src/format.ts b/src/format.ts index 8ac5d71..a94191b 100644 --- a/src/format.ts +++ b/src/format.ts @@ -41,6 +41,17 @@ const TOO_LARGE = 1e100; /** The largest number under `TOO_LARGE`. */ const LARGEST = 9.999999999999998e99; +/** The largest number of 15 digits under `TOO_LARGE`, which `fifteenDigits` keeps under it. */ +const LARGEST_FIFTEEN_DIGITS = 9.99999999999999e99; + +/** + * A number a writer works out for itself as `fifteenDigits` writes it, brought into the range the + * leading CAD app reads as `readable` brings one. + */ +export function readableFifteenDigits(value: number): string { + return fifteenDigits(Math.max(-LARGEST_FIFTEEN_DIGITS, Math.min(LARGEST_FIFTEEN_DIGITS, value))); +} + /** * True for a number the leading CAD app would misread from DXF, because it is 1e100 or * more in size. `lint` refuses these wherever a drawing holds one. diff --git a/src/index.ts b/src/index.ts index e39e1a0..847f9a2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ export { attributeParagraph, + attributeTextStart, attributeDefinitionHandle, attributeHandle, attributesEndHandle, diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index ae96844..b2369bd 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -740,6 +740,24 @@ test("a paragraph is placed in the direction the DXF holds: its rotation within assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); }); +test("an attribute's text starts under 1e100 when its point and height together reach it", () => { + for (const [at, rotation] of [ + [[0, -9e99], 0], + [[9e99, 0], 90], + ] as const) { + const d = createDrawing({ units: "in" }); + d.block("B", {}, () => + d.attribute("N", at, { kind: "paragraph", value: "A", width: 10, height: 9e99, rotation }), + ); + d.insert("B", [0, 0]); + const numbers = toDXF(d.build()).split("\r\n").map(Number).filter(Number.isFinite); + assert.ok( + numbers.every((n) => Math.abs(n) < 1e100), + String(rotation), + ); + } +}); + test("an attribute of paragraph text is written and read as the leading CAD app's -INSERT makes it", async () => { const d = createDrawing({ units: "in" }); d.textStyle({ name: "NOTES", font: "Arial", widthFactor: 0.8 }); @@ -789,6 +807,22 @@ test("an attribute of paragraph text is written and read as the leading CAD app' assert.equal(mirrored?.value, "ALL WORK SHALL COMPLY\\PWITH THE CODES"); }); +test("a read of an attribute of paragraph text is held to where its text starts", async () => { + const d = createDrawing({ units: "in" }); + d.block("B", {}, () => d.attribute("N", [1, 2], { kind: "paragraph", value: "A", height: 0.25 })); + d.insert("B", [10, 5]); + const drawing = d.build(); + const dxf = toDXF(drawing); + // The height below the attribute's point, at 11, 7. + const start = "\r\n10\r\n11\r\n20\r\n6.75\r\n"; + assert.equal(dxf.split(start).length, 2); + assert.deepEqual(readProblems(drawing, await readDXF(dxf, { geometry: true }), "tsdraft"), []); + const moved = dxf.replace(start, "\r\n10\r\n11\r\n20\r\n123\r\n"); + assert.deepEqual(readProblems(drawing, await readDXF(moved, { geometry: true }), "tsdraft"), [ + "model space insert #0 attribute N: starts at 11,123, expected 11,6.75", + ]); +}); + test("a run and a text in a TrueType font are plotted from their first point at their advances", () => { const d = createDrawing({ units: "in" }); d.textStyle({ name: "NOTES", font: "Arial" }); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index ce43c4a..90b3b26 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -4,7 +4,7 @@ // written. The other reader's read is of a DXF that the leading CAD app wrote of the same drawing, // held to the doubles that app holds, within the rounding of 6 decimals for what it works out // again, and each text to what its DXF reader makes of the text it wrote. -import { placeAttribute } from "../src/blocks.ts"; +import { attributeTextStart, placeAttribute } from "../src/blocks.ts"; import { dimensionAngle, arcLengthArc, @@ -105,8 +105,8 @@ export function readProblems( readonly widthFactor: number; readonly obliqueAngle: number; readonly mirrored: boolean; - /** True for the text of an attribute of paragraph text, whose file holds where it starts. */ - readonly paragraph?: boolean; + /** For the text of an attribute of paragraph text, where its file holds that it starts. */ + readonly start?: Point; }, label: string, ): void => { @@ -121,9 +121,12 @@ export function readProblems( const at = justified ? got.alignAt : got.at; if (!nearPoint(at, want.at)) say(`${label}: placed at ${at}, expected ${want.at}`); if (!justified && got.startFrom !== "file") say(`${label}: starts from ${got.startFrom}`); - if (justified && by === "tsdraft" && got.startFrom === "file" && !want.paragraph) { + if (justified && by === "tsdraft" && got.startFrom === "file" && !want.start) { say(`${label}: starts from the file, which holds its alignment point there`); } + if (want.start && !nearPoint(got.stored, want.start)) { + say(`${label}: starts at ${got.stored}, expected ${want.start}`); + } if (!near(got.height, want.height)) say(`${label}: height ${got.height}, expected ${want.height}`); if (!nearAngle(got.rotation, want.rotation)) { @@ -177,7 +180,7 @@ export function readProblems( say(`${label}: reads ${JSON.stringify(got.value)}`); if (!sameName(got.layer, definition.layer)) say(`${label}: on layer ${got.layer}`); // The file holds a mirrored insert's attribute seen from below, which mirrors X. - const at: Point = placed.mirrored ? [-placed.at[0], placed.at[1]] : placed.at; + const at = mirroredBack(placed.at, placed.mirrored); const uneven = placed.paragraph?.uneven ?? true; placement( got, @@ -189,7 +192,9 @@ export function readProblems( widthFactor: uneven ? written(placed.widthFactor) : 1, obliqueAngle: uneven ? written(placed.obliqueAngle) : 0, mirrored: placed.mirrored, - paragraph: placed.paragraph !== undefined, + ...(definition.kind === "paragraph" && { + start: mirroredBack(attributeTextStart(definition, style, placed), placed.mirrored), + }), }, label, ); @@ -208,6 +213,8 @@ export function readProblems( start(got, mine, got.value, label); }; + const mirroredBack = (p: Point, mirrored: boolean): Point => (mirrored ? [-p[0], p[1]] : p); + /** A paragraph's value as a reader holds it: a DWG keeps a `\U+XXXX` as written. */ const paragraphValue = (got: string, want: string): boolean => got === once(want) || got === want; @@ -736,7 +743,9 @@ export function readProblems( widthFactor: paragraph ? 1 : written(style?.widthFactor ?? 1), obliqueAngle: paragraph ? 0 : written(style?.obliqueAngle ?? 0), mirrored: false, - paragraph, + ...(definition.kind === "paragraph" && { + start: attributeTextStart(definition, style), + }), }, label, ); From e61481ff2cb28873b7d880b54df4264ffbe9dbb4 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 03:19:51 -0500 Subject: [PATCH 19/35] Ellipses and splines: written, read and plotted as CAD programs draw them Ellipses and splines, in R2018 drawings. - `d.ellipse(center, majorAxis, ratio)` draws an ellipse, or an arc of one with `startParameter` and `endParameter`, in degrees. A parameter is not the angle a point lies at from the center, except at multiples of 90 degrees; the type's doc comment says how they differ. - `d.spline(fitPoints)` draws the cubic that CAD programs fit through the points. It takes `startTangent`, `endTangent` or `closed`. A free end does not bend, a tangent is a direction, and a closed spline joins smoothly where it closes. - `d.controlSpline(controlPoints)` draws a B-spline of any `degree` from 1 to 11. Its `knots` default to clamped uniform ones, or periodic ones when it is `closed`, and it takes `weights` for a rational spline. - `toDXF` writes each kind the way CAD programs save it. A spline through fit points is written with the knots and control points `fitSpline` gives, and a spline by control points is written clamped. - `toSVG` and `toPDF` draw both kinds, with dashes along the whole curve: an open curve is dashed as a line is, and a closed one as a circle is. - The extents hold the curve itself, not its control points. - `readDXF` reads both kinds, including an ellipse mirrored in another program. - `lint` and the builder refuse a drawing whose curves CAD programs cannot open: a ratio outside 0 to 1, an axis of no length, one parameter without the other, fewer than 2 fit points, a degree out of range, or knots of the wrong count. - `ellipsePoint`, `ellipseBox`, `splinePoint`, `splineBox`, `fitSpline` and `clamped` give the geometry. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 14 + GUIDE.md | 7 +- README.md | 15 + docs/assets/plan-set-A-101-dark.svg | 2 +- docs/assets/plan-set-A-101-light.svg | 2 +- docs/assets/plan-set-A-201-dark.svg | 2 +- docs/assets/plan-set-A-201-light.svg | 2 +- docs/assets/site-plan-dark.svg | 47 ++- docs/assets/site-plan-light.svg | 47 ++- docs/curves.md | 157 ++++++++ docs/format.md | 8 + docs/plotting.md | 5 +- docs/reading.md | 13 + docs/rules.md | 10 + examples/site-plan.ts | 22 ++ scripts/readme-drawing.ts | 1 + src/curves.ts | 555 +++++++++++++++++++++++++++ src/drawing.ts | 317 +++++++++++++++ src/dxf-r2018.ts | 111 +++++- src/extents.ts | 43 +++ src/format.ts | 11 + src/index.ts | 31 ++ src/leaders.ts | 28 +- src/lint.ts | 48 ++- src/pdf.ts | 7 +- src/read/check.ts | 24 ++ src/read/dxf.ts | 2 + src/read/entities.ts | 125 ++++++ src/read/model.ts | 43 +++ src/rules.ts | 535 +++++++++++++++++++++++++- src/shape.ts | 27 ++ src/svg.ts | 232 ++++++++++- test/bounded.test.ts | 151 ++++++++ test/curves.test.ts | 337 ++++++++++++++++ test/format.test.ts | 6 +- test/read-agreement.ts | 61 +++ test/read-fuzz.ts | 45 +++ test/read.test.ts | 2 +- test/rules.test.ts | 212 ++++++++++ test/shape.test.ts | 45 ++- test/standard-lint.test.ts | 6 +- 41 files changed, 3283 insertions(+), 75 deletions(-) create mode 100644 docs/curves.md create mode 100644 src/curves.ts create mode 100644 test/curves.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cbc5b8..925191e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- Ellipses and splines, in R2018 drawings. `d.ellipse(center, majorAxis, ratio)` draws an + ellipse, or an arc of one with `startParameter` and `endParameter`. `d.spline(fitPoints)` draws + the cubic CAD programs fit through the points, with `startTangent`, `endTangent` or `closed`, + and `d.controlSpline(controlPoints)` a B-spline of its `degree`, from 1 to 11, `knots`, which + default to clamped uniform ones, and `weights`, or periodic with `closed`. `toDXF` writes each + as CAD programs save it, a spline through fit points with the knots and control points + `fitSpline` gives and one by control points clamped, and `toSVG` and `toPDF` draw them, with + dashes along the whole curve. The extents hold the curve, not its control points. `readDXF` + reads both. `lint` and the builder refuse a ratio outside 0 to 1, an axis of no length, one + parameter without the other, fewer than 2 fit points or two side by side that are one, a + tangent of no direction or on a closed spline, a degree out of range, too few control points, + knots of the wrong count or that decrease, weights not above 0, and more than 32,767 knots. + `ellipsePoint`, `ellipseBox`, `splinePoint`, `splineBox`, `fitSpline` and `clamped` give their + geometry. - Solid fills, wipeouts and masks, in R2018 drawings. `d.hatch(boundary)` fills the area inside one outline, or inside a list of loops `{ points, bulges? }`, solid in its layer's color: the area inside an odd number of loops is filled, so a loop inside another is a hole, whichever diff --git a/GUIDE.md b/GUIDE.md index 12b521f..ca2882d 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -59,10 +59,15 @@ export default d.build(); Coordinates are in drawing units with Y pointing up. Angles are in degrees, counterclockwise from +X. A layer's color is a number from 1 to 255 in the color index CAD programs share, and a lineweight is in millimetres. Entities drawn inside a `layer()` callback go on that layer. The -builder draws `line`, `polyline`, `rect`, `circle`, `arc`, `text` and dimensions. A polyline +builder draws `line`, `polyline`, `rect`, `circle`, `arc`, `ellipse`, `spline`, `text` and +dimensions. A polyline takes `bulges` to make a side an arc, `width` or `widths` to draw its sides wide, and `radius` to round its corners; `cloud` draws a revision cloud around an outline, which crosses nothing inside it, and `donut` a filled ring or dot. [docs/polylines.md](docs/polylines.md) has them. +`ellipse` draws an ellipse or an arc of one by its center, the end of its major axis and the +ratio of its axes; `spline` draws the cubic CAD programs fit through fit points, for a top of +bank, a tree line or a contour, and `controlSpline` a spline by its control points. +[docs/curves.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/curves.md) has them. `image` draws a PNG or a JPEG at a width in drawing units, with the file's `pixels`, which `rasterSize` reads, and an optional `clip`; the command reads the file from the drawing file's folder for the pictures, and warns of one that is missing. diff --git a/README.md b/README.md index 0d934a3..5bb3b56 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,19 @@ d.donut([10, 10], 0.5); // a filled dot `bulges` makes any side an arc, and `widths` gives each side a width at each end. [Polylines](docs/polylines.md) has the rest. +An ellipse is drawn by its center, the end of its major axis and the ratio of its axes, and a +spline through fit points, as a top of bank or a tree line is drawn through located shots, or by +its control points: + +```ts +d.ellipse([10, 5], [4, 0], 0.5); +d.spline(bank); // the cubic CAD programs fit through the points +d.controlSpline(controlPoints, { degree: 3 }); +``` + +[Ellipses and splines](docs/curves.md) has arcs of an ellipse, tangents, closed splines, knots +and weights. + A paragraph is one text whose lines wrap at a width, which a CAD user edits as one. A line feed starts a new paragraph, and small helpers write the codes for a numbered list, an underline, bold, a stacked fraction and a superscript: @@ -405,6 +418,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version block, names, handles and what the preview draws. - [Polylines](docs/polylines.md) covers arcs by their bulge, rounded corners, revision clouds, widths and donuts, how a wide polyline plots, and what `lint` refuses of them. +- [Ellipses and splines](docs/curves.md) covers ellipses and their arcs, splines through fit + points and by control points, how they plot and dash, and what `lint` refuses of them. - [Paragraphs](docs/paragraphs.md) covers paragraph text: its width and box, the codes its value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, diff --git a/docs/assets/plan-set-A-101-dark.svg b/docs/assets/plan-set-A-101-dark.svg index 0034712..b282d18 100644 --- a/docs/assets/plan-set-A-101-dark.svg +++ b/docs/assets/plan-set-A-101-dark.svg @@ -1,4 +1,4 @@ - + diff --git a/docs/assets/plan-set-A-101-light.svg b/docs/assets/plan-set-A-101-light.svg index c914a84..15c009f 100644 --- a/docs/assets/plan-set-A-101-light.svg +++ b/docs/assets/plan-set-A-101-light.svg @@ -1,4 +1,4 @@ - + diff --git a/docs/assets/plan-set-A-201-dark.svg b/docs/assets/plan-set-A-201-dark.svg index 85d50e7..3afd547 100644 --- a/docs/assets/plan-set-A-201-dark.svg +++ b/docs/assets/plan-set-A-201-dark.svg @@ -1,4 +1,4 @@ - + diff --git a/docs/assets/plan-set-A-201-light.svg b/docs/assets/plan-set-A-201-light.svg index f75f89f..9d973e0 100644 --- a/docs/assets/plan-set-A-201-light.svg +++ b/docs/assets/plan-set-A-201-light.svg @@ -1,4 +1,4 @@ - + diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index ed4b149..83e82fe 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -1,4 +1,4 @@ - + @@ -59,6 +59,7 @@ + @@ -160,6 +161,7 @@ 50' PUBLIC RIGHT-OF-WAY OAK STREET CENTERLINE + TOP OF BANK LOT 11 LOT 13 LOT 27 @@ -214,6 +216,7 @@ + @@ -361,29 +364,31 @@ EDGE OF PAVEMENT OR CONCRETE STREET CENTERLINE + + TOP OF BANK - + - PROPERTY CORNER + PROPERTY CORNER - - - + + + - EXISTING TREE TO REMAIN - ABBREVIATIONS - - AC - ACRES - CONC. - CONCRETE - ELEV. - ELEVATION - F.F.E. - FINISHED FLOOR ELEVATION - MAX. - MAXIMUM - SF - SQUARE FEET + EXISTING TREE TO REMAIN + ABBREVIATIONS + + AC + ACRES + CONC. + CONCRETE + ELEV. + ELEVATION + F.F.E. + FINISHED FLOOR ELEVATION + MAX. + MAXIMUM + SF + SQUARE FEET diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index aa25144..dbba44c 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -1,4 +1,4 @@ - + @@ -59,6 +59,7 @@ + @@ -160,6 +161,7 @@ 50' PUBLIC RIGHT-OF-WAY OAK STREET CENTERLINE + TOP OF BANK LOT 11 LOT 13 LOT 27 @@ -214,6 +216,7 @@ + @@ -361,29 +364,31 @@ EDGE OF PAVEMENT OR CONCRETE STREET CENTERLINE + + TOP OF BANK - + - PROPERTY CORNER + PROPERTY CORNER - - - + + + - EXISTING TREE TO REMAIN - ABBREVIATIONS - - AC - ACRES - CONC. - CONCRETE - ELEV. - ELEVATION - F.F.E. - FINISHED FLOOR ELEVATION - MAX. - MAXIMUM - SF - SQUARE FEET + EXISTING TREE TO REMAIN + ABBREVIATIONS + + AC + ACRES + CONC. + CONCRETE + ELEV. + ELEVATION + F.F.E. + FINISHED FLOOR ELEVATION + MAX. + MAXIMUM + SF + SQUARE FEET diff --git a/docs/curves.md b/docs/curves.md new file mode 100644 index 0000000..b1130fe --- /dev/null +++ b/docs/curves.md @@ -0,0 +1,157 @@ +# Ellipses and splines + +An ellipse is one entity, whole or an arc of it. A spline is a smooth curve: through fit points, +as a drafter draws the top of a bank, a tree line or a contour through located shots, or by its +control points, as a curve is given in another program. In the file each is the `ELLIPSE` or +`SPLINE` CAD programs hold, which a CAD user selects and edits as one. + +Both are R2018 only. The builder and `lint` refuse them in an R12 drawing. + +## Ellipses + +`ellipse(center, majorAxis, ratio)` takes the vector from the center to one end of the major +axis, which gives the major radius and the direction, and the ratio of the minor radius to the +major, above 0 and at most 1: + +```ts +d.ellipse([10, 5], [4, 0], 0.5); // 8 across, 4 high +d.ellipse([10, 5], [0, 3], 0.6, { startParameter: 0, endParameter: 180 }); // the left half +``` + +`startParameter` and `endParameter` make an arc of it, counterclockwise from one to the other, +in degrees, given together or not at all. A parameter is not the angle a point is at from the +center: the point at parameter `t` is `center + cos(t) * majorAxis + sin(t) * ratio * minor`, +where `minor` is `majorAxis` turned a quarter turn counterclockwise. They agree at multiples of 90 +degrees; on an ellipse of ratio 0.5, parameter 45 is the point at about 26.6 degrees. +`ellipsePoint` gives a point at a parameter in radians. Parameters are stored from 0 up to 360, +so -90 becomes 270. + +## Splines through fit points + +`spline(fitPoints)` draws the cubic CAD programs' `SPLINE` fits through the points, with its knots +spaced by the chords between them: + +```ts +d.spline([ + [-34, 146], + [-28, 124], + [-35, 98], + [-27, 72], +]); +d.spline( + [ + [0, 0], + [10, 4], + [20, 2], + ], + { startTangent: [0, 1], endTangent: [1, 0] }, +); +d.spline( + [ + [0, 10], + [5, 14], + [10, 10], + [5, 6], + ], + { closed: true }, +); +``` + +`startTangent` and `endTangent` are the directions it leaves its first point and reaches its +last in; where one is left out it is worked out from the points. `closed` runs it from the last +point back to the first, smooth through it, and takes no tangents. Two points with no tangent +give the straight line between them. + +The file holds the fit points and the cubic through them: its knots and control points, which +`fitSpline` works out, and which the writers, the pictures and the extents all take from it. A +closed one holds its first point again at its end, with the direction it runs through it as both +tangents. + +## Splines by their control points + +`controlSpline(controlPoints)` draws a B-spline of `degree`, 3 unless given, from 1 to 11: + +```ts +d.controlSpline([ + [0, 0], + [5, 8], + [10, 0], + [15, 8], +]); +// A quarter circle, as a rational quadratic. +d.controlSpline( + [ + [0, 0], + [0, 5], + [5, 5], + ], + { degree: 2, weights: [1, Math.SQRT1_2, 1] }, +); +d.controlSpline( + [ + [0, 0], + [5, 8], + [10, 0], + [15, 8], + ], + { closed: true }, +); +``` + +Its `knots` are as many as its control points and its degree together, and one more, none less +than the one before. Left out, they are clamped and uniform: the degree and one more of 0, then +1, 2 and on, and the degree and one more of the last, so the curve starts on its first control +point and ends on its last. `weights`, one for each control point and each above 0, make it +rational, which draws a circle or an ellipse exactly. `closed` makes it periodic, smooth where it +joins: without `knots`, its first `degree` control points come again at its end, with uniform +knots, so it closes on them. + +CAD programs save every spline clamped at the ends of what it draws, so the writer writes one whose +knots are not clamped there, a closed one among them, as the same curve with clamped knots: +`clamped` gives that form. + +## How it plots + +`toSVG` and `toPDF` draw an ellipse as an ellipse and an arc of one as an elliptical arc, through +an insert's scale, turn and mirror too. A spline of degree 1 to 3 that is not rational is drawn +exactly, as lines or cubic pieces; a rational one, or one of a higher degree, as 32 straight steps +to each span of its knots. + +A dash pattern runs along the whole curve as one stretch. An arc of an ellipse and an open spline +are fitted as a line is: as many whole patterns as fit, and the first and last dash each half of +the first dash and of what is left over. A whole ellipse and a closed spline hold the whole number +of patterns nearest their length, stretched alike to go round, from a dash at parameter 0, or at +the spline's start. A curve shorter than its pattern is solid. + +The extents hold the curve itself, not its control points: an ellipse's are exact, and a spline's +within a ten-millionth of a unit of the curve, and never inside it. + +## Checks + +The builder refuses, and `lint` reports, under the rule `geometry`: + +- an ellipse whose ratio is not above 0 and at most 1 as written, whose major axis is `[0, 0]` as + written, with one parameter and not the other, or with parameters outside 0 up to 360 or equal as + written; +- a spline through fewer than 2 fit points, or 3 when it is closed, or with two side by side, or + the last and the first of a closed one, that are one as written; a tangent of `[0, 0]`, or any + tangent on a closed one; or a fit whose control points come to 1e100 or more; +- a spline by its control points of a degree that is not a whole number from 1 to + `SPLINE_DEGREE_MOST`, with fewer control points than its degree and one more, with knots that + are not as many as its control points and its degree and one, that decrease, or that are all + one over what it draws, as written, or with weights that are not one for each control point and + each above 0 as written; +- more than `SPLINE_ITEMS`, 32,767, knots, which a file counts in 16 bits: a spline through fit + points takes 6 more than its points, 7 when it is closed. + +A literal the compiler can read is refused there too: a ratio of 0, of less or of more than 1, a +degree outside the range, fewer than 2 fit points or two the same side by side, a tangent of +`[0, 0]`, a tangent on a closed spline, and too few control points, the wrong count of knots or +of weights, or a weight of 0 or less, for a spline given as literals. + +## Reading + +`readDXF` with `geometry` reads an `ellipse` with its `center`, `majorAxis`, `ratio` and, for an +arc, its `startParameter` and `endParameter` in degrees, and a `spline` with its `degree`, `knots`, +`controlPoints` and `weights` as the file holds them, `closed`, `periodic`, and its `fitPoints`, +tangents and `fitTolerance` where it has them. [Reading a DXF](reading.md) has the rest. diff --git a/docs/format.md b/docs/format.md index af2e4b7..42edbc0 100644 --- a/docs/format.md +++ b/docs/format.md @@ -109,6 +109,14 @@ dashes where it has them. A gradient is `{ name, angle, centered }` where they a dimension style's `textMask` are written where they are set. A drawing with none of them has the JSON it had before they existed. [Fills, wipeouts and masks](fills.md) describes them. +An ellipse is an entity of kind `"ellipse"`, with its `layer`, `center`, `majorAxis` and `ratio`, +and for an arc of it its `startParameter` and `endParameter`. A spline is an entity of kind +`"spline"`: through fit points, with its `fitPoints` and where they are set its `startTangent`, +`endTangent` and `closed`; or by its control points, with its `controlPoints`, `degree` and +`knots`, and where they are set its `weights` and `closed`. Each has the `linetype` and +`lineweight` of every entity. A drawing with neither has the JSON it had before they existed. +[Ellipses and splines](curves.md) describes them. + A drawing written by hand needs `format: 0` too. `lint` reports a drawing without it, or with another version, under the rule `format`, and `toDXF` refuses to write it. `lint` takes any plain data and never throws: a list that is not an array, an entity of an unknown `kind`, a diff --git a/docs/plotting.md b/docs/plotting.md index 689bc98..ed084c7 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -58,7 +58,10 @@ preview shows it: by its twist, as [Frozen layers and a twist](layouts.md#frozen-layers-and-a-twist) says. - A curve strays from its arc by at most 1/1000 inch on the paper. - A dash pattern is sized on the paper and fitted to each line, side of a polyline, arc and - circle, as [Linetypes on a sheet](layouts.md#linetypes-on-a-sheet) says. + circle, as [Linetypes on a sheet](layouts.md#linetypes-on-a-sheet) says, and along the whole + of an ellipse or a spline, as [How it plots](curves.md#how-it-plots) says. +- An ellipse, an arc of one and a spline of degree 3 or less are drawn exactly; a rational spline + or one of a higher degree in 32 straight steps to each span of its knots. - A line of lineweight 0 plots as the thinnest line the printer draws, as a viewport's border does. - A wide side of a polyline is filled, at its width whatever its pen, with its joins and its diff --git a/docs/reading.md b/docs/reading.md index 7b1ae97..6c6f033 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -190,6 +190,19 @@ leader: angle and `centered: false` do not give its mirror image, because its shift does not mirror with the angle. - `wipeout`: its `points` in the world's coordinates, without the first again at the end. +- `ellipse`: its `center` and `majorAxis`, which the file holds in the world's coordinates, its + `ratio`, and for an arc its `startParameter` and `endParameter` in degrees, as `Ellipse` holds + them. One the file holds seen from below runs its parameters the other way round, and is read as + the ellipse it draws seen from above: its arc from s to e is the arc from 360 less e to 360 less + s. One whose ratio is outside 0 to 1, or whose axis has no length, is counted under + `unread.malformed`, and one out of the plane under `other`. +- `spline`: its `degree`, `knots`, `controlPoints` and, for a rational one, `weights`, as the file + holds them; `closed` and `periodic` from its flags; and where the file holds them its + `fitPoints`, `startTangent`, `endTangent`, `fitTolerance` and the `knotSpacing` its flags give. + One closed by its first fit point again at its end is `closed`, with that point once in + `fitPoints`. One whose counts disagree with its groups, whose degree is not a whole number from + 1 to 11, or whose knots do not fit its control points is counted under `unread.malformed`, and + one with a point off the plane under `other`. - An `mtext` with a background holds `mask`: its `offsetFactor`, and its `color` or `trueColor` where it is not in the drawing's background. diff --git a/docs/rules.md b/docs/rules.md index 0567a15..0054fd8 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -73,6 +73,16 @@ it would take `1e+100` for `1e+10` and report nothing. alone, and its `angle` and `origin` are finite. The lines it places hold no number of 1e100 or more, and it draws at most 1,000,000 lines across the box of its loops. The rule of these is `hatch-pattern`. [Patterns](fills.md#patterns) has the rest. +- An ellipse and a spline are R2018 only. An ellipse's ratio is above 0 and at most 1 as + written, its major axis is not `[0, 0]` as written, and an arc of it has both parameters, from + 0 up to 360 and not equal as written. A spline through fit points has 2 or more, 3 when it is + closed, none side by side the same as written, and tangents that are not `[0, 0]`, none on a + closed one. A spline by control points has a whole degree from 1 to `SPLINE_DEGREE_MOST`, at + least one more control point than its degree, as many knots as its control points and its + degree and one, never decreasing and not all one over what it draws, and a weight above 0 for + each control point where it has weights. A closed one ends where it starts, the way it + arrives. A spline holds at most `SPLINE_ITEMS`, 32,767, knots. + [Ellipses and splines](curves.md#checks) has the rest. - A hatch's `gradient` goes with no `pattern`. Its `name` is one of `GRADIENT_KINDS`, its `angle` a finite number under 1e100 and `centered` true or false, and it has two `colors` or a `color` and a `tint` from 0 to 1, each color three whole numbers from 0 to 255, and no other field. The rule of these is diff --git a/examples/site-plan.ts b/examples/site-plan.ts index f0df955..f0b587e 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -109,6 +109,7 @@ export const standard = defineStandard({ "V-TREE": { color: 3, pen: "fine", discipline: "V" }, "C-ANNO-REVS": { color: 1, pen: "medium", discipline: "C" }, "C-ANNO-IMAG": { color: 8, pen: "fine", discipline: "C" }, + "C-TOPO-BANK": { color: 30, linetype: "HIDDEN", pen: "fine", discipline: "C" }, }, }); @@ -156,6 +157,16 @@ const trees: { at: Point; radius: number }[] = [ { at: [85, 111], radius: 5 }, { at: [28, 12], radius: 5 }, ]; +// The top of the bank of a drainage swale in the adjoining lot, where the survey located it. +const bank: Point[] = [ + [-34, 146], + [-28, 124], + [-35, 98], + [-27, 72], + [-33, 48], + [-26, 26], + [-31, 6], +]; // Positions worked out from the site. const houseX = (lot.width - house.width) / 2; @@ -362,6 +373,8 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee d.layer("V-TREE", () => { for (const tree of trees) d.insert("TREE", tree.at, { scale: tree.radius }); }); + // A line that bends with the ground is a spline through the points located on it. + d.layer("C-TOPO-BANK", () => d.spline(bank)); // The plan's annotation, in model space with what it describes. A text names the view it is // read in, which sizes it to plot at its role's height. Gaps and offsets are lengths on paper, @@ -507,6 +520,14 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee align: "right", }); + // The bank, beside it on the side away from the lot. + d.text([-38, 60], "TOP OF BANK", { + role: "note", + view: plan, + align: "center", + rotation: 90, + }); + // The adjoining lots, each an inch outside its lot line and reading along it. d.text([-plan.paper(1), lot.depth / 2], "LOT 11", { role: "label", @@ -795,6 +816,7 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee legendRow("C-BLDG", "BUILDING FOOTPRINT", sampleLine); legendRow("C-PAVE", "EDGE OF PAVEMENT OR CONCRETE", sampleLine); legendRow("C-ROAD-CNTR", "STREET CENTERLINE", sampleLine); + legendRow("C-TOPO-BANK", "TOP OF BANK", sampleLine); legendRow("C-PROP-MONU", "PROPERTY CORNER", () => d.insert("PROPERTY CORNER", sampleCenter())); row -= leading / 2; // The tree is one foot in radius in its block, and 3/16 in on the paper. diff --git a/scripts/readme-drawing.ts b/scripts/readme-drawing.ts index c6196d5..86cd4a1 100644 --- a/scripts/readme-drawing.ts +++ b/scripts/readme-drawing.ts @@ -84,6 +84,7 @@ const pictures: Picture[] = [ "C-BLDG": "accent", "C-PAVE": "muted", "C-ROAD-CNTR": "muted", + "C-TOPO-BANK": "muted", "V-TREE": "muted", "C-ANNO-DIMS": "accent", "C-ANNO-REVS": "accent", diff --git a/src/curves.ts b/src/curves.ts new file mode 100644 index 0000000..6107c47 --- /dev/null +++ b/src/curves.ts @@ -0,0 +1,555 @@ +/** + * What an ellipse and a spline draw: the points of each, the spline the leading CAD app fits + * through fit points, and the pieces the pictures draw them in. The writers, the plots, the + * extents and the readers all take an ellipse and a spline from here. + */ +import type { Point } from "./drawing.ts"; + +/** + * How the knots of a spline through fit points are spaced: by the chords between the points, + * their square roots, or alike. A DXF holds chord alone; a DWG may hold another. + */ +export type KnotSpacing = "chord" | "square-root" | "uniform"; + +type Xy = readonly [number, number]; + +const TAU = 2 * Math.PI; + +/** The parameter `t` of an ellipse turned into [0, 2π). */ +export function unturned(t: number): number { + const r = t % TAU; + return r < 0 ? r + TAU : r; +} + +/** A point of an ellipse about `center`, with `major` from the center and the minor `ratio`. */ +export function ellipsePoint(center: Xy, major: Xy, ratio: number, t: number): [number, number] { + const [c, s] = [Math.cos(t), Math.sin(t)]; + return [ + center[0] + major[0] * c - major[1] * ratio * s, + center[1] + major[1] * c + major[0] * ratio * s, + ]; +} + +/** The span of a B-spline's knots that holds `u`, among those the curve runs over. */ +function spanOf(degree: number, knots: readonly number[], count: number, u: number): number { + const last = count - 1; + if (u >= knots[last + 1]!) { + let k = last; + while (k > degree && knots[k]! >= knots[last + 1]!) k--; + return k; + } + let [lo, hi] = [degree, last + 1]; + while (hi - lo > 1) { + const mid = (lo + hi) >> 1; + if (u < knots[mid]!) hi = mid; + else lo = mid; + } + return lo; +} + +/** + * A point of a B-spline at `u`, rational when `weights` are given, by de Boor's steps on the + * control points of the span that holds `u`. + */ +export function splinePoint( + degree: number, + knots: readonly number[], + points: readonly Xy[], + weights: readonly number[] | undefined, + u: number, +): [number, number] { + const k = spanOf(degree, knots, points.length, u); + const d: [number, number, number][] = []; + for (let j = 0; j <= degree; j++) { + const p = points[k - degree + j]!; + const w = weights?.[k - degree + j] ?? 1; + d.push([p[0] * w, p[1] * w, w]); + } + for (let r = 1; r <= degree; r++) { + for (let j = degree; j >= r; j--) { + const i = k - degree + j; + const span = knots[i + degree - r + 1]! - knots[i]!; + const a = span === 0 ? 0 : (u - knots[i]!) / span; + const [p, q] = [d[j - 1]!, d[j]!]; + d[j] = [(1 - a) * p[0] + a * q[0], (1 - a) * p[1] + a * q[1], (1 - a) * p[2] + a * q[2]]; + } + } + const [x, y, w] = d[degree]!; + return [x / w, y / w]; +} + +/** The knots of a B-spline that bound the pieces it draws: from `knots[degree]` to `knots[count]`. */ +export function splineBreaks(degree: number, knots: readonly number[], count: number): number[] { + const out: number[] = []; + for (let i = degree; i <= count; i++) { + const u = knots[i]!; + if (out.length === 0 || u > out[out.length - 1]!) out.push(u); + } + return out; +} + +/** + * The points a B-spline is drawn through: each piece between two knots cut into `steps` of equal + * parameter, the ends of the pieces among them. + */ +export function splinePolyline( + degree: number, + knots: readonly number[], + points: readonly Xy[], + weights: readonly number[] | undefined, + steps: number, +): [number, number][] { + const breaks = splineBreaks(degree, knots, points.length); + const out: [number, number][] = []; + for (let b = 0; b + 1 < breaks.length; b++) { + const [u0, u1] = [breaks[b]!, breaks[b + 1]!]; + for (let s = b === 0 ? 0 : 1; s <= steps; s++) + out.push(splinePoint(degree, knots, points, weights, u0 + ((u1 - u0) * s) / steps)); + } + return out; +} + +/** The parameter of each fit point, from 0, spaced as `spacing` says. */ +export function fitParameters(points: readonly Xy[], spacing: KnotSpacing): number[] { + const out = [0]; + for (let i = 1; i < points.length; i++) { + const [a, b] = [points[i - 1]!, points[i]!]; + const chord = Math.hypot(b[0] - a[0], b[1] - a[1]); + const step = spacing === "chord" ? chord : spacing === "square-root" ? Math.sqrt(chord) : 1; + out.push(out[i - 1]! + step); + } + return out; +} + +/** A cubic B-spline through fit points: its knots and control points. */ +export interface FittedSpline { + readonly knots: readonly number[]; + readonly controlPoints: readonly Point[]; + /** For a closed spline, the direction it runs through its first point in, at both ends. */ + readonly tangent?: Point; +} + +/** + * The values at `u` of the `degree + 1` basis functions of the knots that are not 0 in the span + * `span`: those of control points `span - degree` to `span`. + */ +function basisAt(degree: number, knots: readonly number[], span: number, u: number): number[] { + const out = [1]; + const left: number[] = []; + const right: number[] = []; + for (let j = 1; j <= degree; j++) { + left[j] = u - knots[span + 1 - j]!; + right[j] = knots[span + j]! - u; + let saved = 0; + for (let r = 0; r < j; r++) { + const term = out[r]! / (right[r + 1]! + left[j - r]!); + out[r] = saved + right[r + 1]! * term; + saved = left[j - r]! * term; + } + out[j] = saved; + } + return out; +} + +/** One row of a system of three diagonals: what it holds of the unknown before, its own and the next. */ +interface Row { + readonly before: number; + readonly own: number; + readonly next: number; + readonly value: Xy; +} + +/** Solves a system of three diagonals by the Thomas algorithm. */ +function threeDiagonals(rows: readonly Row[]): [number, number][] { + const m = rows.length; + const own = rows.map((r) => r.own); + const value = rows.map((r): [number, number] => [r.value[0], r.value[1]]); + for (let i = 1; i < m; i++) { + const w = rows[i]!.before / own[i - 1]!; + own[i] = own[i]! - w * rows[i - 1]!.next; + value[i] = [value[i]![0] - w * value[i - 1]![0], value[i]![1] - w * value[i - 1]![1]]; + } + const out: [number, number][] = new Array(m); + out[m - 1] = [value[m - 1]![0] / own[m - 1]!, value[m - 1]![1] / own[m - 1]!]; + for (let i = m - 2; i >= 0; i--) + out[i] = [ + (value[i]![0] - rows[i]!.next * out[i + 1]![0]) / own[i]!, + (value[i]![1] - rows[i]!.next * out[i + 1]![1]) / own[i]!, + ]; + return out; +} + +/** + * The control points of the clamped cubic through `points` at the knots `knots`: the first and + * last are the end points, and each end either leaves with the derivative given or, with none + * given, bends not at all there. + */ +function throughPoints( + points: readonly Xy[], + knots: readonly number[], + startDerivative: Xy | undefined, + endDerivative: Xy | undefined, +): Point[] { + const n = points.length - 1; + const count = n + 3; + const [first, last] = [points[0]!, points[n]!]; + const t = (i: number) => knots[i]!; + // The unknowns are control points 1 to count - 2. + const rows: Row[] = []; + if (startDerivative) { + const f = (t(4) - t(1)) / 3; + rows.push({ + before: 0, + own: 1, + next: 0, + value: [first[0] + f * startDerivative[0], first[1] + f * startDerivative[1]], + }); + } else { + // No bend at the start: (P2 - P1) / (t5 - t2) = (P1 - P0) / (t4 - t1). + const [a, b] = [t(4) - t(1), t(5) - t(2)]; + rows.push({ + before: 0, + own: -(1 / a + 1 / b), + next: 1 / b, + value: [-first[0] / a, -first[1] / a], + }); + } + for (let k = 1; k <= n - 1; k++) { + const [a, b, c] = basisAt(3, knots, k + 3, t(k + 3)); + rows.push({ before: a!, own: b!, next: c!, value: points[k]! }); + } + if (endDerivative) { + const f = (t(count) - t(count - 1)) / 3; + rows.push({ + before: 0, + own: 1, + next: 0, + value: [last[0] - f * endDerivative[0], last[1] - f * endDerivative[1]], + }); + } else { + const [a, b] = [t(count) - t(count - 1), t(count) - t(count - 2)]; + rows.push({ + before: 1 / b, + own: -(1 / a + 1 / b), + next: 0, + value: [-last[0] / a, -last[1] / a], + }); + } + return [[first[0], first[1]], ...threeDiagonals(rows), [last[0], last[1]]]; +} + +/** + * The cubic the leading CAD app fits through fit points: clamped knots at each point's parameter, + * and an end's tangent given, as a direction, or worked out where it is not. Closed, it runs + * through the points and the first again, with one tangent at both ends, worked out where they + * join, which it returns. + */ +export function fitSpline( + points: readonly Xy[], + spacing: KnotSpacing, + startTangent?: Xy, + endTangent?: Xy, + closed = false, +): FittedSpline { + if (closed) { + const ring = [...points, points[0]!]; + const tangent = joinTangent(ring, spacing); + return { ...fitSpline(ring, spacing, tangent, tangent), tangent }; + } + const u = fitParameters(points, spacing); + const n = points.length - 1; + const [u0, un] = [u[0]!, u[n]!]; + const knots = [u0, u0, u0, ...u, un, un, un]; + // A tangent is a direction: the curve leaves along it at the pace of its parameter, a unit of + // chord for each unit of parameter. + let chords = 0; + for (let i = 1; i <= n; i++) + chords += Math.hypot(points[i]![0] - points[i - 1]![0], points[i]![1] - points[i - 1]![1]); + const pace = un - u0 > 0 ? chords / (un - u0) : 1; + const derivative = (v: Xy | undefined): Xy | undefined => { + if (v === undefined) return undefined; + const l = Math.hypot(v[0], v[1]); + return [(v[0] / l) * pace, (v[1] / l) * pace]; + }; + return { + knots, + controlPoints: throughPoints(points, knots, derivative(startTangent), derivative(endTangent)), + }; +} + +/** A point in homogeneous coordinates: x and y times the weight, and the weight. */ +export type Weighted = readonly [number, number, number]; + +/** + * The Bézier pieces of a B-spline, one for each span of knots with a length between + * `knots[degree]` and `knots[count]`: `degree + 1` control points each, in homogeneous + * coordinates, which a rational spline needs. Each comes from the blossom of its span, in time in + * proportion to the control points. + */ +export function splinePieces( + degree: number, + knots: readonly number[], + points: readonly Xy[], + weights: readonly number[] | undefined, +): Weighted[][] { + const out: Weighted[][] = []; + const [dx, dy, dw] = [ + new Float64Array(degree + 1), + new Float64Array(degree + 1), + new Float64Array(degree + 1), + ]; + const count = points.length; + for (let i = degree; i < count; i++) { + const [a, b] = [knots[i]!, knots[i + 1]!]; + if (!(b > a)) continue; + const piece: Weighted[] = []; + for (let j = 0; j <= degree; j++) { + // The blossom at `a` taken degree - j times and `b` taken j times. + for (let k = 0; k <= degree; k++) { + const p = points[i - degree + k]!; + const w = weights?.[i - degree + k] ?? 1; + [dx[k], dy[k], dw[k]] = [p[0] * w, p[1] * w, w]; + } + for (let r = 1; r <= degree; r++) { + const t = r <= degree - j ? a : b; + for (let k = degree; k >= r; k--) { + const at = i - degree + k; + const span = knots[at + degree - r + 1]! - knots[at]!; + const f = span === 0 ? 0 : (t - knots[at]!) / span; + dx[k] = (1 - f) * dx[k - 1]! + f * dx[k]!; + dy[k] = (1 - f) * dy[k - 1]! + f * dy[k]!; + dw[k] = (1 - f) * dw[k - 1]! + f * dw[k]!; + } + } + piece.push([dx[degree]!, dy[degree]!, dw[degree]!]); + } + out.push(piece); + } + return out; +} + +/** A box: its least x and y, and its greatest. */ +export type CurveBox = [number, number, number, number]; + +/** A Bézier piece cut in two at its middle. */ +function halves(part: readonly Weighted[]): [Weighted[], Weighted[]] { + let row: Weighted[] = [...part]; + const left: Weighted[] = [row[0]!]; + const right: Weighted[] = [row[row.length - 1]!]; + while (row.length > 1) { + const next: Weighted[] = []; + for (let k = 0; k + 1 < row.length; k++) { + const [p, q] = [row[k]!, row[k + 1]!]; + next.push([(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2]); + } + left.push(next[0]!); + right.push(next[next.length - 1]!); + row = next; + } + return [left, right.reverse()]; +} + +/** + * The box of a B-spline, from its curve. It passes through the ends of its Bézier pieces, and + * each piece lies inside the hull of its control points, so a piece whose hull stays inside the + * box of the ends is left as it is. A side a piece's hull reaches past is cut in two, as de + * Casteljau cuts it, where it can still reach past the box, until the hull is within `tolerance` + * of the curve or the cuts, 64 a side, run out, and the hull's side is taken. So the box holds the + * curve, with at most `tolerance` more on a side but where the cuts ran out. + */ +export function splineBox( + degree: number, + knots: readonly number[], + points: readonly Xy[], + weights: readonly number[] | undefined, + tolerance: number, +): CurveBox | undefined { + const pieces = splinePieces(degree, knots, points, weights); + if (pieces.length === 0) return undefined; + const box: CurveBox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const piece of pieces) { + for (const p of [piece[0]!, piece[degree]!]) { + const [x, y] = [p[0] / p[2], p[1] / p[2]]; + box[0] = Math.min(box[0], x); + box[1] = Math.min(box[1], y); + box[2] = Math.max(box[2], x); + box[3] = Math.max(box[3], y); + } + } + // Each of the four sides: the axis and whether it is the greatest. + for (let side = 0; side < 4; side++) { + const [axis, sign] = [side % 2, side >= 2 ? 1 : -1]; + const value = (p: Weighted): number => (sign * p[axis]!) / p[2]; + const reachOf = (part: readonly Weighted[]): number => { + let most = -Infinity; + for (const p of part) most = Math.max(most, value(p)); + return most; + }; + let best = sign * box[side]!; + for (const piece of pieces) { + if (reachOf(piece) <= best) continue; + let cuts = 0; + const stack: Weighted[][] = [piece]; + while (stack.length > 0) { + const part = stack.pop()!; + const reach = reachOf(part); + if (reach <= best) continue; + best = Math.max(best, value(part[0]!), value(part[part.length - 1]!)); + if (reach - best <= tolerance || cuts >= 64) { + best = reach; + continue; + } + cuts++; + stack.push(...halves(part)); + } + } + box[side] = sign * best; + } + return box; +} + +/** + * The box of an ellipse, or of its arc from `start` counterclockwise to `end` in radians: the + * ends of the arc, and the parameters where x and y are greatest and least that it runs through. + */ +export function ellipseBox( + center: Xy, + major: Xy, + ratio: number, + start?: number, + end?: number, +): CurveBox { + const whole = start === undefined || end === undefined; + const from = whole ? 0 : unturned(start); + let sweep = whole ? TAU : unturned(end) - from; + if (sweep <= 0) sweep += TAU; + const ts: number[] = whole ? [] : [from, from + sweep]; + // x is greatest where its derivative, -major.x sin t - major.y ratio cos t, is 0, and least + // half a turn on; y likewise. + for (const t0 of [ + Math.atan2(-major[1] * ratio, major[0]), + Math.atan2(major[0] * ratio, major[1]), + ]) + for (const t of [t0, t0 + Math.PI]) { + const on = unturned(t - from); + if (whole || on <= sweep) ts.push(from + on); + } + const box: CurveBox = [Infinity, Infinity, -Infinity, -Infinity]; + for (const t of ts) { + const [x, y] = ellipsePoint(center, major, ratio, t); + box[0] = Math.min(box[0], x); + box[1] = Math.min(box[1], y); + box[2] = Math.max(box[2], x); + box[3] = Math.max(box[3], y); + } + return box; +} + +/** + * The direction a closed spline through `ring`, whose last point is its first again, runs through + * its first point in: that of the cubic that closes through the points smooth to its second + * derivative. + */ +function joinTangent(ring: readonly Xy[], spacing: KnotSpacing): Point { + // The derivatives D of the cubic that closes smooth to its second derivative through the m + // points, each span i as long in parameter as h[i]: for each point, + // h[i] D[i-1] + 2 (h[i-1] + h[i]) D[i] + h[i-1] D[i+1] = 3 (h[i] / h[i-1] (P[i] - P[i-1]) + + // h[i-1] / h[i] (P[i+1] - P[i])), a cyclic system of three diagonals. + const m = ring.length - 1; + const u = fitParameters(ring, spacing); + const h = (i: number) => u[(((i % m) + m) % m) + 1]! - u[((i % m) + m) % m]!; + const P = (i: number) => ring[((i % m) + m) % m]!; + const rows: Row[] = []; + for (let i = 0; i < m; i++) { + const [a, b] = [h(i - 1), h(i)]; + const value: Xy = [0, 1].map( + (k) => 3 * ((b / a) * (P(i)[k]! - P(i - 1)[k]!) + (a / b) * (P(i + 1)[k]! - P(i)[k]!)), + ) as unknown as Xy; + rows.push({ before: b, own: 2 * (a + b), next: a, value }); + } + return cyclicFirst(rows); +} + +/** + * The first unknown of a cyclic system of three diagonals, whose first row also holds the last + * unknown by `before` and whose last row the first by `next`, by the Sherman-Morrison formula. + */ +function cyclicFirst(rows: readonly Row[]): Point { + const m = rows.length; + const [corner, last] = [rows[0]!.before, rows[m - 1]!.next]; + const gamma = -rows[0]!.own; + // The system less the corners, and `u` (gamma at the first, the last corner at the end). + const plain = rows.map((r, i): Row => ({ + before: i === 0 ? 0 : r.before, + own: i === 0 ? r.own - gamma : i === m - 1 ? r.own - (last * corner) / gamma : r.own, + next: i === m - 1 ? 0 : r.next, + value: r.value, + })); + const x = threeDiagonals(plain); + const z = threeDiagonals( + plain.map((r, i): Row => ({ ...r, value: [i === 0 ? gamma : i === m - 1 ? last : 0, 0] })), + ); + const shared = 1 + z[0]![0] + (corner * z[m - 1]![0]) / gamma; + const factor = (k: 0 | 1) => (x[0]![k] + (corner * x[m - 1]![k]) / gamma) / shared; + return [x[0]![0] - factor(0) * z[0]![0], x[0]![1] - factor(1) * z[0]![0]]; +} + +/** A B-spline: its degree, knots, control points and, for a rational one, weights. */ +export interface BSpline { + readonly degree: number; + readonly knots: readonly number[]; + readonly controlPoints: readonly Point[]; + readonly weights?: readonly number[]; +} + +/** + * The same curve with clamped knots: its first and last knot each `degree + 1` times, so it + * starts on its first control point and ends on its last, as the leading CAD app saves every + * spline. Knots are inserted at the ends of what it runs over, one at a time as Boehm inserts + * them, and the knots and control points outside are dropped. A clamped spline comes back as it + * is. + */ +export function clamped(spline: BSpline): BSpline { + const { degree: p } = spline; + let knots = [...spline.knots]; + let points: Weighted[] = spline.controlPoints.map((q, i) => { + const w = spline.weights?.[i] ?? 1; + return [q[0] * w, q[1] * w, w]; + }); + const [a, b] = [knots[p]!, knots[spline.controlPoints.length]!]; + /** Inserts `u` once in the span from knot `k`, which holds it. */ + const insert = (u: number, k: number): void => { + const next: Weighted[] = []; + for (let i = 0; i <= points.length; i++) { + if (i <= k - p) next.push(points[i]!); + else if (i > k) next.push(points[i - 1]!); + else { + const f = (u - knots[i]!) / (knots[i + p]! - knots[i]!); + const [q, r] = [points[i - 1]!, points[i]!]; + next.push([ + (1 - f) * q[0] + f * r[0], + (1 - f) * q[1] + f * r[1], + (1 - f) * q[2] + f * r[2], + ]); + } + } + knots.splice(k + 1, 0, u); + points = next; + }; + const count = (u: number) => knots.filter((t) => t === u).length; + // At the start, in the span that ends after `a`; at the end, in the span that ends at `b`. + for (let s = count(a); s < p + 1; s++) insert(a, knots.lastIndexOf(a)); + const first = knots.lastIndexOf(a) - p; + knots = knots.slice(first); + points = points.slice(first); + for (let s = count(b); s < p + 1; s++) insert(b, knots.indexOf(b) - 1); + const last = knots.indexOf(b); + knots = knots.slice(0, last + p + 1); + points = points.slice(0, last); + return { + degree: p, + knots, + controlPoints: points.map(([x, y, w]): Point => [x / w, y / w]), + ...(spline.weights === undefined ? {} : { weights: points.map(([, , w]) => w) }), + }; +} diff --git a/src/drawing.ts b/src/drawing.ts index d03f0df..4bea488 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -226,6 +226,17 @@ import { type LEADER_SIDES, type LEADER_VERTICAL_ATTACHMENTS, HATCH_LOOP_POINTS, + controlSplineProblems, + ellipseProblems, + fitSplineProblems, + type ControlPoints, + type EllipseRatio, + type FitPoints, + type Knots, + type SPLINE_CLOSED_TANGENT, + type SplineDegree, + type Tangent, + type Weights, HATCH_NO_LOOPS, GRADIENT_WITH_PATTERN, type GRADIENT_KINDS, @@ -442,6 +453,72 @@ export interface Arc extends EntityBase { readonly endAngle: number; } +/** + * An ellipse, or an arc of one. Its points are `center + cos(t) * majorAxis + sin(t) * ratio * + * minor` for each parameter `t`, where `minor` is `majorAxis` turned a quarter turn + * counterclockwise. A parameter is not the angle a point is at from the center, except at + * multiples of 90 degrees: on an ellipse of ratio 0.5, the parameter 45 is the point at about + * 26.6 degrees. R2018 only. + */ +export interface Ellipse extends EntityBase { + readonly kind: "ellipse"; + readonly center: Point; + /** From the center to one end of the major axis: the major radius and its direction. */ + readonly majorAxis: Point; + /** The minor radius over the major: above 0, and at most 1. */ + readonly ratio: number; + /** + * For an arc, the parameter it starts at, in degrees from 0 up to 360, counterclockwise from + * the end of `majorAxis`. Given with `endParameter` or not at all, for a whole ellipse. + */ + readonly startParameter?: number; + /** For an arc, the parameter it ends at, in degrees from 0 up to 360. */ + readonly endParameter?: number; +} + +/** + * A spline through fit points: the cubic the leading CAD app's `SPLINE` fits through them, with + * its knots spaced by the chords between the points, which the writers work out and write beside + * the points. A DXF holds no other spacing: that app fits every spline it reads through fit points + * by chord. R2018 only. + */ +export interface FitSpline extends EntityBase { + readonly kind: "spline"; + /** The points it passes through, in order: 2 or more, 3 or more when it is closed. */ + readonly fitPoints: readonly Point[]; + /** The direction it leaves the first point in. Worked out from the points by default. */ + readonly startTangent?: Point; + /** The direction it arrives at the last point in. Worked out from the points by default. */ + readonly endTangent?: Point; + /** + * Whether it runs from the last point back to the first, smooth through it. It then takes no + * tangents. Defaults to false. + */ + readonly closed?: boolean; +} + +/** A spline by its control points: a B-spline of its degree, rational when it has weights. R2018 only. */ +export interface ControlSpline extends EntityBase { + readonly kind: "spline"; + readonly controlPoints: readonly Point[]; + /** From 1 up to `SPLINE_DEGREE_MOST`. */ + readonly degree: number; + /** One more than the control points and the degree together, none less than the one before. */ + readonly knots: readonly number[]; + /** One for each control point, each above 0. Every weight is 1 when left out. */ + readonly weights?: readonly number[]; + /** Whether it is periodic, joined smooth where it starts. Defaults to false. */ + readonly closed?: boolean; +} + +/** A spline: through fit points, or by its control points. `isFitSpline` tells the two apart. */ +export type Spline = FitSpline | ControlSpline; + +/** True for a spline through fit points. */ +export function isFitSpline(spline: Spline): spline is FitSpline { + return (spline as { readonly fitPoints?: unknown }).fitPoints !== undefined; +} + /** * A text style: the font of the texts that name it, and how wide and how slanted its characters * are drawn. It has no height, so each text keeps its own. @@ -938,6 +1015,8 @@ export type Entity = | Polyline | Circle | Arc + | Ellipse + | Spline | Text | Paragraph | Insert @@ -1520,6 +1599,77 @@ function hatchGradientCopy(given: unknown): HatchGradient { return read.gradient; } +/** What `ellipse()` takes besides what every entity does. */ +export interface EllipseOptions< + V extends DxfVersion = "R2018", + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, +> extends EntityOptions { + /** + * For an arc of the ellipse, the parameter it starts at, in degrees counterclockwise from the end + * of the major axis. Given with `endParameter` or not at all. Brought into 0 up to 360. + */ + readonly startParameter?: number; + /** For an arc of the ellipse, the parameter it ends at, in degrees. */ + readonly endParameter?: number; +} + +/** What `spline()` takes besides what every entity does. */ +export interface SplineOptions< + V extends DxfVersion = "R2018", + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, + S extends Point = Point, + E extends Point = Point, + C extends boolean = boolean, +> extends EntityOptions { + /** The direction it leaves the first point in. Worked out from the points when left out. */ + readonly startTangent?: [C] extends [true] ? typeof SPLINE_CLOSED_TANGENT : Tangent; + /** The direction it arrives at the last point in. Worked out from the points when left out. */ + readonly endTangent?: [C] extends [true] ? typeof SPLINE_CLOSED_TANGENT : Tangent; + /** True to run from the last point back to the first, smooth through it. */ + readonly closed?: C; +} + +/** What `controlSpline()` takes besides what every entity does. */ +export interface ControlSplineOptions< + V extends DxfVersion = "R2018", + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, + D extends number = number, + K extends readonly number[] = readonly number[], + C extends readonly Point[] = readonly Point[], + H extends readonly number[] = readonly number[], +> extends EntityOptions { + /** From 1 up to `SPLINE_DEGREE_MOST`. Defaults to 3. */ + readonly degree?: SplineDegree; + /** + * As many as the control points and the degree together, and one more, none less than the one + * before. Defaults to clamped uniform knots: the degree and one more of 0, then 1, 2 and on, + * and the degree and one more of the last. + */ + readonly knots?: Knots; + /** One for each control point, each above 0, for a rational spline. */ + readonly weights?: Weights; + /** + * True for a periodic spline, smooth where it joins. Without `knots`, the first `degree` + * control points are added again at the end, with uniform knots, so the curve closes on them. + */ + readonly closed?: boolean; +} + /** * A hatch's pattern as `hatch()` takes it: a `HatchPatternChoice` whose scale or spacing is greater * than 0 and not written as 0, with no field of the other kind. @@ -3615,6 +3765,173 @@ export class DrawingBuilder< }); } + /** + * An ellipse about `center`, with `majorAxis` from the center to one end of its major axis and + * `ratio` its minor radius over its major, above 0 and at most 1. With `startParameter` and + * `endParameter`, an arc of it, counterclockwise from one to the other. A parameter is not the + * angle a point is at, except at multiples of 90 degrees: see `Ellipse`. R2018 only. + * + * ```ts + * d.ellipse([10, 5], [4, 0], 0.5); + * d.ellipse([10, 5], [0, 3], 0.6, { startParameter: 0, endParameter: 180 }); + * ``` + */ + ellipse< + R extends number, + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + >( + center: Point, + majorAxis: Point, + ratio: EllipseRatio, + options: EllipseOptions = {}, + ): this { + return this.#add(DrawingBuilder.prototype.ellipse, options, () => { + if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); + const axis = pt(majorAxis); + const { startParameter, endParameter } = options; + const arc = startParameter !== undefined && endParameter !== undefined; + const start = arc ? turn(num(startParameter, "startParameter")) : startParameter; + const end = arc ? turn(num(endParameter, "endParameter")) : endParameter; + const [problem] = ellipseProblems(axis, ratio, start, end); + if (problem) refuse("geometry", capitalized(problem)); + return { + kind: "ellipse", + layer: this.#current, + center: pt(center), + majorAxis: axis, + ratio: ratio as number, + ...(arc ? { startParameter: start!, endParameter: end! } : {}), + }; + }); + } + + /** + * A spline through `fitPoints`: the cubic the leading CAD app's `SPLINE` fits through them, its + * knots spaced by the chords, with the tangents given at its ends or worked out from the points. `closed` runs it from the last + * point back to the first, smooth through it. R2018 only. + * + * ```ts + * d.spline([[0, 0], [10, 4], [20, 2], [30, 6]]); + * d.spline([[0, 0], [10, 4], [20, 2]], { startTangent: [0, 1] }); + * ``` + */ + spline< + const F extends readonly Point[], + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + const S extends Point = Point, + const E extends Point = Point, + C extends boolean = false, + >(fitPoints: FitPoints, options: SplineOptions = {}): this { + return this.#add(DrawingBuilder.prototype.spline, options, () => { + if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); + if (!Array.isArray(fitPoints)) + refuse("geometry", "A spline's fit points are a list of points"); + const o = options as SplineOptions; + const points = (fitPoints as readonly Point[]).map(pt); + const startTangent = o.startTangent === undefined ? undefined : pt(o.startTangent as Point); + const endTangent = o.endTangent === undefined ? undefined : pt(o.endTangent as Point); + const closed = o.closed === true; + const [problem] = fitSplineProblems({ + fitPoints: points, + startTangent, + endTangent, + closed, + }); + if (problem) refuse("geometry", capitalized(problem)); + return { + kind: "spline", + layer: this.#current, + fitPoints: points, + ...(startTangent ? { startTangent } : {}), + ...(endTangent ? { endTangent } : {}), + ...(closed ? { closed } : {}), + }; + }); + } + + /** + * A spline by its control points: a B-spline of `degree`, 3 unless given, with clamped uniform + * knots unless `knots` are given, rational with `weights`. `closed` makes it periodic: without + * `knots`, its first `degree` control points are added again at the end, with uniform knots, so + * it closes smooth on them. R2018 only. + * + * ```ts + * d.controlSpline([[0, 0], [5, 8], [10, 0], [15, 8]]); + * d.controlSpline([[0, 0], [0, 5], [5, 5]], { degree: 2, weights: [1, Math.SQRT1_2, 1] }); + * ``` + */ + controlSpline< + const C extends readonly Point[], + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + D extends number = 3, + const K extends readonly number[] = readonly number[], + const H extends readonly number[] = readonly number[], + >( + controlPoints: ControlPoints, + options: ControlSplineOptions = {}, + ): this { + return this.#add(DrawingBuilder.prototype.controlSpline, options, () => { + if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); + if (!Array.isArray(controlPoints)) + refuse("geometry", "A spline's control points are a list of points"); + const o = options as ControlSplineOptions; + const degree: unknown = o.degree ?? 3; + const given = (controlPoints as readonly Point[]).map(pt); + const closed = o.closed === true; + const p = typeof degree === "number" ? degree : 0; + if (Number.isInteger(p) && p >= 1 && given.length < p + 1) + refuse( + "geometry", + capitalized(controlSplineProblems({ controlPoints: given, degree, knots: [] })[0]!), + ); + const wrapped = closed && o.knots === undefined; + const points = wrapped ? [...given, ...given.slice(0, p)] : given; + const knots: readonly number[] = + (o.knots as readonly number[] | undefined) ?? + (wrapped + ? Array.from({ length: points.length + p + 1 }, (_, i) => i) + : Array.from({ length: points.length + p + 1 }, (_, i) => + Math.min(Math.max(i - p, 0), points.length - p), + )); + const givenWeights = o.weights as readonly number[] | undefined; + const weights = + givenWeights === undefined + ? undefined + : wrapped + ? [...givenWeights, ...givenWeights.slice(0, p)] + : givenWeights; + const [problem] = controlSplineProblems({ + controlPoints: points, + degree, + knots, + weights, + closed, + }); + if (problem) refuse("geometry", capitalized(problem)); + return { + kind: "spline", + layer: this.#current, + controlPoints: points, + degree: degree as number, + knots: [...knots], + ...(weights === undefined ? {} : { weights: [...weights] }), + ...(closed ? { closed } : {}), + }; + }); + } + text< H extends number = number, T extends string = string, diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index a4d2465..2eefc0d 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -56,8 +56,11 @@ import type { Units, Viewport, HatchPattern, + Spline, } from "./drawing.ts"; +import { isFitSpline } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; +import { clamped, fitSpline } from "./curves.ts"; import { nearestColorIndex } from "./svg.ts"; import { dimensionMask, @@ -112,7 +115,16 @@ import { } from "./papers.ts"; import { fontInfo, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { ID_HANDLE_SEED, validIdHandle } from "./handles.ts"; -import { dxfOnce, dxfText, fifteenDigits, fmt, readable, written, writtenAngle } from "./format.ts"; +import { + dxfOnce, + dxfText, + fifteenDigits, + fmt, + readable, + sixteenDigits, + written, + writtenAngle, +} from "./format.ts"; import { layerKey, layerZeroFirst } from "./layers.ts"; import { layoutParagraph, @@ -1194,6 +1206,84 @@ function writeParagraphAttribute( g(44, definition.lineSpacing ?? 1); } +/** A number with the 16 significant digits the leading CAD app saves a parameter with, and no exponent. */ +/** + * Writes a spline as the leading CAD app saves one. Through fit points: the cubic `fitSpline` + * fits, then the points, a closed one with its first point again at the end and the tangent where + * it joins at both ends. By control points: clamped, as that app saves every spline. + */ +function writeSpline(g: Group, e: Spline, begin: () => void): void { + begin(); + point3(g, 210, 0, 0, 1); + const tolerances = (fit: boolean) => { + g(42, "0.000000001"); + g(43, "0.0000000001"); + if (fit) g(44, "0.0000000001"); + }; + const unit = (code: number, [x, y]: Point) => { + const length = Math.hypot(x, y); + for (const [at, value] of [ + [code, x / length], + [code + 10, y / length], + ] as const) + g(at, value === 0 ? "0" : fifteenDigits(value)); + g(code + 20, 0); + }; + // Numbers the writer works out, as the leading CAD app saves them, with 16 digits. + const exactPoint = (code: number, x: number, y: number) => { + g(code, sixteenDigits(x)); + g(code + 10, sixteenDigits(y)); + g(code + 20, 0); + }; + if (isFitSpline(e)) { + const closed = e.closed === true; + // Fitted through the points as written, which a reader of the file fits through again. + const asWritten = (p: Point): Point => [written(p[0]), written(p[1])]; + const points = e.fitPoints.map(asWritten); + const fitted = fitSpline(points, "chord", e.startTangent, e.endTangent, closed); + const fit = closed ? [...points, points[0]!] : points; + const startTangent = closed ? fitted.tangent : e.startTangent; + const endTangent = closed ? fitted.tangent : e.endTangent; + // Fit by chord (32), planar (8), and 16 more for a line between two points with no tangent; + // a closed one is periodic (2) and closed (1). + const line = fit.length === 2 && !startTangent && !endTangent; + g(70, 1024 + 32 + 8 + (line ? 16 : 0) + (closed ? 3 : 0)); + g(71, 3); + g(72, fitted.knots.length); + g(73, fitted.controlPoints.length); + g(74, fit.length); + tolerances(true); + if (startTangent) unit(12, startTangent); + if (endTangent) unit(13, endTangent); + for (const knot of fitted.knots) g(40, sixteenDigits(knot)); + for (const [x, y] of fitted.controlPoints) exactPoint(10, x, y); + for (const [x, y] of fit) point(g, 11, x, y); + return; + } + // Knots are written with 16 digits, as a span may be smaller than 6 decimals hold; the control + // points and weights as written, or with 16 digits where the clamp worked them out. + const held = clamped({ + degree: e.degree, + knots: e.knots, + controlPoints: e.controlPoints.map(([x, y]): Point => [written(x), written(y)]), + ...(e.weights === undefined ? {} : { weights: e.weights.map(written) }), + }); + const worked = + held.knots.length !== e.knots.length || held.knots.some((k, i) => k !== e.knots[i]); + g(70, 8 + (held.weights ? 4 : 0) + (e.closed ? 3 : 0)); + g(71, held.degree); + g(72, held.knots.length); + g(73, held.controlPoints.length); + g(74, 0); + tolerances(false); + for (const knot of held.knots) g(40, sixteenDigits(knot)); + held.controlPoints.forEach(([x, y], i) => { + if (worked) exactPoint(10, x, y); + else point(g, 10, x, y); + if (held.weights) g(41, worked ? sixteenDigits(held.weights[i]!) : held.weights[i]!); + }); +} + /** The vertical justification of the text a paragraph attribute would be as a line. */ const TEXT_VALIGN_OF = { top: "top", middle: "middle", bottom: "bottom" } as const; @@ -1262,6 +1352,25 @@ function writeEntity( g(50, writtenAngle(e.startAngle)); g(51, writtenAngle(e.endAngle)); return; + case "ellipse": { + begin("ELLIPSE", "AcDbEllipse"); + point(g, 10, ...e.center); + point(g, 11, ...e.majorAxis); + point3(g, 210, 0, 0, 1); + g(40, e.ratio); + // The end is always past the start, by up to a turn, as the leading CAD app saves it. + const radians = (t: number) => (writtenAngle(t) * Math.PI) / 180; + const start = e.startParameter === undefined ? 0 : radians(e.startParameter); + let end = e.endParameter === undefined ? 2 * Math.PI : radians(e.endParameter); + if (end <= start) end += 2 * Math.PI; + // With 15 digits, which the app reads back as written: from 16 it keeps one a bit off. + g(41, start === 0 ? 0 : fifteenDigits(start)); + g(42, fifteenDigits(end)); + return; + } + case "spline": + writeSpline(g, e, () => begin("SPLINE", "AcDbSpline")); + return; case "paragraph": { begin("MTEXT", "AcDbMText"); // Columns: the width of them all and their height, then an embedded object after group 44, diff --git a/src/extents.ts b/src/extents.ts index 663fd9c..fde0cdc 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -30,6 +30,7 @@ import type { LeaderStyle, Point, Polyline, + Spline, Text, TextStyle, } from "./drawing.ts"; @@ -45,6 +46,8 @@ import { placer, } from "./paragraphs.ts"; import { filled } from "./shape.ts"; +import { ellipseBox, splineBox } from "./curves.ts"; +import { drawnEllipse, SplineMemo } from "./rules.ts"; type Bounds = [number, number, number, number]; @@ -301,6 +304,21 @@ export function boxer( add(e.center[0] - e.radius, e.center[1] - e.radius); add(e.center[0] + e.radius, e.center[1] + e.radius); break; + case "ellipse": { + const drawn = drawnEllipse(e); + if (!drawn) break; + const box = ellipseBox(drawn.center, drawn.majorAxis, drawn.ratio, drawn.start, drawn.end); + add(box[0], box[1]); + add(box[2], box[3]); + break; + } + case "spline": { + const box = splineBoxOf(e); + if (box === undefined) break; + add(box[0], box[1]); + add(box[2], box[3]); + break; + } case "text": { // A long value that took the place of another of its length is read again, and paid for. const again = typeof e.value === "string" && readAgain(e.value); @@ -388,6 +406,31 @@ export function boxer( } } }; + /** + * The box of a spline, from its curve, worked out once for every spline of the same lists and + * fields: within a ten-millionth of a unit, or less than a writer's rounding moves a number, of + * the curve, and never inside it. One worked out again from lists another spline read is paid for + * by the work its fit and its pieces take. + */ + const splines = new SplineMemo(); + const splineBoxes = new WeakMap(); + const splineBoxOf = (e: Spline): Bounds | undefined => { + const fields = e as unknown as Readonly>; + const drawn = splines.get(fields, (lists) => { + let cost = 0; + for (const list of lists) if (Array.isArray(list)) cost += list.length * 2; + return spend(cost); + }); + if (!drawn) return undefined; + const known = splineBoxes.get(drawn); + if (known !== undefined) return known ?? undefined; + const { degree, knots, controlPoints, weights } = drawn; + let reach = 0; + for (const [x, y] of controlPoints) reach = Math.max(reach, Math.abs(x), Math.abs(y)); + const box = splineBox(degree, knots, controlPoints, weights, 1e-7 + reach * 2 ** -44) ?? null; + splineBoxes.set(drawn, box); + return box ?? undefined; + }; /** The box of a list of points, worked out once for a long list however many hold it. */ const pointBoxes = new WeakMap(); /** The box of a hatch's list of loops, worked out once however many hatches hold the list. */ diff --git a/src/format.ts b/src/format.ts index a94191b..7c381c8 100644 --- a/src/format.ts +++ b/src/format.ts @@ -25,6 +25,17 @@ export function fifteenDigits(value: number): string { * An arc angle in degrees as the DXF writers print it: rounded to 6 decimals, * with 0 in place of an angle that rounds up to 360. */ +/** + * A number the writers work out, such as a knot or a fitted point, as they print it: 16 + * significant digits, and below a millionth 20 decimals, never with an exponent. + */ +export function sixteenDigits(value: number): string { + const kept = Number(value.toPrecision(16)); + return Math.abs(kept) < 1e-6 + ? kept.toFixed(20).replace(/0+$/, "").replace(/\.$/, "") + : String(kept); +} + export function writtenAngle(degrees: number): number { const rounded = written(degrees); return rounded >= 360 ? rounded - 360 : rounded; diff --git a/src/index.ts b/src/index.ts index 847f9a2..dbf5af7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -70,6 +70,14 @@ export { type BlockOptions, type Circle, type CloudOptions, + type ControlSplineOptions, + type EllipseOptions, + type SplineOptions, + type ControlSpline, + type Ellipse, + type FitSpline, + isFitSpline, + type Spline, type DimensionStyle, type DiameterDimension, type DiameterDimensionOptions, @@ -203,6 +211,18 @@ export { type GradientWritten, } from "./fills.ts"; export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; +export { + clamped, + ellipseBox, + ellipsePoint, + fitSpline, + splineBox, + splinePoint, + type BSpline, + type CurveBox, + type FittedSpline, + type KnotSpacing, +} from "./curves.ts"; export { FONT_METRICS, FONT_METRICS_RANGES, type FontMetrics } from "./font-metrics.ts"; export { capHeightOf, FONTS, type Font, type FontInfo } from "./fonts.ts"; export { idHandle } from "./handles.ts"; @@ -302,16 +322,20 @@ export type { ArrowheadOf, AttributeTag, BlockName, + ControlPoints, Description, DimensionAffix, DimensionPrefix, DimensionScale, DonutHole, DimensionStyleName, + EllipseRatio, DimensionText, EntityId, + FitPoints, FontOf, InsertScale, + Knots, LayerColor, LayerLinetypeName, LayerName, @@ -341,8 +365,11 @@ export type { Positive, Precision, Ratio, + SplineDegree, + Tangent, TextGap, TextStyleName, + Weights, WidthFactor, XrefPath, } from "./rules.ts"; @@ -354,6 +381,8 @@ export { LEADER_SIDES, LEADER_VERTICAL_ATTACHMENTS, LINE_SPACING_RANGE, + SPLINE_DEGREE_MOST, + SPLINE_ITEMS, XREF_DEPTH, } from "./rules.ts"; export { BUILT_IN_STANDARD, defineStandard, type BuiltInStandard } from "./standard/define.ts"; @@ -394,6 +423,8 @@ export { READ_FORMAT, type DrawingRead, type ReadArc, + type ReadEllipse, + type ReadSpline, type ReadAttribute, type ReadAttributeDefinition, type ReadAttributeParagraph, diff --git a/src/leaders.ts b/src/leaders.ts index f9bfa8b..9f78e74 100644 --- a/src/leaders.ts +++ b/src/leaders.ts @@ -36,8 +36,11 @@ import { LEADER_SHAFT_LENGTH, leaderStyleNameProblem, pictureNumberProblem, + drawnEllipse, + drawnSpline, } from "./rules.ts"; import { filled, Strings } from "./shape.ts"; +import { ellipsePoint, splinePolyline, unturned } from "./curves.ts"; /** The shortest line of a note that `leaderRepeats` tells apart by its value. */ const LONG = 256; @@ -577,7 +580,30 @@ function outlineOf(block: Block, findBlock?: (name: string) => Block | undefined } } else if (e.kind === "circle") round(e.center, num(e.radius)); else if (e.kind === "arc") round(e.center, num(e.radius), num(e.startAngle), num(e.endAngle)); - else if (e.kind === "insert" && depth < OUTLINE_DEPTH && typeof e.block === "string") { + else if (e.kind === "ellipse" || e.kind === "spline") { + // A curve as the points of 32 steps a turn of an ellipse, or 8 a piece of a spline. + const fields = e as unknown as Readonly>; + const lists = [fields.fitPoints, fields.controlPoints, fields.knots, fields.weights]; + read += lists.reduce((n: number, l) => n + (Array.isArray(l) ? l.length : 0), 0); + if (read > OUTLINE_ITEMS) break; + let points: Point[] = []; + if (e.kind === "ellipse") { + const d = drawnEllipse(e); + if (d) { + const from = d.start ?? 0; + const turn = + d.start === undefined ? 2 * Math.PI : unturned(d.end! - from) || 2 * Math.PI; + points = Array.from({ length: 33 }, (_, k) => + ellipsePoint(d.center, d.majorAxis, d.ratio, from + (turn * k) / 32), + ); + } + } else { + const d = drawnSpline(fields); + if (d) points = splinePolyline(d.degree, d.knots, d.controlPoints, d.weights, 8); + } + read += points.length; + for (let i = 1; i < points.length; i++) segment(map(points[i - 1]!), map(points[i]!)); + } else if (e.kind === "insert" && depth < OUTLINE_DEPTH && typeof e.block === "string") { const nested = findBlock?.(e.block); if (nested === undefined || open.has(nested)) continue; const [sx, sy] = Array.isArray(e.scale) ? e.scale : [1, 1]; diff --git a/src/lint.ts b/src/lint.ts index 24f91c6..4846568 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -51,6 +51,7 @@ import type { TextStyle, Xref, } from "./drawing.ts"; +import { isFitSpline } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; import { exactKey, imagePathKey, imageReactorHandle, imageVectors } from "./images.ts"; import { written } from "./format.ts"; @@ -141,6 +142,9 @@ import { linetypeProblem, linetypeScaleProblem, R12_ONLY, + controlSplineProblems, + ellipseProblems, + fitSplineProblems, magnitudeProblem, polylineSidesProblems, paperProblem, @@ -1885,7 +1889,8 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) entity.kind === "image" || entity.kind === "paragraph" || entity.kind === "hatch" || - entity.kind === "wipeout") + entity.kind === "wipeout" || + entity.kind === "spline") ) { let cost = 0; const columns: unknown = entity.kind === "paragraph" ? entity.columns : undefined; @@ -1897,17 +1902,21 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ? [isObject(columns) ? columns.heights : undefined] : entity.kind === "wipeout" ? [entity.points] - : entity.kind === "hatch" - ? [ - entity.loops, - ...loops.flatMap((loop) => - isObject(loop) ? [loop.points, loop.bulges] : [], - ), - ] - : [entity.points, entity.bulges, entity.widths]; + : entity.kind === "spline" + ? [entity.fitPoints, entity.controlPoints, entity.knots, entity.weights] + : entity.kind === "hatch" + ? [ + entity.loops, + ...loops.flatMap((loop) => + isObject(loop) ? [loop.points, loop.bulges] : [], + ), + ] + : [entity.points, entity.bulges, entity.widths]; + // A spline's fit is worked out again from its lists, which takes more for each point. + const per = entity.kind === "spline" ? 2 : 8; for (const list of lists) { if (Array.isArray(list) && list.length >= FREE && again(list)) - cost += Math.floor(list.length / 8); + cost += Math.floor(list.length / per); } if (cost > 0 && !spend(cost, here)) return; } @@ -2078,6 +2087,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } lintImage(entity, add, problems.length === 0, named, here); } + if (r12 && (entity.kind === "ellipse" || entity.kind === "spline")) { + add("geometry", "error", R12_ONLY.curves); + return; + } if (entity.kind === "hatch" || entity.kind === "wipeout") { if (r12) { add(entity.kind, "error", R12_ONLY.hatches); @@ -2607,9 +2620,9 @@ function asText(definition: AttributeDefinition): Text { } /** - * True for an entity whose box can cost anything: an insert, a dimension, a leader, a text too - * long for a table of strings to keep, and a polyline that may have an arc or a width, whose box - * pays for a long list read again. + * True for an entity whose box can cost anything: an insert, a dimension, a leader, a spline, a + * text too long for a table of strings to keep, and a polyline that may have an arc or a width, + * whose box pays for a long list read again. */ function costsBoxes(e: Readonly>): boolean { const kind = e.kind; @@ -2621,6 +2634,7 @@ function costsBoxes(e: Readonly>): boolean { } return ( kind === "insert" || + kind === "spline" || kind === "leader" || kind === "linear-dimension" || kind === "aligned-dimension" || @@ -2768,6 +2782,14 @@ function geometryProblems(e: Entity): string[] { }); break; } + case "ellipse": + finite("its center and major axis", ...e.center, ...e.majorAxis); + if (out.length > 0) break; + out.push(...ellipseProblems(e.majorAxis, e.ratio, e.startParameter, e.endParameter)); + break; + case "spline": + out.push(...(isFitSpline(e) ? fitSplineProblems(e) : controlSplineProblems(e))); + break; case "wipeout": if (e.points.length < 3) out.push(WIPEOUT_POINTS); if (!e.points.every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) { diff --git a/src/pdf.ts b/src/pdf.ts index b0009a7..2d8de82 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -875,7 +875,7 @@ function arcCurves( } /** - * The pieces of a path's `d`, which `toSVG` writes with `M`, `L` and `A` alone, on a page that + * The pieces of a path's `d`, which `toSVG` writes with `M`, `L`, `C`, `A` and `Z` alone, on a page that * draws one unit `scale` points long. */ function pathPieces(d: string, where: string, scale: number): Piece[] { @@ -901,6 +901,11 @@ function pathPieces(d: string, where: string, scale: number): Piece[] { // A hatch's loop closes back to where it started. pieces.push({ kind: "close" }); at = start; + } else if (command === "C") { + // A spline's Bézier pieces. + const [x1, y1, x2, y2, x, y] = numbers(6) as number[]; + at = [x!, y!]; + pieces.push({ kind: "curve", c1: [x1!, y1!], c2: [x2!, y2!], to: at }); } else if (command === "A") { const [rx, ry, turn, large, sweep, x, y] = numbers(7) as number[]; const to: [number, number] = [x!, y!]; diff --git a/src/read/check.ts b/src/read/check.ts index c22db66..3db05be 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -155,6 +155,30 @@ const ENTITY: Readonly> = { start: "number", end: "number", }, + ellipse: { + ...BASE, + kind: { oneOf: ["ellipse"] }, + center: "point", + majorAxis: "point", + ratio: "number", + "startParameter?": "number", + "endParameter?": "number", + }, + spline: { + ...BASE, + kind: { oneOf: ["spline"] }, + degree: "count", + knots: { list: "number" }, + controlPoints: { list: "point" }, + "weights?": { list: "number" }, + closed: "boolean", + "periodic?": "boolean", + "fitPoints?": { list: "point" }, + "startTangent?": "point", + "endTangent?": "point", + "fitTolerance?": "number", + "knotSpacing?": { oneOf: ["chord", "square-root", "uniform"] }, + }, text: { ...BASE, ...PLACEMENT, kind: { oneOf: ["text"] }, value: "string" }, insert: INSERT, mtext: { diff --git a/src/read/dxf.ts b/src/read/dxf.ts index a35205d..0376af9 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -187,6 +187,7 @@ const BLOCK_READS = new Set([ "ATTRIB", "CIRCLE", "DIMENSION", + "ELLIPSE", "HATCH", "IMAGE", "INSERT", @@ -200,6 +201,7 @@ const BLOCK_READS = new Set([ "POLYLINE", "SEQEND", "SOLID", + "SPLINE", "TEXT", "VERTEX", "VIEWPORT", diff --git a/src/read/entities.ts b/src/read/entities.ts index c7326bf..ea7dd3a 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -224,6 +224,10 @@ export function readingOf( end: turned(num(r, face === -1 ? 50 : 51) ?? 0, face), }, }; + case "ELLIPSE": + return ellipse(r, base, face); + case "SPLINE": + return spline(r, base, face); case "LWPOLYLINE": return lwpolyline(r, base, face); case "TEXT": { @@ -530,6 +534,118 @@ function hatchGradient( }; } +/** + * An ellipse: its center and axis are in the world's coordinates whatever its extrusion, and seen + * from below its parameters run clockwise, so its arc from s to e is the arc from -e to -s of the + * ellipse seen from above. One whose ratio is outside (0, 1] or whose axis has no length is broken. + */ +function ellipse(r: Rec, base: ReadEntityBase, face: Facing): Reading { + if (face === 0) return { other: "ELLIPSE in 3D" }; + const s = inSubclass(r, "AcDbEllipse"); + if (Math.abs(num(s, 30) ?? 0) > 1e-9 || Math.abs(num(s, 31) ?? 0) > 1e-9) + return { other: "ELLIPSE in 3D" }; + const majorAxis = point(s, 11); + const ratio = num(s, 40) ?? 1; + if (!(ratio > 0 && ratio <= 1) || (majorAxis[0] === 0 && majorAxis[1] === 0)) + return { malformed: "ELLIPSE with a ratio outside 0 to 1 or an axis of no length" }; + const [s0, e0] = [num(s, 41) ?? 0, num(s, 42) ?? 2 * Math.PI]; + const whole = Math.abs(e0 - s0) >= 2 * Math.PI - 1e-9 || s0 === e0; + const inDegrees = (t: number) => degrees((t * 180) / Math.PI); + const [start, end] = face === -1 ? [-e0, -s0] : [s0, e0]; + return { + entity: { + ...base, + kind: "ellipse", + center: point(s, 10), + majorAxis, + ratio, + ...(whole ? {} : { startParameter: inDegrees(start), endParameter: inDegrees(end) }), + }, + }; +} + +/** The highest degree of a spline read. */ +const SPLINE_DEGREE_READ = 11; + +/** + * A spline as the file holds it, in the world's coordinates whatever its extrusion. One whose + * counts disagree with its groups, whose degree is out of range, or whose knots do not fit its + * control points is broken; one with a point off the plane is counted. + */ +function spline(r: Rec, base: ReadEntityBase, face: Facing): Reading { + if (face === 0) return { other: "SPLINE in 3D" }; + const s = inSubclass(r, "AcDbSpline"); + const flags = num(s, 70) ?? 0; + const degree = num(s, 71) ?? 3; + const knots: number[] = []; + const weights: number[] = []; + const controlPoints: Point[] = []; + const fitPoints: Point[] = []; + let flat = true; + for (let i = 0; i < s.codes.length; i++) { + const code = s.codes[i]!; + const value = Number(s.values[i]); + if (code === 40) knots.push(value); + // Weights count only for a spline marked rational, as the leading CAD app reads them. + else if (code === 41 && (flags & 4) !== 0) weights.push(value); + else if (code === 10 || code === 11) { + const y = s.codes[i + 1] === code + 10 ? Number(s.values[i + 1]) : 0; + const z = s.codes[i + 2] === code + 20 ? Number(s.values[i + 2]) : 0; + if (Math.abs(z) > 1e-9) flat = false; + (code === 10 ? controlPoints : fitPoints).push([value, y]); + } + } + if (!flat) return { other: "SPLINE in 3D" }; + const counted = (code: number, list: readonly unknown[]) => (num(s, code) ?? 0) === list.length; + const broken = + !Number.isInteger(degree) || + degree < 1 || + degree > SPLINE_DEGREE_READ || + !counted(72, knots) || + !counted(73, controlPoints) || + !counted(74, fitPoints) || + (weights.length > 0 && weights.length !== controlPoints.length) || + (controlPoints.length > 0 && knots.length !== controlPoints.length + degree + 1) || + (controlPoints.length === 0 && fitPoints.length < 2); + if (broken) return { malformed: "SPLINE whose counts disagree with its groups or its degree" }; + // A fit closed by its first point again at its end gives that point once. + const [head, tail] = [fitPoints[0], fitPoints.at(-1)]; + const repeated = + (flags & 1) !== 0 && fitPoints.length > 2 && head![0] === tail![0] && head![1] === tail![1]; + const tangent = (code: number) => + first(s, code) === undefined + ? {} + : { [code === 12 ? "startTangent" : "endTangent"]: point(s, code) }; + const spacing = + (flags & 1024) === 0 + ? undefined + : (flags & 64) !== 0 + ? "square-root" + : (flags & 128) !== 0 + ? "uniform" + : (flags & 32) !== 0 + ? "chord" + : undefined; + const tolerance = num(s, 44); + return { + entity: { + ...base, + kind: "spline", + degree, + knots, + controlPoints, + ...(weights.length > 0 && { weights }), + closed: (flags & 1) !== 0, + ...((flags & 2) !== 0 && { periodic: true as const }), + ...(fitPoints.length > 0 && { fitPoints: repeated ? fitPoints.slice(0, -1) : fitPoints }), + ...tangent(12), + ...tangent(13), + ...(fitPoints.length > 0 && tolerance !== undefined && { fitTolerance: tolerance }), + ...(spacing !== undefined && { knotSpacing: spacing }), + }, + }; +} + /** * A wipeout: its clip, which the file holds in the axes of its picture of one pixel, in the * world's coordinates, a polygon without its first point again at its end, or a rectangle's four @@ -1183,7 +1299,16 @@ export function costOf(e: ReadEntity): number { return own + 2; case "circle": case "arc": + case "ellipse": return own + 1; + case "spline": + return ( + own + + e.knots.length + + e.controlPoints.length + + (e.weights?.length ?? 0) + + (e.fitPoints?.length ?? 0) + ); case "polyline": return own + e.points.length + (e.bulges?.length ?? 0) + (e.widths?.length ?? 0); case "solid": diff --git a/src/read/model.ts b/src/read/model.ts index ffc5615..45f9d55 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -4,6 +4,7 @@ // written back. import type { ParagraphColumns } from "../paragraphs.ts"; import type { Point } from "../drawing.ts"; +import type { KnotSpacing } from "../curves.ts"; /** The format of a `DrawingRead`. A reader gives the format it was built for. */ export const READ_FORMAT = 0; @@ -773,12 +774,54 @@ export interface ReadWipeout extends ReadEntityBase { readonly points: readonly Point[]; } +/** + * An ellipse, or an arc of one, as `Ellipse` holds it: in the world's coordinates, with its + * parameters in degrees counterclockwise. One the file holds seen from below, which runs its + * parameters clockwise, is read as the ellipse it draws seen from above. + */ +export interface ReadEllipse extends ReadEntityBase { + readonly kind: "ellipse"; + readonly center: Point; + readonly majorAxis: Point; + readonly ratio: number; + /** For an arc, from 0 up to 360. Left out, with `endParameter`, for a whole ellipse. */ + readonly startParameter?: number; + readonly endParameter?: number; +} + +/** + * A spline as the file holds it: its B-spline, and the fit points and what the fit took where the + * file holds them. A spline through fit points that the file closes by repeating its first fit + * point is `closed`, and its fit points leave the repeat out. + */ +export interface ReadSpline extends ReadEntityBase { + readonly kind: "spline"; + readonly degree: number; + readonly knots: readonly number[]; + /** In the world's coordinates, as the file holds them. None for one held by fit points alone. */ + readonly controlPoints: readonly Point[]; + /** One for each control point, for a rational spline. */ + readonly weights?: readonly number[]; + /** Group 70's closed bit, or for fit points, a first point repeated at the end. */ + readonly closed: boolean; + /** Group 70's periodic bit, where it is set. */ + readonly periodic?: true; + readonly fitPoints?: readonly Point[]; + readonly startTangent?: Point; + readonly endTangent?: Point; + readonly fitTolerance?: number; + /** How the knots of a fit are spaced, where the file says. */ + readonly knotSpacing?: KnotSpacing; +} + /** What a space or a block draws, of the kinds the writers write. */ export type ReadEntity = | ReadLine | ReadPolyline | ReadCircle | ReadArc + | ReadEllipse + | ReadSpline | ReadText | ReadInsert | ReadMtext diff --git a/src/rules.ts b/src/rules.ts index f4602bd..8009468 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -5,6 +5,7 @@ // That app discards the whole drawing over most names that break the name rules. import type { XrefProblem } from "./blocks.ts"; import type { DxfVersion, HatchGradient, Point, Rgb, Units } from "./drawing.ts"; +import { clamped, fitSpline, type FittedSpline } from "./curves.ts"; import type { PaperUnit } from "./paper.ts"; import { paperInfo, PLOT_STYLE_TABLES, type Paper, type PlotStyleTable } from "./papers.ts"; import { @@ -30,7 +31,7 @@ import { type LeaderArrowhead, } from "./arrowheads.ts"; import { isPaperUnit, isUnits, modelLength } from "./units.ts"; -import { isTooLarge, written, writtenAngle } from "./format.ts"; +import { isTooLarge, sixteenDigits, written, writtenAngle } from "./format.ts"; import { fontInfo, STANDARD_TEXT_STYLE, type Font } from "./fonts.ts"; import { parseParagraph, @@ -184,6 +185,8 @@ const LINE_SPACING = "A paragraph's line spacing is a factor from 0.25 to 4"; const R12_IMAGES = 'tsdraft writes no images to R12 drawings. Use DXF version "R2018" for an image'; const R12_HATCHES = 'tsdraft writes no hatches or wipeouts to R12 drawings. Use DXF version "R2018" for a fill'; +const R12_CURVES = + 'tsdraft writes no ellipses or splines to R12 drawings. Use DXF version "R2018" for a curve'; const IMAGE_PATH_EMPTY = "An image's path cannot be empty. The leading CAD app finds no file by it"; const IMAGE_PATH_ABSOLUTE = 'An image\'s path must start from the folder of the drawing\'s file, as "aerial.png" and "../images/aerial.png" do, and cannot start with /, \\ or a drive such as C:. The leading CAD app looks for the file of an absolute path in that folder alone, and on another machine finds none'; @@ -484,6 +487,130 @@ type AboveZero = number extends N ? Message : N; +/** + * Resolves to `N` when it is an ellipse's ratio that is above 0 and at most 1 once written, and + * to the error message otherwise. + */ +export type EllipseRatio = number extends N + ? N + : `${N}` extends "1" | `1.000000${RoundsDown}${string}` + ? N + : `${N}` extends `-${string}` | "0" + ? typeof ELLIPSE_RATIO + : WrittenAsZero<`${N}`> extends true + ? typeof ELLIPSE_RATIO + : `${N}` extends `0.${string}` | `${string}e-${string}` + ? N + : typeof ELLIPSE_RATIO; + +type SplineDegrees = Exclude, 0> | typeof SPLINE_DEGREE_MOST; + +/** Resolves to `D` when it is a spline's degree, and to the error message otherwise. */ +export type SplineDegree = number extends D + ? D + : D extends SplineDegrees + ? D + : typeof SPLINE_DEGREE; + +/** True for two points whose coordinates are the same literals. */ +type SamePoint = number extends A[0] | A[1] | B[0] | B[1] + ? false + : [A[0], A[1]] extends [B[0], B[1]] + ? true + : false; + +/** True when two points side by side are the same literals. */ +type SideBySide

= P extends readonly [ + infer A extends Point, + infer B extends Point, + ...infer Rest extends readonly Point[], +] + ? SamePoint extends true + ? true + : SideBySide + : false; + +/** + * Resolves to `P` when it is fit points a spline can pass through, and to the error message + * otherwise: 2 or more, no two side by side the same. Points the same once written but not as + * literals, and a closed spline's 3, are checked when the code runs. + */ +export type FitPoints

= number extends P["length"] + ? P + : P["length"] extends 0 | 1 + ? typeof SPLINE_FIT_POINTS + : SideBySide

extends true + ? typeof SPLINE_FIT_SAME + : P; + +/** Resolves to `T` when it is a tangent with a direction, and to the error message otherwise. */ +export type Tangent = number extends T[0] | T[1] + ? T + : [T[0], T[1]] extends [0, 0] + ? typeof SPLINE_TANGENT_ZERO + : T; + +type Tuple = A["length"] extends N + ? A + : Tuple; + +/** + * Resolves to `P` when a spline of degree `D` has enough control points, at least one more than + * its degree, and to the error message otherwise. + */ +export type ControlPoints

= number extends + | P["length"] + | D + ? P + : D extends SplineDegrees + ? P extends readonly [...Tuple, unknown, ...unknown[]] + ? P + : typeof SPLINE_CONTROL_POINTS + : P; + +/** + * Resolves to `K` when it is as many knots as a spline of the control points `P` and degree `D` + * takes, and to the error message otherwise. Whether they decrease is checked when the code runs. + */ +export type Knots< + K extends readonly number[], + P extends readonly Point[], + D extends number, +> = number extends K["length"] | P["length"] | D + ? K + : D extends SplineDegrees + ? K["length"] extends [...Tuple, ...Tuple, unknown]["length"] + ? K + : typeof SPLINE_KNOT_COUNT + : K; + +/** True when no weight of `W` is a literal of 0 or less, or one written as 0. */ +type WeightsAbove0 = W extends readonly [ + infer A extends number, + ...infer Rest extends readonly number[], +] + ? number extends A + ? WeightsAbove0 + : `${A}` extends `-${string}` | "0" + ? false + : WrittenAsZero<`${A}`> extends true + ? false + : WeightsAbove0 + : true; + +/** + * Resolves to `W` when it is one weight above 0 for each control point of `P`, and to the error + * message otherwise. + */ +export type Weights = + WeightsAbove0 extends true + ? number extends W["length"] | P["length"] + ? W + : W["length"] extends P["length"] + ? W + : typeof SPLINE_WEIGHTS + : typeof SPLINE_WEIGHTS; + /** Resolves to `N` when it is a length on paper, and to the error message otherwise. */ export type PaperLength = AboveZero; @@ -1696,8 +1823,414 @@ export const R12_ONLY = { paragraphs: R12_PARAGRAPHS, images: R12_IMAGES, hatches: R12_HATCHES, + curves: R12_CURVES, } as const; +/** The highest degree of a spline by its control points. */ +export const SPLINE_DEGREE_MOST = 11; + +/** The most knots a spline holds, and so control points and fit points: a file holds each count as a 16-bit integer. */ +export const SPLINE_ITEMS = 32_767; + +/** What is wrong with an ellipse's ratio. */ +export const ELLIPSE_RATIO = + "an ellipse's ratio, its minor radius over its major, must be above 0 and at most 1 once rounded to the 6 decimals tsdraft writes"; + +/** What is wrong with an ellipse whose major axis has no length. */ +export const ELLIPSE_AXIS = + "an ellipse's major axis must not be [0, 0] once rounded to the 6 decimals tsdraft writes"; + +/** What is wrong with an ellipse that has one parameter of an arc and not the other. */ +export const ELLIPSE_PARAMETERS_PAIR = + "an ellipse takes startParameter and endParameter together, for an arc of it, or neither, for the whole ellipse"; + +/** What is wrong with an arc of an ellipse whose parameters are out of range. */ +export const ELLIPSE_PARAMETERS_RANGE = "an ellipse's parameters must be from 0 up to 360"; + +/** What is wrong with an arc of an ellipse whose parameters are one. */ +export const ELLIPSE_PARAMETERS_SAME = + "an ellipse's start and end parameters must differ once rounded to the 6 decimals tsdraft writes. Leave both out for the whole ellipse"; + +/** What is wrong with a spline of too few fit points. */ +export const SPLINE_FIT_POINTS = + "a spline through fit points needs at least 2 of them, and 3 when it is closed"; + +/** What is wrong with two fit points side by side that are one. */ +export const SPLINE_FIT_SAME = + "two fit points side by side, and the last and the first of a closed spline, must differ once rounded to the 6 decimals tsdraft writes"; + +/** What is wrong with a tangent of no direction. */ +export const SPLINE_TANGENT_ZERO = + "a spline's tangent must not be [0, 0] once rounded to the 6 decimals tsdraft writes: it gives no direction"; + +/** What is wrong with a closed spline given a tangent. */ +export const SPLINE_CLOSED_TANGENT = + "a closed spline takes no tangents: it is smooth where it joins"; + +/** What is wrong with a spline's degree. */ +export const SPLINE_DEGREE = `a spline's degree is a whole number from 1 to ${SPLINE_DEGREE_MOST}`; + +/** What is wrong with a spline of too few control points for its degree. */ +export const SPLINE_CONTROL_POINTS = + "a spline needs at least one more control point than its degree"; + +/** What is wrong with a spline of the wrong count of knots. */ +export const SPLINE_KNOT_COUNT = + "a spline has as many knots as its control points and its degree together, and one more"; + +/** What is wrong with a spline's knots. */ +export const SPLINE_KNOTS = + "a spline's knots must never decrease, and the ones it runs over, from the knot at its degree to the knot at its count of control points, must not all be equal, and two that differ must still differ in the 16 digits tsdraft writes"; + +/** What is wrong with a closed spline by its control points that does not close. */ +export const SPLINE_OPEN_CLOSED = + "a closed spline must end where it starts, leaving it the way it arrives: its knots and control points give a curve that does not, which CAD programs hold as closed all the same"; + +/** What is wrong with a spline's weights. */ +export const SPLINE_WEIGHTS = + "a spline has one weight for each control point, each above 0 once rounded to the 6 decimals tsdraft writes"; + +/** What is wrong with a spline of more knots, control points or fit points than a file holds. */ +export const SPLINE_MANY = `a spline holds at most ${SPLINE_ITEMS.toLocaleString("en-US")} knots, and a spline through fit points takes 6 more knots than it has points, 7 when it is closed: a file holds each count as a 16-bit integer`; + +/** What is wrong with a spline through fit points whose curve reaches past what a file holds. */ +export const SPLINE_FIT_DRAWN = + "the spline fitted through its points has a control point of 1e100 or more in size, which the leading CAD app reads wrongly from DXF. Give the points closer together"; + +/** + * What is wrong with an ellipse's ratio, axis and parameters, each once. Its center and axis are + * checked as points apart. + */ +export function ellipseProblems( + majorAxis: Point, + ratio: unknown, + startParameter: unknown, + endParameter: unknown, +): string[] { + const out: string[] = []; + if (typeof ratio !== "number" || !(ratio > 0) || written(ratio) === 0 || written(ratio) > 1) { + out.push(ELLIPSE_RATIO); + } + if (written(majorAxis[0]) === 0 && written(majorAxis[1]) === 0) out.push(ELLIPSE_AXIS); + if ((startParameter === undefined) !== (endParameter === undefined)) { + out.push(ELLIPSE_PARAMETERS_PAIR); + } else if (startParameter !== undefined) { + const inRange = (t: unknown): t is number => + typeof t === "number" && Number.isFinite(t) && t >= 0 && t < 360; + if (!inRange(startParameter) || !inRange(endParameter)) out.push(ELLIPSE_PARAMETERS_RANGE); + else if (writtenAngle(startParameter) === writtenAngle(endParameter)) + out.push(ELLIPSE_PARAMETERS_SAME); + } + return out; +} + +/** An ellipse as it draws: its parameters in radians, for an arc of it. */ +export interface DrawnEllipse { + readonly center: Point; + readonly majorAxis: Point; + readonly ratio: number; + readonly start?: number; + readonly end?: number; +} + +/** True for a point of two finite numbers under 1e100. */ +function isKeptPoint(value: unknown): value is Point { + if (!Array.isArray(value) || value.length !== 2) return false; + const [x, y]: unknown[] = value; + return ( + typeof x === "number" && + typeof y === "number" && + Number.isFinite(x) && + Number.isFinite(y) && + !isTooLarge(x) && + !isTooLarge(y) + ); +} + +/** + * What an ellipse draws, or undefined for one of the wrong shape or that `lint` refuses, which + * the pictures and the extents leave out. + */ +export function drawnEllipse(e: { + readonly center: unknown; + readonly majorAxis: unknown; + readonly ratio: unknown; + readonly startParameter?: unknown; + readonly endParameter?: unknown; +}): DrawnEllipse | undefined { + const { center, majorAxis, ratio, startParameter: start, endParameter: end } = e; + if (!isKeptPoint(center) || !isKeptPoint(majorAxis)) return undefined; + if (ellipseProblems(majorAxis, ratio, start, end).length > 0) return undefined; + const radians = (t: number) => (writtenAngle(t) * Math.PI) / 180; + return { + center, + majorAxis, + ratio: ratio as number, + ...(start === undefined + ? {} + : { start: radians(start as number), end: radians(end as number) }), + }; +} + +/** A spline as the B-spline it draws. */ +export interface DrawnSpline { + readonly degree: number; + readonly knots: readonly number[]; + readonly controlPoints: readonly Point[]; + readonly weights?: readonly number[]; + /** True for a spline that closes, which a pattern of dashes goes round as a circle's does. */ + readonly closed: boolean; +} + +/** The items of a list of at most `SPLINE_ITEMS` that each pass `is`, or undefined. */ +function listOf(value: unknown, is: (item: unknown) => item is T): readonly T[] | undefined { + if (!Array.isArray(value) || value.length > SPLINE_ITEMS) return undefined; + for (let i = 0; i < value.length; i++) if (!is(value[i])) return undefined; + return value as readonly T[]; +} + +const isNumber = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value); + +/** + * The B-spline a spline draws, or undefined for one of the wrong shape or that `lint` refuses, + * which the pictures and the extents leave out. A spline through fit points is the one + * `fitSpline` fits. Each list is read once, and none past the count a file holds. + */ +export function drawnSpline(e: Readonly>): DrawnSpline | undefined { + const closed = e.closed === true; + if (e.fitPoints !== undefined) { + const fitPoints = listOf(e.fitPoints, isKeptPoint); + const tangent = (t: unknown) => (t === undefined || isKeptPoint(t) ? t : null); + const [startTangent, endTangent] = [tangent(e.startTangent), tangent(e.endTangent)]; + if (fitPoints === undefined || startTangent === null || endTangent === null) return undefined; + const fields = { fitPoints, startTangent, endTangent, closed }; + const { problems, fitted } = checkFit(fields); + if (problems.length > 0 || !fitted) return undefined; + return { degree: 3, knots: fitted.knots, controlPoints: fitted.controlPoints, closed }; + } + const controlPoints = listOf(e.controlPoints, isKeptPoint); + const knots = listOf(e.knots, isNumber); + const weights = e.weights === undefined ? undefined : listOf(e.weights, isNumber); + if (controlPoints === undefined || knots === undefined) return undefined; + if (e.weights !== undefined && weights === undefined) return undefined; + const fields = { controlPoints, degree: e.degree, knots, weights, closed: e.closed }; + if (controlSplineProblems(fields).length > 0) return undefined; + return { + degree: e.degree as number, + knots, + controlPoints, + ...(weights === undefined ? {} : { weights }), + closed, + }; +} + +/** + * The drawn spline of each spline a walk meets, worked out once for every spline that holds the + * same lists and the same other fields, however many objects hold them. `again` is told the lists + * of one worked out anew that another spline read before, for the walk to pay for them, and says + * whether there was room to: without it, the spline is not worked out. + */ +export class SplineMemo { + readonly #ids = new WeakMap(); + #next = 1; + readonly #byList = new WeakMap>(); + readonly #read = new WeakSet(); + + get( + e: Readonly>, + again: (lists: readonly object[]) => boolean, + ): DrawnSpline | undefined { + const fit = e.fitPoints !== undefined; + const list = fit ? e.fitPoints : e.controlPoints; + if (typeof list !== "object" || list === null) return undefined; + const id = (value: unknown): string => { + if (typeof value !== "object" || value === null) return typeof value; + let found = this.#ids.get(value); + if (found === undefined) this.#ids.set(value, (found = this.#next++)); + return String(found); + }; + const point = (t: unknown): string => + t === undefined ? "-" : isKeptPoint(t) ? `${t[0]},${t[1]}` : "x"; + const key = fit + ? `f ${e.closed === true} ${point(e.startTangent)} ${point(e.endTangent)}` + : `c ${e.closed === true} ${typeof e.degree === "number" ? e.degree : "x"} ${id(e.knots)} ${id(e.weights)}`; + let byKey = this.#byList.get(list); + if (!byKey) this.#byList.set(list, (byKey = new Map())); + const known = byKey.get(key); + if (known !== undefined) return known ?? undefined; + const lists = [list, e.knots, e.weights].filter( + (l): l is object => typeof l === "object" && l !== null, + ); + const seen = lists.filter((l) => this.#read.has(l)); + for (const l of lists) this.#read.add(l); + if (seen.length > 0 && !again(seen)) return undefined; + const drawn = drawnSpline(e) ?? null; + byKey.set(key, drawn); + return drawn ?? undefined; + } +} + +/** What is wrong with a list of points of a curve, which the shape has found to be points. */ +function curvePointsProblem(points: readonly Point[], what: string): string | undefined { + for (const [x, y] of points) { + if (!Number.isFinite(x) || !Number.isFinite(y)) return `its ${what} must be finite numbers`; + } + for (const [x, y] of points) { + const problem = magnitudeProblem(x) ?? magnitudeProblem(y); + if (problem) return `its ${what}: ${problem}`; + } + return undefined; +} + +/** The fields of a spline through fit points, as the checks read them. */ +interface FitFields { + readonly fitPoints: readonly Point[]; + readonly startTangent?: Point | undefined; + readonly endTangent?: Point | undefined; + readonly closed?: boolean | undefined; +} + +/** + * What is wrong with a spline through fit points. Its points are read once, and never past the + * count a file holds. + */ +export function fitSplineProblems(spline: FitFields): string[] { + return checkFit(spline).problems; +} + +/** What is wrong with a spline through fit points, and, when nothing is, its fit. */ +function checkFit(spline: FitFields): { problems: string[]; fitted?: FittedSpline } { + const { fitPoints: points, closed } = spline; + const n = points.length; + if (n + (closed ? 7 : 6) > SPLINE_ITEMS) return { problems: [SPLINE_MANY] }; + const out: string[] = []; + if (n < (closed ? 3 : 2)) out.push(SPLINE_FIT_POINTS); + const problem = curvePointsProblem(points, "fit points"); + if (problem) out.push(problem); + else { + // Two numbers more than a millionth apart are never one once written. + const same = (a: Point, b: Point) => + Math.abs(a[0] - b[0]) <= 2e-6 && + Math.abs(a[1] - b[1]) <= 2e-6 && + written(a[0]) === written(b[0]) && + written(a[1]) === written(b[1]); + let found = closed && n > 1 && same(points[0]!, points[n - 1]!); + for (let i = 1; i < n && !found; i++) found = same(points[i - 1]!, points[i]!); + if (found) out.push(SPLINE_FIT_SAME); + } + for (const tangent of [spline.startTangent, spline.endTangent]) { + if (tangent === undefined) continue; + if (closed) { + out.push(SPLINE_CLOSED_TANGENT); + break; + } + const wrong = curvePointsProblem([tangent], "tangents"); + if (wrong) out.push(wrong); + else if (written(tangent[0]) === 0 && written(tangent[1]) === 0) out.push(SPLINE_TANGENT_ZERO); + } + if (out.length > 0) return { problems: out }; + // Fitted through the points as written, as the writers and the readers of the file fit them. + const held = points.map((p): Point => [written(p[0]), written(p[1])]); + const fitted = fitSpline(held, "chord", spline.startTangent, spline.endTangent, closed); + if (fitted.controlPoints.some(([x, y]) => !(Math.abs(x) < 1e100 && Math.abs(y) < 1e100))) + return { problems: [SPLINE_FIT_DRAWN] }; + return { problems: out, fitted }; +} + +/** The fields of a spline by its control points, as the checks read them. */ +interface ControlFields { + readonly controlPoints: readonly Point[]; + readonly degree: unknown; + readonly knots: readonly number[]; + readonly weights?: readonly number[] | undefined; + readonly closed?: unknown; +} + +/** + * What is wrong with a spline by its control points. Its lists are read once, and never past the + * count a file holds. + */ +export function controlSplineProblems(spline: ControlFields): string[] { + const { controlPoints: points, degree, knots, weights } = spline; + if ( + typeof degree !== "number" || + !Number.isInteger(degree) || + degree < 1 || + degree > SPLINE_DEGREE_MOST + ) { + return [SPLINE_DEGREE]; + } + const n = points.length; + if ( + n + degree + 1 > SPLINE_ITEMS || + knots.length > SPLINE_ITEMS || + (weights !== undefined && weights.length > SPLINE_ITEMS) + ) { + return [SPLINE_MANY]; + } + const out: string[] = []; + if (n < degree + 1) out.push(SPLINE_CONTROL_POINTS); + const problem = curvePointsProblem(points, "control points"); + if (problem) out.push(problem); + if (knots.length !== n + degree + 1) out.push(SPLINE_KNOT_COUNT); + else if (!knots.every(Number.isFinite)) out.push("its knots must be finite numbers"); + else { + const large = knots.map(magnitudeProblem).find((p) => p !== undefined); + if (large) out.push(`its knots: ${large}`); + else { + // Judged as the writers print them, with 16 digits: two knots that differ must print apart. + const printed = knots.map((k) => Number(sixteenDigits(k))); + let wrong = false; + for (let i = 1; i < knots.length && !wrong; i++) + wrong = + printed[i]! < printed[i - 1]! || + (knots[i] !== knots[i - 1] && printed[i] === printed[i - 1]); + if (wrong || (n >= degree + 1 && printed[degree]! === printed[n]!)) out.push(SPLINE_KNOTS); + } + } + if ( + weights !== undefined && + (weights.length !== n || + !weights.every((w) => Number.isFinite(w) && written(w) > 0 && !isTooLarge(w))) + ) { + out.push(SPLINE_WEIGHTS); + } + if (out.length === 0 && spline.closed === true && !closes(spline, degree)) + out.push(SPLINE_OPEN_CLOSED); + return out; +} + +/** + * True when a spline by its control points ends where it starts, in the direction it starts in, as + * it is written: the first and last control points of its clamped form are one, and, above + * degree 1, the sides beside them point the same way. + */ +function closes(spline: ControlFields, degree: number): boolean { + // Moved to its first point first, so the clamp's rounding is the curve's size and not how far + // it lies from the origin; a move changes nothing of the clamp. + const [ox, oy] = spline.controlPoints[0]!.map(written) as [number, number]; + const held = clamped({ + degree, + knots: spline.knots, + controlPoints: spline.controlPoints.map(([x, y]): Point => [written(x) - ox, written(y) - oy]), + ...(spline.weights === undefined ? {} : { weights: spline.weights.map(written) }), + }); + const p = held.controlPoints; + const [first, second, before, last] = [p[0]!, p[1]!, p[p.length - 2]!, p[p.length - 1]!]; + let reach = 0; + for (const [x, y] of p) reach = Math.max(reach, Math.abs(x), Math.abs(y)); + const near = 1e-9 * Math.max(1, reach); + if (Math.abs(first[0] - last[0]) > near || Math.abs(first[1] - last[1]) > near) return false; + // A closed spline of degree 1 is a polygon, which turns a corner where it closes. + if (degree === 1) return true; + const [ax, ay] = [second[0] - first[0], second[1] - first[1]]; + const [bx, by] = [last[0] - before[0], last[1] - before[1]]; + const [la, lb] = [Math.hypot(ax, ay), Math.hypot(bx, by)]; + if (!(la > near && lb > near)) return la <= near && lb <= near; + return Math.abs(ax * by - ay * bx) <= 1e-9 * la * lb && ax * bx + ay * by > 0; +} + /** What is wrong with a hatch with no loop. */ export const HATCH_NO_LOOPS = "a hatch needs at least one loop"; diff --git a/src/shape.ts b/src/shape.ts index 89dd907..b959625 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -8,7 +8,10 @@ import type { TextAttributeDefinition, Block, Circle, + ControlSpline, DimensionStyle, + Ellipse, + FitSpline, Drawing, Entity, Hatch, @@ -64,6 +67,8 @@ const KINDS = [ "polyline", "circle", "arc", + "ellipse", + "spline", "text", "paragraph", "insert", @@ -485,6 +490,23 @@ function shapes(all: boolean, typed = all): Shapes { } as const; const justified = { style: ruled(string), align: ruled(string), valign: ruled(string) } as const; + const fitSpline = fields( + { kind, layer: string, fitPoints: list(point) }, + { + ...shared, + startTangent: point, + endTangent: point, + closed: boolean, + }, + ); + const controlSpline = fields( + { kind, layer: string, controlPoints: list(point), degree: number, knots: list(number) }, + { ...shared, weights: list(number), closed: boolean }, + ); + /** A spline is through fit points when it has them, and by its control points otherwise. */ + const splineFields: FieldsCheck = (value, at, problems, extra) => + (value.fitPoints === undefined ? controlSpline : fitSpline)(value, at, problems, extra); + const ENTITIES = { line: fields({ kind, layer: string, from: point, to: point }, shared), polyline: fields( @@ -496,6 +518,11 @@ function shapes(all: boolean, typed = all): Shapes { { kind, layer: string, center: point, radius: number, startAngle: number, endAngle: number }, shared, ), + ellipse: fields( + { kind, layer: string, center: point, majorAxis: point, ratio: number }, + { ...shared, startParameter: number, endParameter: number }, + ), + spline: splineFields, text: fields( { kind, layer: string, at: point, height: number, value: string, rotation: number }, { ...shared, ...justified }, diff --git a/src/svg.ts b/src/svg.ts index 3d30149..bce1876 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -14,6 +14,7 @@ import { sweep, type DimensionStyle, type Drawing, + type Ellipse, type Entity, type Hatch, type HatchPattern, @@ -26,6 +27,7 @@ import { type Paragraph, type Point, type Polyline, + type Spline, type Text, type TextStyle, type Viewport, @@ -110,7 +112,16 @@ import { } from "./paragraphs.ts"; import { arrowheadInfo, DEFAULT_ARROWHEAD } from "./arrowheads.ts"; import { DEFAULT_PLOT_STYLE_TABLE, paperInfo } from "./papers.ts"; -import { shown as quoted, turning, viewportProblem } from "./rules.ts"; +import { + drawnEllipse, + shown as quoted, + SplineMemo, + turning, + viewportProblem, + type DrawnEllipse, + type DrawnSpline, +} from "./rules.ts"; +import { ellipsePoint, splinePieces, splinePolyline, unturned } from "./curves.ts"; import { filled, KEYED } from "./shape.ts"; import { isUnits } from "./units.ts"; @@ -383,6 +394,9 @@ interface Plan { interface Known { readonly sides: WeakMap; readonly plans: PolylineMemo; + /** The curve each ellipse, and each spline's drawn spline, draws, and its flat. */ + readonly curves: WeakMap; + readonly splines: SplineMemo; /** * Pays for the lists a plan is about to read, when a list was read for another plan before, * or refuses the picture. @@ -392,7 +406,148 @@ interface Known { /** A new `Known`, for one picture, which pays for lists read again with `readAgain`. */ function knowing(readAgain: Known["readAgain"] = () => {}): Known { - return { sides: new WeakMap(), plans: new PolylineMemo(), readAgain }; + return { + sides: new WeakMap(), + plans: new PolylineMemo(), + curves: new WeakMap(), + splines: new SplineMemo(), + readAgain, + }; +} + +/** What an ellipse or a spline draws, and the flat it is cut into dashes along. */ +interface Curve { + readonly ellipse?: DrawnEllipse; + readonly spline?: DrawnSpline; + /** Its points from start to end in its own coordinates, worked out when first dashed. */ + flat?: Flat; +} + +/** A curve as points close together, with the length along it to each. */ +interface Flat { + readonly points: readonly Point[]; + readonly lengths: readonly number[]; + /** True for one that closes, whose pattern goes round as a circle's does. */ + readonly closed: boolean; +} + +/** The steps an ellipse is cut into for a full turn, and each piece of a spline. */ +const ELLIPSE_STEPS = 512; +const SPLINE_STEPS = 32; + +/** + * The curve of an ellipse or a spline, worked out once into `known` for each: none for one of + * the wrong shape or that `lint` refuses. + */ +function curveOf(e: Ellipse | Spline, known: Known): Curve | undefined { + let key: object = e; + let spline: DrawnSpline | undefined; + if (e.kind === "spline") { + const fields = e as unknown as Readonly>; + spline = known.splines.get(fields, (lists) => { + known.readAgain(lists); + return true; + }); + if (!spline) return undefined; + key = spline; + } + const found = known.curves.get(key); + if (found !== undefined) return found ?? undefined; + let made: Curve | null = null; + if (spline) made = { spline }; + else { + const ellipse = drawnEllipse(e as Ellipse); + if (ellipse) made = { ellipse }; + } + known.curves.set(key, made); + return made ?? undefined; +} + +/** The flat of a curve, in its own coordinates. */ +function flatOf(curve: Curve): Flat { + if (curve.flat) return curve.flat; + let points: Point[]; + let closed: boolean; + if (curve.ellipse) { + const { center, majorAxis, ratio, start, end } = curve.ellipse; + const from = start ?? 0; + const turn = start === undefined ? 2 * Math.PI : unturned(end! - from) || 2 * Math.PI; + const steps = Math.max(8, Math.ceil((ELLIPSE_STEPS * turn) / (2 * Math.PI))); + points = Array.from({ length: steps + 1 }, (_, k) => + ellipsePoint(center, majorAxis, ratio, from + (turn * k) / steps), + ); + closed = start === undefined; + } else { + const { degree, knots, controlPoints, weights } = curve.spline!; + points = splinePolyline(degree, knots, controlPoints, weights, SPLINE_STEPS); + closed = curve.spline!.closed; + } + const lengths = [0]; + for (let i = 1; i < points.length; i++) { + const [a, b] = [points[i - 1]!, points[i]!]; + lengths.push(lengths[i - 1]! + Math.hypot(b[0] - a[0], b[1] - a[1])); + } + return (curve.flat = { points, lengths, closed }); +} + +/** + * An ellipse, or an arc of one, where `matrix` puts it: the image of an ellipse under the matrix + * is an ellipse, whose axes come from the images of its two semi-axes, as `rounded` finds them. + */ +function ellipseToSvg(d: DrawnEllipse, matrix: Matrix | undefined, s: string): string { + const [mx, my] = d.majorAxis; + const minor: Point = [-my * d.ratio, mx * d.ratio]; + const linear = (v: Point): Point => + matrix ? [matrix[0] * v[0] + matrix[2] * v[1], matrix[1] * v[0] + matrix[3] * v[1]] : v; + const [a, b] = [linear(d.majorAxis), linear(minor)]; + const round = rounded(1, [a[0], a[1], b[0], b[1], 0, 0]); + const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + if (d.start === undefined) return roundToSvg(at(d.center), round, s); + const turn = unturned(d.end! - d.start); + const large = turn > Math.PI ? 1 : 0; + const [start, end] = [d.start, d.end!].map((t) => { + const [x, y] = at(ellipsePoint(d.center, d.majorAxis, d.ratio, t)); + return `${fmt(x)} ${fmt(y)}`; + }); + // SVG draws nothing for an arc that ends where it starts. + if (start === end && large === 1) return roundToSvg(at(d.center), round, s); + return ``; +} + +/** + * A spline as path data, where `matrix` puts it. One of degree 1 to 3 that is not rational is + * drawn exactly, as lines or cubic Bézier pieces, a quadratic piece raised to a cubic; any other + * as the points of its flat. + */ +function splinePath(curve: Curve, matrix: Matrix | undefined): string { + const spline = curve.spline!; + const place = ([x, y]: Point): string => { + const [px, py] = matrix ? mapPoint(matrix, [x, y]) : [x, y]; + return `${fmt(px)} ${fmt(py)}`; + }; + const parts: string[] = []; + if (spline.weights !== undefined || spline.degree > 3) { + flatOf(curve).points.forEach((p, i) => parts.push(`${i === 0 ? "M" : "L"} ${place(p)}`)); + return parts.join(" "); + } + const { degree, knots, controlPoints } = spline; + let last = ""; + for (const piece of splinePieces(degree, knots, controlPoints, undefined)) { + const q = piece.map(([x, y]): Point => [x, y]); + const first = place(q[0]!); + if (first !== last) parts.push(`M ${first}`); + const end = place(q[degree]!); + if (degree === 1) parts.push(`L ${end}`); + else if (degree === 2) { + const raised = (p: Point): Point => [ + p[0] + ((q[1]![0] - p[0]) * 2) / 3, + p[1] + ((q[1]![1] - p[1]) * 2) / 3, + ]; + parts.push(`C ${place(raised(q[0]!))} ${place(raised(q[2]!))} ${end}`); + } else parts.push(`C ${place(q[1]!)} ${place(q[2]!)} ${end}`); + last = end; + } + return parts.join(" "); } /** @@ -1935,6 +2090,14 @@ function entityToSvg( } case "text": return textToSvg(e, style, pen, mark, matrix, true); + case "ellipse": { + const curve = curveOf(e, sides); + return curve ? ellipseToSvg(curve.ellipse!, matrix, s) : ``; + } + case "spline": { + const curve = curveOf(e, sides); + return curve ? `` : ``; + } } } @@ -2210,6 +2373,71 @@ function dashedPath( case "arc": ok = round(e.center, e.radius, e.startAngle, sweep(e.startAngle, e.endAngle), true); break; + case "ellipse": + case "spline": { + // A curve's pattern runs along its whole length: fitted as a line's is, or, for one that + // closes, as a circle's is, from its start. + const curve = curveOf(e, known); + if (!curve) return undefined; + const flat = flatOf(curve); + const closed = flat.closed; + // Under an insert the pattern runs along the curve as it plots, so the curve is placed first + // and measured there, in the block's units the pattern is shrunk to. + const grown = matrix ? Math.sqrt(Math.abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])) : 1; + // A matrix that turns, mirrors and scales alike keeps the curve's lengths in the block's + // units, so only the points a dash writes are placed. Any other places the whole curve, + // which a curve drawn again pays for. + const [a, b, c, d] = matrix ?? [1, 0, 0, 1]; + const alike = (x: number, y: number) => Math.abs(x - y) <= 1e-12 * grown; + const similar = (alike(a, d) && alike(b, -c)) || (alike(a, -d) && alike(b, c)); + let points: readonly Point[] = flat.points; + let lengths: readonly number[] = flat.lengths; + if (matrix && !similar) { + known.readAgain([flat.points]); + const placed = flat.points.map((p) => mapPoint(matrix, p)); + const measured = [0]; + for (let i = 1; i < placed.length; i++) { + const [p, q] = [placed[i - 1]!, placed[i]!]; + measured.push(measured[i - 1]! + Math.hypot(q[0] - p[0], q[1] - p[1]) / grown); + } + [points, lengths] = [placed, measured]; + } + const put = (p: Point): string => { + const [x, y] = matrix && similar ? mapPoint(matrix, p) : p; + return `${fmt(x)} ${fmt(y)}`; + }; + const length = lengths[lengths.length - 1]!; + const along = (from: number, to: number): string => { + const at = (t: number, i: number): Point => { + const [a, b] = [points[i]!, points[i + 1] ?? points[i]!]; + const span = lengths[i + 1]! - lengths[i]!; + const f = span > 0 ? (t - lengths[i]!) / span : 0; + return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f]; + }; + // The step that holds `t`: the last whose length is at most `t`. + const step = (t: number): number => { + let [lo, hi] = [0, lengths.length - 2]; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if (lengths[mid]! <= t) lo = mid; + else hi = mid - 1; + } + return lo; + }; + const [i, j] = [step(from), step(to)]; + const drawn = [`M ${put(at(from, i))}`]; + for (let k = i + 1; k <= j; k++) drawn.push(`L ${put(points[k]!)}`); + drawn.push(`L ${put(at(to, j))}`); + return drawn.join(" "); + }; + if (!(length > 0) || !(grown > 0)) return undefined; + if (!closed) ok = cut(length, along, true); + else { + if (!(length >= total)) return undefined; + ok = cut(length, along, false, length / (Math.round(length / total) * total)); + } + break; + } } return ok && (out.length > 0 || (wide?.fills.length ?? 0) > 0) ? out.join(" ") : undefined; } diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 0e7c9ef..98e9125 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2800,3 +2800,154 @@ test("a gradient that draws nothing pays for the sides it walked, and a gradient ], }); }); + +test("ellipses and splines of any size, count or shape are checked, boxed, drawn and written in a bounded time", () => { + const most = 32_767; + const zigzag = (count: number, size = 1): Point[] => + Array.from({ length: count }, (_, i) => [i * size, (i % 2) * size]); + const fit = zigzag(most - 6); + // Of the highest degree, rational: each of its points is worked out from 12. + const controls = zigzag(4000); + const knots = Array.from({ length: 4012 }, (_, i) => Math.max(0, Math.min(i - 11, 3989))); + const weights = controls.map((_, i) => 1 + (i % 3)); + const curves: Record[] = [ + // The longest spline through fit points a file holds, many times over with one list. + ...Array.from({ length: 3 }, () => ({ kind: "spline", layer: "0", fitPoints: fit })), + // One closed, one with tangents, and one past the count a file holds. + { kind: "spline", layer: "0", fitPoints: fit.slice(0, 20_000), closed: true }, + { kind: "spline", layer: "0", fitPoints: fit, startTangent: [0, 1], endTangent: [1e99, 0] }, + { kind: "spline", layer: "0", fitPoints: zigzag(1_000_000) }, + // The highest degree, rational, dashed finely, and the same lists shared. + ...Array.from({ length: 2 }, () => ({ + kind: "spline", + layer: "0", + linetype: "FINE", + controlPoints: controls, + degree: 11, + knots, + weights, + })), + // Lists that are all slots, numbers that are not finite or past what a file holds, sizes of + // none, and a degree past any. + // oxlint-disable-next-line unicorn/no-new-array + { kind: "spline", layer: "0", controlPoints: new Array(2 ** 32 - 1), degree: 3, knots }, + { + kind: "spline", + layer: "0", + controlPoints: zigzag(4, 1e300), + degree: 3, + knots: [0, 0, 0, 0, 1, 1, 1, 1], + }, + { + kind: "spline", + layer: "0", + controlPoints: zigzag(4, 0), + degree: 3, + knots: [0, 0, 0, 0, 1, 1, 1, 1], + }, + { + kind: "spline", + layer: "0", + controlPoints: zigzag(4), + degree: 1e9, + knots: [NaN, 0, 0, 0, 1, 1, 1, 1], + }, + { + kind: "spline", + layer: "0", + fitPoints: [ + [NaN, 0], + [0, -0], + ], + startTangent: [0, 0], + }, + { kind: "spline", layer: "0", fitPoints: zigzag(4, 4e99), closed: true }, + { + kind: "ellipse", + layer: "0", + linetype: "FINE", + center: [0, 0], + majorAxis: [9e99, 9e99], + ratio: 1e-6, + }, + { + kind: "ellipse", + layer: "0", + center: [0, 0], + majorAxis: [1, 0], + ratio: NaN, + startParameter: 1e99, + }, + { kind: "ellipse", layer: "0", linetype: "FINE", center: [0, 0], majorAxis: [0, 0], ratio: -1 }, + { + kind: "ellipse", + layer: "0", + linetype: "FINE", + center: [0, 0], + majorAxis: [1e6, 0], + ratio: 1, + startParameter: 0, + endParameter: 359.99999, + }, + ]; + // Each in a chain of blocks deeper than the stack, and in model space. + const tree = nested({ kind: "spline", layer: "0", fitPoints: fit } as Entity, 7000, 1, "C"); + const drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + linetypes: [{ name: "FINE", description: "", pattern: [1e-3, -1e-3] }], + blocks: tree.blocks, + entities: [...curves, tree.top], + } as unknown as Drawing; + const found = settled(20_000, () => lintWithin(drawing, {}, 500_000)); + assert.ok(Array.isArray(found), String(found)); + for (const walk of [ + () => svgWithin(drawing, {}, 2_000_000), + () => inspectWithin(drawing, {}, 500_000), + () => extents(drawing.entities, [], drawing.blocks), + ]) { + const done = settled(20_000, walk); + assert.ok(!(done instanceof Error) || done instanceof RangeError, String(done)); + } + // What lint passes is written in a bounded time. + const sound = { + ...drawing, + blocks: [], + entities: [...curves.slice(0, 5), ...curves.slice(6, 8)], + } as unknown as Drawing; + assert.deepEqual( + within(20_000, () => lint(sound)), + [], + ); + const written = settled(20_000, () => toDXFR2018(sound)); + assert.equal(typeof written, "string", String(written)); +}); + +test("a dashed spline a block holds is placed by each insert in time in proportion to what it writes", () => { + const fitPoints = Array.from({ length: 2000 }, (_, i): Point => [i * 100, (i % 2) * 100]); + const drawing = (scale: [number, number]): Drawing => ({ + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + linetypes: [{ name: "DOTS", description: "", pattern: [0, -10_000] }], + blocks: [ + { name: "B", entities: [{ kind: "spline", layer: "0", linetype: "DOTS", fitPoints }] }, + ], + entities: Array.from({ length: 1000 }, (_, k) => ({ + kind: "insert" as const, + layer: "0", + block: "B", + at: [0, k * 300] as Point, + scale, + rotation: k, + })), + }); + // Turned and scaled alike, an insert places only the dots it writes. + assert.equal(typeof within(3000, () => toSVG(drawing([1.5, 1.5]))), "string"); + // Scaled unevenly, it places the whole curve, which each insert after the first pays for. + const uneven = settled(3000, () => svgWithin(drawing([2, 1]), {}, 200_000)); + assert.ok(typeof uneven === "string" || uneven instanceof RangeError, String(uneven)); +}); diff --git a/test/curves.test.ts b/test/curves.test.ts new file mode 100644 index 0000000..f19a782 --- /dev/null +++ b/test/curves.test.ts @@ -0,0 +1,337 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + createDrawing, + HIDDEN, + readDXF, + toDXF, + toPDF, + toSVG, + type Drawing, + type Entity, + type Point, +} from "../src/index.ts"; +import { clamped, ellipsePoint, splinePoint } from "../src/curves.ts"; +import { extents } from "../src/extents.ts"; +import { readProblems } from "./read-agreement.ts"; + +/** The groups of the `n`th record of `type` in a DXF, as `code=value`. */ +function record(dxf: string, type: string, n = 0): string[] { + const lines = dxf.split("\r\n"); + let at = -1; + for (let k = 0; k <= n; k++) { + at = lines.findIndex((line, i) => i > at && line === type && lines[i - 1]!.trim() === "0"); + } + const out: string[] = []; + for (let i = at + 1; i + 1 < lines.length && lines[i]!.trim() !== "0"; i += 2) + out.push(`${lines[i]!.trim()}=${lines[i + 1]}`); + return out; +} + +/** The groups of a record from its subclass on, without its handle and owner. */ +const own = (groups: readonly string[], subclass: string) => + groups.slice(groups.indexOf(`100=${subclass}`) + 1); + +const drawing = (entities: Entity[]): Drawing => ({ ...createDrawing().build(), entities }); + +test("toDXF writes an ellipse and a spline as the leading CAD app saves them", () => { + const dxf = toDXF( + drawing([ + { kind: "ellipse", layer: "0", center: [1, 2], majorAxis: [3, 0], ratio: 0.5 }, + // An arc that runs through 0 ends a turn past its start. + { + kind: "ellipse", + layer: "0", + center: [0, 0], + majorAxis: [0, 2], + ratio: 0.5, + startParameter: 300, + endParameter: 60, + }, + { + kind: "spline", + layer: "0", + controlPoints: [ + [0, 0], + [0, 1], + [1, 1], + ], + degree: 2, + knots: [0, 0, 0, 1, 1, 1], + weights: [1, 0.5, 1], + }, + // A periodic spline of unclamped knots is saved clamped over what it runs over. + { + kind: "spline", + layer: "0", + controlPoints: [ + [0.3, 0.3], + [1.5, 0.3], + [1.5, 1.1], + [0.3, 1.1], + [0.3, 0.3], + [1.5, 0.3], + [1.5, 1.1], + ], + degree: 3, + knots: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + closed: true, + }, + { + kind: "spline", + layer: "0", + fitPoints: [ + [0, 0], + [3, 4], + ], + }, + { + kind: "spline", + layer: "0", + fitPoints: [ + [0, 0], + [4, 0], + [2, 3], + ], + closed: true, + }, + ]), + ); + assert.deepEqual(own(record(dxf, "ELLIPSE"), "AcDbEllipse"), [ + ...["10=1", "20=2", "30=0", "11=3", "21=0", "31=0", "210=0", "220=0", "230=1", "40=0.5"], + ...["41=0", "42=6.28318530717959"], + ]); + assert.deepEqual(own(record(dxf, "ELLIPSE", 1), "AcDbEllipse").slice(-2), [ + "41=5.23598775598299", + "42=7.33038285837618", + ]); + assert.deepEqual(own(record(dxf, "SPLINE"), "AcDbSpline"), [ + ...["210=0", "220=0", "230=1", "70=12", "71=2", "72=6", "73=3", "74=0"], + ...["42=0.000000001", "43=0.0000000001"], + ...["40=0", "40=0", "40=0", "40=1", "40=1", "40=1"], + ...["10=0", "20=0", "30=0", "41=1", "10=0", "20=1", "30=0", "41=0.5"], + ...["10=1", "20=1", "30=0", "41=1"], + ]); + const periodic = own(record(dxf, "SPLINE", 1), "AcDbSpline"); + assert.deepEqual(periodic.slice(3, 8), ["70=11", "71=3", "72=11", "73=7", "74=0"]); + assert.deepEqual( + periodic.filter((g) => g.startsWith("40=")).map((g) => Number(g.slice(3))), + [3, 3, 3, 3, 4, 5, 6, 7, 7, 7, 7], + ); + const points = periodic.filter((g) => /^[12]0=/.test(g)); + assert.deepEqual(points.slice(0, 2), points.slice(-2)); + // Through two points: a line, its four control points a third of the way apart. + const two = own(record(dxf, "SPLINE", 2), "AcDbSpline"); + assert.deepEqual(two.slice(3, 15), [ + ...["70=1080", "71=3", "72=8", "73=4", "74=2"], + ...["42=0.000000001", "43=0.0000000001", "44=0.0000000001"], + ...["40=0", "40=0", "40=0", "40=0"], + ]); + assert.deepEqual( + two.filter((g) => /^[12]0=/.test(g)), + [ + "10=0", + "20=0", + "10=0.9999999999999998", + "20=1.333333333333333", + "10=2", + "20=2.666666666666667", + "10=3", + "20=4", + ], + ); + // Closed: its first fit point again at the end, and one tangent at both ends. + const ring = own(record(dxf, "SPLINE", 3), "AcDbSpline"); + assert.deepEqual(ring.slice(3, 8), ["70=1067", "71=3", "72=10", "73=6", "74=4"]); + const tangent = (codes: readonly number[]) => + codes.map((code) => ring.find((g) => g.startsWith(`${code}=`))!.split("=")[1]); + assert.deepEqual(tangent([12, 22, 32]), tangent([13, 23, 33])); + assert.deepEqual(ring.filter((g) => /^[12]1=/.test(g)).slice(-2), ["11=0", "21=0"]); +}); + +test("clamped gives the same curve, starting and ending on its control points", () => { + const points: Point[] = [ + [0, 0], + [1, 3], + [2, -1], + [4, 2], + [5, 0], + ]; + const spline = { + degree: 3, + knots: [0, 1, 2, 3, 4, 5, 6, 7, 8], + controlPoints: points, + weights: [1, 2, 1, 0.5, 1], + }; + const held = clamped(spline); + assert.deepEqual(held.knots, [3, 3, 3, 3, 4, 5, 5, 5, 5]); + for (const u of [3, 3.4, 4, 4.9, 5]) { + const [a, b] = [ + splinePoint(3, spline.knots, points, spline.weights, u), + splinePoint(3, held.knots, held.controlPoints, held.weights, u), + ]; + assert.ok(Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-12, `${u}`); + } + assert.deepEqual(clamped(held), held); +}); + +test("readDXF gives back each curve as it was drawn, and one seen from below as it draws", async () => { + const d = createDrawing(); + d.ellipse([1, 2], [3, 1], 0.4, { startParameter: 30, endParameter: 90 }); + d.ellipse([1, 2], [3, 1], 0.4); + d.spline([ + [0, 0], + [3, 4], + [6, 1], + ]); + d.spline( + [ + [0, 0], + [4, 0], + [2, 3], + ], + { closed: true }, + ); + d.controlSpline( + [ + [0, 0], + [0, 1], + [1, 1], + ], + { degree: 2, weights: [1, Math.SQRT1_2, 1] }, + ); + d.controlSpline( + [ + [0, 0], + [1, 2], + [2, 0], + [3, 2], + ], + { closed: true }, + ); + const built = d.build(); + const text = toDXF(built); + const read = await readDXF(text, { geometry: true }); + assert.deepEqual(readProblems(built, read, "tsdraft"), []); + const fit = read.model.entities![3]!; + assert.ok(fit.kind === "spline" && fit.closed && fit.fitPoints?.length === 3); + + // The arc from 30 to 90 seen from below runs from -90 to -30. + const below = text.replace( + "230\r\n1\r\n40\r\n0.4\r\n41\r\n0.523598775598299\r\n42\r\n1.5707963267949", + "230\r\n-1\r\n40\r\n0.4\r\n41\r\n4.71238898038469\r\n42\r\n5.759586531581287", + ); + assert.ok(below !== text); + const [arc] = (await readDXF(below, { geometry: true })).model.entities!; + assert.ok(arc?.kind === "ellipse"); + assert.ok(Math.abs(arc.startParameter! - 30) < 1e-9 && Math.abs(arc.endParameter! - 90) < 1e-9); + + const broken = await readDXF( + text.replace("40\r\n0.4\r\n", "40\r\n1.5\r\n").replace("72\r\n9\r\n", "72\r\n8\r\n"), + { geometry: true }, + ); + assert.deepEqual(Object.keys(broken.unread.malformed).sort(), [ + "ELLIPSE with a ratio outside 0 to 1 or an axis of no length", + "SPLINE whose counts disagree with its groups or its degree", + ]); +}); + +test("toSVG draws an ellipse an insert places as the ellipse it maps it to", () => { + const d = createDrawing(); + d.block("OVAL", {}, () => { + d.ellipse([0, 0], [2, 0], 0.5); + d.ellipse([0, 0], [2, 0], 0.5, { startParameter: 0, endParameter: 90 }); + }); + d.insert("OVAL", [10, 10], { scale: [-1, 3] }); + const svg = toSVG(d.build()); + // The axes [2, 0] and [0, 1] become [-2, 0] and [0, 3]: the longer is 3, upright. + assert.match(svg, / { + const points: Point[] = [ + [0, 0], + [1, 4], + [3, -2], + [4, 1], + ]; + const d = createDrawing(); + d.controlSpline(points); + d.ellipse([0, 0], [2, 0], 0.5, { startParameter: 45, endParameter: 135 }); + const box = extents(d.build().entities); + const curve = Array.from({ length: 10001 }, (_, k) => + splinePoint(3, [0, 0, 0, 0, 1, 1, 1, 1], points, undefined, k / 10000), + ); + const arc = Array.from({ length: 10001 }, (_, k) => + ellipsePoint([0, 0], [2, 0], 0.5, Math.PI / 4 + (Math.PI / 2) * (k / 10000)), + ); + const all = [...curve, ...arc]; + const sampled = [ + Math.min(...all.map((p) => p[0])), + Math.min(...all.map((p) => p[1])), + Math.max(...all.map((p) => p[0])), + Math.max(...all.map((p) => p[1])), + ]; + for (const [i, got] of box.entries()) { + const want = sampled[i]!; + assert.ok(Math.abs(got - want) < 1e-6, `${i}: ${got} against ${want}`); + assert.ok(i < 2 ? got <= want : got >= want, `${i}: ${got} inside ${want}`); + } +}); + +test("a curve's dashes run along its whole length, as a line's or a circle's do", () => { + const dashed = (e: Entity): string => { + const d = createDrawing().linetype(HIDDEN); + d.layer("D", { linetype: "HIDDEN" }); + const svg = toSVG({ ...d.build(), entities: [{ ...e, layer: "D" } as Entity] }); + return / path.split("M").length - 1; + // A whole ellipse of ratio 1 dashes as the circle it is, from its parameter 0. + const round = dashed({ kind: "circle", layer: "D", center: [0, 0], radius: 3 }); + const oval = dashed({ kind: "ellipse", layer: "D", center: [0, 0], majorAxis: [3, 0], ratio: 1 }); + assert.equal(moves(oval), moves(round)); + assert.ok(oval.startsWith("M 3 0 ")); + // A spline that is a straight line dashes as the line: half of the first dash and of what is + // left over at each end. + const line = dashed({ kind: "line", layer: "D", from: [0, 0], to: [10, 0] }); + const straight = dashed({ + kind: "spline", + layer: "D", + controlPoints: [ + [0, 0], + [10, 0], + ], + degree: 1, + knots: [0, 0, 1, 1], + }); + const ends = (path: string) => + path + .split("M") + .slice(1) + .map((dash) => { + const xs = dash + .trim() + .split(/ L /) + .map((p) => Number(p.split(" ")[0])); + return [xs[0], xs.at(-1)]; + }); + assert.deepEqual(ends(straight), ends(line)); +}); + +test("toPDF plots a spline's Bézier pieces and an arc of an ellipse", () => { + const d = createDrawing({ units: "in" }); + d.layout("S", { paper: "ANSI B" }, () => { + d.controlSpline([ + [1, 1], + [2, 3], + [3, 1], + [4, 3], + ]); + d.ellipse([6, 4], [1, 0], 0.5, { startParameter: 0, endParameter: 270 }); + }); + const pdf = new TextDecoder("latin1").decode(toPDF(d.build())); + assert.match(pdf, / c\n/); +}); diff --git a/test/format.test.ts b/test/format.test.ts index 13dad38..357d7bd 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -39,7 +39,7 @@ function refusal(value: unknown): readonly Diagnostic[] { return assert.fail("fromJSON took the value"); } -const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader", "image", "hatch" or "wipeout"`; +const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "ellipse", "spline", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader", "image", "hatch" or "wipeout"`; test("a drawing goes to JSON and back unchanged", () => { const drawing = sample(); @@ -94,13 +94,13 @@ test("fromJSON names what it does not know, and runs lint", () => { layers: [{ name: "0", color: 7, colour: 1 }], entities: [ { ...(base.entities![0] as object), layer: "0", thickness: 2 }, - { kind: "ellipse", layer: "0" }, + { kind: "xline", layer: "0" }, { kind: "circle", layer: "0", center: [0, 0, 0] }, ], }), [ 'format: entities[0]: unknown field "thickness"', - `format: entities[1]: unknown entity kind "ellipse".${kinds}`, + `format: entities[1]: unknown entity kind "xline".${kinds}`, 'format: entities[2]: the field "radius" is missing', "format: entities[2].center must be a point, [x, y]", 'format: layers[0]: unknown field "colour". Did you mean "color"?', diff --git a/test/read-agreement.ts b/test/read-agreement.ts index 90b3b26..fc899ad 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -21,7 +21,9 @@ import type { Point, TextStyle, } from "../src/drawing.ts"; +import { isFitSpline } from "../src/drawing.ts"; import { written, writtenAngle } from "../src/format.ts"; +import { clamped } from "../src/curves.ts"; import { idHandle } from "../src/handles.ts"; import { findLeaderStyle, leaderPicture } from "../src/leaders.ts"; import { fromImagePixels, imageClip, imageVectors, writtenImagePath } from "../src/images.ts"; @@ -348,6 +350,65 @@ export function readProblems( ); } return; + case "ellipse": { + if (!kind("ellipse") || got.kind !== "ellipse") return; + // Its parameters are written in radians, and come back within rounding of the degrees. + const angle = (a: number | undefined, b: number | undefined): boolean => { + if (a === undefined || b === undefined) return a === b; + const turned = (((a - b) % 360) + 360) % 360; + return Math.min(turned, 360 - turned) <= 1e-9; + }; + if ( + !nearPoint(got.center, point(want.center)) || + !nearPoint(got.majorAxis, point(want.majorAxis)) || + !near(got.ratio, written(want.ratio)) || + !angle( + got.startParameter, + want.startParameter === undefined ? undefined : writtenAngle(want.startParameter), + ) || + !angle( + got.endParameter, + want.endParameter === undefined ? undefined : writtenAngle(want.endParameter), + ) + ) { + say(`${label}: ${JSON.stringify({ ...got, handle: undefined })}`); + } + return; + } + case "spline": { + if (!kind("spline") || got.kind !== "spline") return; + if ((got.closed ?? false) !== (want.closed ?? false)) say(`${label}: closed ${got.closed}`); + if (isFitSpline(want)) { + // The leading CAD app fits its own control points: the fit points are what agree. + if ( + got.fitPoints?.length !== want.fitPoints.length || + got.fitPoints.some((p, i) => !nearPoint(p, point(want.fitPoints[i]!))) + ) { + say(`${label}: fit points ${JSON.stringify(got.fitPoints).slice(0, 200)}`); + } + return; + } + // A spline by its control points is written clamped, as that app saves it. + const held = clamped(want); + // Knots and points the clamp worked out are written with 16 digits, not as given. + const worked = + held.knots.length !== want.knots.length || held.knots.some((k, i) => k !== want.knots[i]); + const as = (v: number) => (worked ? v : written(v)); + const at = (p: Point) => (worked ? p : point(p)); + const loose = by !== "tsdraft" || worked; + if ( + got.degree !== want.degree || + got.knots.length !== held.knots.length || + got.knots.some((k, i) => !near(k, as(held.knots[i]!), loose)) || + got.controlPoints.length !== held.controlPoints.length || + got.controlPoints.some((p, i) => !nearPoint(p, at(held.controlPoints[i]!), loose)) || + (got.weights === undefined) !== (held.weights === undefined) || + (got.weights ?? []).some((w, i) => !near(w, as(held.weights![i]!), loose)) + ) { + say(`${label}: ${JSON.stringify({ ...got, handle: undefined }).slice(0, 300)}`); + } + return; + } case "text": { if (!kind("text") || got.kind !== "text") return; const style = styleOf(want.style); diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index 4812716..fcae915 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -84,12 +84,57 @@ export function seedFiles(): Uint8Array[] { }); images.insert("LOGO", [0, 10]); }); + // Ellipses and splines of each kind, in model space and in a block. + const curves = createDrawing({ units: "ft" }); + curves.block("CURVE", {}, () => curves.layer("0", {}, () => curves.ellipse([0, 0], [2, 1], 0.5))); + curves.layer("C", { color: 3 }, () => { + curves.ellipse([0, 0], [3, 0], 0.4, { startParameter: 300, endParameter: 60 }); + curves.spline([ + [0, 0], + [4, 2], + [8, 1], + ]); + curves.spline( + [ + [0, 5], + [3, 8], + [6, 5], + ], + { closed: true }, + ); + curves.spline( + [ + [0, 9], + [4, 10], + ], + { startTangent: [0, 1], endTangent: [1, 0] }, + ); + curves.controlSpline( + [ + [0, 0], + [0, 2], + [2, 2], + ], + { degree: 2, weights: [1, Math.SQRT1_2, 1] }, + ); + curves.controlSpline( + [ + [5, 0], + [6, 2], + [7, 0], + [8, 2], + ], + { closed: true }, + ); + curves.insert("CURVE", [10, 10]); + }); return [ ...[ toDXF(sheet), toDXF(kitchen), toDXF(d.build(), { version: "R12" }), toDXF(images.build()), + toDXF(curves.build()), ].map((t) => encoder.encode(t)), leaderFile(), ]; diff --git a/test/read.test.ts b/test/read.test.ts index 6075253..04f0ca1 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -303,7 +303,7 @@ test("readDXF keeps fields, the heights MTEXT sets, and counts what it does not ownLineweight: 1, lineweights: { "35": 1 }, }); - assert.deepEqual(plain(read.unread.entities), { SPLINE: 1, OLE2FRAME: 1 }); + assert.deepEqual(plain(read.unread.entities), { OLE2FRAME: 1 }); assert.deepEqual(plain(read.unread.objects), { ACAD_PROXY_OBJECT: 1 }); // No text value of model space is kept. assert.ok(!JSON.stringify(read).includes("big")); diff --git a/test/rules.test.ts b/test/rules.test.ts index 7e16789..9a85af2 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -1763,3 +1763,215 @@ test("a hatch's gradient is checked by the builder and by lint", () => { /R2018/, ); }); + +test("ellipses and splines are checked by the builder and by lint", () => { + const d = createDrawing(); + const zigzag: Point[] = [ + [0, 0], + [1, 2], + [2, 0], + ]; + // Literals the compiler reads. + const three = [ + [0, 0], + [1, 2], + [2, 0], + ] as const; + const twice = [ + [0, 0], + [1, 1], + [1, 1], + ] as const; + // @ts-expect-error: a ratio is above 0. + assert.throws(() => d.ellipse([0, 0], [2, 0], 0), /ratio/); + // @ts-expect-error: a ratio is at most 1. + assert.throws(() => d.ellipse([0, 0], [2, 0], 1.5), /ratio/); + // @ts-expect-error: a ratio written as 0. + assert.throws(() => d.ellipse([0, 0], [2, 0], 4e-7), /ratio/); + d.ellipse([0, 0], [2, 0], 1.0000004); + assert.throws(() => d.ellipse([0, 0], [4e-7, 0], 0.5), /major axis/); + assert.throws(() => d.ellipse([0, 0], [2, 0], 0.5, { startParameter: 10 }), /together/); + assert.throws( + () => d.ellipse([0, 0], [2, 0], 0.5, { startParameter: 10, endParameter: 370.0000001 }), + /must differ/, + ); + + // @ts-expect-error: a spline passes through 2 points or more. + assert.throws(() => d.spline([[0, 0]]), /at least 2/); + // @ts-expect-error: two points side by side are one. + assert.throws(() => d.spline(twice), /side by side/); + assert.throws( + () => + d.spline([ + [0, 0], + [1, 1], + [1.0000001, 1], + ]), + /side by side/, + ); + // @ts-expect-error: a tangent of no direction. + assert.throws(() => d.spline(zigzag, { startTangent: [0, 0] }), /no direction/); + // @ts-expect-error: a closed spline takes no tangent. + assert.throws(() => d.spline(zigzag, { closed: true, endTangent: [1, 0] }), /closed spline/); + assert.throws(() => d.spline(zigzag.slice(0, 2), { closed: true }), /3 when it is closed/); + + // @ts-expect-error: a degree from 1 to SPLINE_DEGREE_MOST. + assert.throws(() => d.controlSpline(zigzag, { degree: 12 }), /degree/); + // @ts-expect-error: a cubic needs 4 control points. + assert.throws(() => d.controlSpline(three), /one more control point/); + // @ts-expect-error: 3 control points of degree 2 take 6 knots. + assert.throws(() => d.controlSpline(three, { degree: 2, knots: [0, 0, 0, 1, 1] }), /knots/); + // @ts-expect-error: one weight for each control point. + assert.throws(() => d.controlSpline(three, { degree: 2, weights: [1, 1] }), /weight/); + // @ts-expect-error: a weight above 0. + assert.throws(() => d.controlSpline(three, { degree: 2, weights: [1, -1, 1] }), /weight/); + assert.throws( + () => d.controlSpline(zigzag, { degree: 2, knots: [0, 0, 0, 2, 1, 1] }), + /never decrease/, + ); + assert.throws( + () => d.controlSpline(zigzag, { degree: 2, knots: [0, 0, 0, 0, 0, 0] }), + /never decrease/, + ); + // Closed without knots, its first control points come again, with uniform knots. + d.controlSpline(zigzag, { degree: 2, closed: true }); + const closed = d.build().entities.at(-1)!; + assert.ok(closed.kind === "spline" && !("fitPoints" in closed)); + assert.deepEqual(closed.knots, [0, 1, 2, 3, 4, 5, 6, 7]); + assert.equal(closed.controlPoints.length, 5); + + // lint holds a drawing made another way to the same rules, and R12 to none of them. + const one = (entity: object, dxf: "R12" | "R2018" = "R2018") => + lint({ ...createDrawing().build(), dxf, entities: [{ layer: "0", ...entity } as Entity] }).map( + (x) => `${x.rule}: ${x.message}`, + ); + assert.deepEqual(one({ kind: "ellipse", center: [0, 0], majorAxis: [1, 0], ratio: 2 }), [ + "geometry: ellipse #0: an ellipse's ratio, its minor radius over its major, must be above 0 and at most 1 once rounded to the 6 decimals tsdraft writes", + ]); + assert.match( + one({ + kind: "ellipse", + center: [0, 0], + majorAxis: [1, 0], + ratio: 1, + startParameter: 400, + endParameter: 3, + })[0]!, + /from 0 up to 360/, + ); + assert.match( + one({ kind: "spline", fitPoints: zigzag, startTangent: [0, 1], closed: true })[0]!, + /closed spline takes no tangents/, + ); + assert.match( + one({ + kind: "spline", + controlPoints: zigzag, + degree: 2, + knots: [0, 0, 0, 1, 1, 1], + weights: [1, 0, 1], + })[0]!, + /weight/, + ); + assert.match( + one({ kind: "spline", controlPoints: zigzag, degree: 2.5, knots: [0, 0, 0, 1, 1, 1] })[0]!, + /degree is a whole number/, + ); + assert.match( + one({ + kind: "spline", + fitPoints: [ + [0, 0], + [9e99, 0], + [0, 1e-6], + [-9e99, 0], + ], + })[0]!, + /fitted through its points/, + ); + assert.match( + one({ kind: "ellipse", center: [0, 0], majorAxis: [1, 0], ratio: 0.5 }, "R12")[0]!, + /no ellipses or splines to R12/, + ); + assert.throws(() => createDrawing({ dxf: "R12" }).spline(zigzag), /no ellipses or splines/); + // Clamped knots make an open curve, which a closed spline's flag would not close. + assert.throws( + () => + d.controlSpline( + [ + [10, 0], + [20, 15], + [50, 15], + [60, 0], + ], + { closed: true, knots: [0, 0, 0, 0, 1, 1, 1, 1] }, + ), + /end where it starts/, + ); + d.controlSpline( + [ + [10, 0], + [20, 15], + [50, 15], + [60, 0], + ], + { closed: true }, + ); + // Knots that differ by less than the 16 digits tsdraft writes would print as one. + const b = 1 + Number.EPSILON; + assert.throws( + () => + d.controlSpline( + [ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + ], + { knots: [1, 1, 1, 1, b, b, b, b] }, + ), + /16 digits/, + ); + assert.throws( + () => + d.controlSpline( + [ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + ], + { knots: [0, 0, 0, 0, 1e-21, 1e-21, 1e-21, 1e-21] }, + ), + /16 digits/, + ); + // A knot repeated inside, as the leading CAD app's own splines hold one, is kept. + d.controlSpline( + [ + [0, 0], + [1, 2], + [2, 0], + [3, 2], + [4, 0], + [5, 2], + ], + { knots: [0, 0, 0, 0, 1, 1, 2, 2, 2, 2] }, + ); + // A polygon closes with a corner, and a small closed outline far from the origin closes too. + d.controlSpline( + [ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + ], + { closed: true, degree: 1 }, + ); + d.controlSpline( + Array.from({ length: 7 }, (_, i): Point => [ + 612345.25 + 0.5 * Math.cos(i * 0.9), + 1298765.5 + 0.35 * Math.sin(i * 0.9), + ]), + { closed: true }, + ); +}); diff --git a/test/shape.test.ts b/test/shape.test.ts index c33851a..d4b49e8 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -31,6 +31,7 @@ import { type TextStyle, type Viewport, type Xref, + type FitSpline, } from "../src/index.ts"; import { timeLimit } from "./time-limit.ts"; @@ -219,6 +220,32 @@ const kinds: { id: "w2", ...styled, }, + ellipse: { + kind: "ellipse", + layer: "0", + center: [100, 5], + majorAxis: [4, 1], + ratio: 0.5, + startParameter: 30, + endParameter: 270, + id: "w6", + ...styled, + }, + // A spline by its control points; `fitted` is one through fit points. + spline: { + kind: "spline", + layer: "0", + controlPoints: [ + [110, 0], + [112, 4], + ], + degree: 1, + knots: [0, 0, 1, 1], + weights: [1, 2], + closed: false, + id: "w7", + ...styled, + }, "radius-dimension": { kind: "radius-dimension", layer: "0", @@ -326,6 +353,21 @@ const tinted: Required> = { ...styled, }; +/** A spline through fit points, with every field one can have. */ +const fitted: Required = { + kind: "spline", + layer: "0", + fitPoints: [ + [120, 0], + [124, 3], + ], + startTangent: [0, 1], + endTangent: [1, 0], + closed: false, + id: "w5", + ...styled, +}; + const keyed: Required< Omit< Leader, @@ -538,6 +580,7 @@ const full: Required & { { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }, wide, keyed, + fitted, shaded, tinted, ], @@ -763,7 +806,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #18: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #20: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ diff --git a/test/standard-lint.test.ts b/test/standard-lint.test.ts index f2779fa..87a317c 100644 --- a/test/standard-lint.test.ts +++ b/test/standard-lint.test.ts @@ -175,8 +175,8 @@ test("a text plots at its role's height in each viewport that shows it, and at l assert.deepEqual( lint(half, { standard }).map((d) => d.message), [ - `text #52: This text of the role "note" plots 0.047 in tall in viewport "plan" at 1" = 10', and the role is 0.094 in: it was sized for another scale. Draw it in the view of the viewport that shows it`, - `text #52: This text plots 0.047 in tall in viewport "plan" at 1" = 10', below the standard's least height of 0.0625 in`, + `text #53: This text of the role "note" plots 0.047 in tall in viewport "plan" at 1" = 10', and the role is 0.094 in: it was sized for another scale. Draw it in the view of the viewport that shows it`, + `text #53: This text plots 0.047 in tall in viewport "plan" at 1" = 10', below the standard's least height of 0.0625 in`, ], ); // The model of the sheet at 1" = 10', shown at 1" = 20': every text and dimension is off. @@ -259,7 +259,7 @@ test("a dimension is shown at its style's scale", () => { assert.equal(found.length, 7); assert.match( found[0]!.message, - /^linear-dimension #28: It is in the dimension style "DIMS-1in-20ft", for 1" = 20', and is shown in viewport "plan" at 1" = 10'/, + /^linear-dimension #29: It is in the dimension style "DIMS-1in-20ft", for 1" = 20', and is shown in viewport "plan" at 1" = 10'/, ); }); From f3ad36b2fc96fcb07023eed34c03eceb3f0ff5df Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 03:59:29 -0500 Subject: [PATCH 20/35] Ordinate dimensions Ordinate dimensions, drawn as the leading CAD app draws them: - `d.ordinateDimension(feature, leaderEnd, { axis, origin })` gives the distance from `origin`, `[0, 0]` unless given, to `feature` along X (`axis: "x"`) or along Y (`axis: "y"`), without its sign, on a leader from near `feature` to `leaderEnd` with its text beyond. A feature at the origin reads 0. - The leader runs along Y for an X ordinate and along X for a Y one, from the style's offset off the feature. Where its end is off the feature's line it jogs across, from twice the arrow size along it, or four arrow sizes short of the end where that is further, to two arrow sizes short of the end, then runs on past the end under the text. A centered text stands on the leader, which stops at the end, and words below stand under it. A leader that ends level with its feature runs back, down or to the left. The leader takes the style's extension lineweight and no arrowhead. - The leader is laid out in the numbers the leading CAD app holds for the written coordinates, which it reads from a decimal in a way of its own. A jog across by no more than 1e-10 of the feature's X, for an X ordinate, or its Y, in the drawing and not as measured from `origin`, is drawn straight: a jog of a hundred-thousandth at an X of a million is one line. That app holds 1,000,000,000,000 and 1,000,000,000,000.0001 as one number, so a leader that ends that far along runs back. - `lint` refuses an ordinate dimension whose axis is neither `"x"` nor `"y"`, whose leader ends at its feature, or whose measurement takes more digits than a length's writing holds, and warns of one whose leader runs further across than along. - `toDXF` writes them, and `readDXF` reads them as `ordinate-dimension`, with the axis, the origin, the feature, the leader's end, the middle of the text and what it measures; one in a turned coordinate system is counted under `other`. The command's dimension summary lists them, and its JSON's dimension kinds are listed in full. - The guide no longer lists arc length and ordinate dimensions as not drawn. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 5 + GUIDE.md | 4 +- cli/src/state.ts | 6 +- cli/src/worker.ts | 1 + docs/command.md | 9 +- docs/dimensions.md | 45 ++++++++- docs/reading.md | 6 +- src/dimensions.ts | 208 +++++++++++++++++++++++++++++++++++++++- src/drawing.ts | 82 ++++++++++++++++ src/dxf-r2018.ts | 27 +++++- src/extents.ts | 1 + src/format.ts | 25 +++++ src/index.ts | 4 + src/inspect.ts | 1 + src/lint.ts | 21 +++- src/read/check.ts | 16 ++++ src/read/dxf.ts | 3 +- src/read/entities.ts | 33 +++++++ src/read/model.ts | 25 +++++ src/rules.ts | 11 +++ src/shape.ts | 13 +++ test/bounded.test.ts | 14 +++ test/dimensions.test.ts | 132 +++++++++++++++++++++++++ test/read-agreement.ts | 48 +++++++++- test/read.test.ts | 4 +- test/shape.test.ts | 14 ++- 26 files changed, 732 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 925191e..7c26194 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -151,6 +151,11 @@ coordinates, and lists the file's image definitions in `images`, with how many images name each, one that none names among them. The example sheet has a vicinity map above its key plan. [docs/images.md](docs/images.md) describes them. +- Ordinate dimensions: `ordinateDimension(feature, leaderEnd, { axis, origin })` gives the X or the + Y of a feature from an origin, `[0, 0]` unless given, without its sign, on a leader to + `leaderEnd` with its text beyond, drawn as the leading CAD app draws it: the leader jogs where + the end is off the feature's line, except by no more than 1e-10 of the feature's X or Y in the + drawing, which it draws straight. `toDXF` writes them, and `readDXF` reads them as `ordinate-dimension`. - Arc length dimensions: `arcLengthDimension(center, radius, startAngle, endAngle, at, options)` measures the length of an arc, as `arc` takes it, with its own arc through `at`, drawn as the leading CAD app draws it: from a right angle up about the center with extension lines along radii, diff --git a/GUIDE.md b/GUIDE.md index ca2882d..22e4148 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -400,6 +400,9 @@ d.linearDimension([24, 30], [76, 30], [0, 20], { style: "PLAN" }); - `arcLengthDimension(center, radius, startAngle, endAngle, at, options)` dimensions the length of an arc, as `arc` takes it, with its own arc through `at`; a style's `arcSymbol` puts the arc symbol `"before"` the text, `"above"` it, or `"none"`. +- `ordinateDimension(feature, leaderEnd, { axis, origin })` gives the X (`axis: "x"`) or the Y of + `feature` from `origin`, `[0, 0]` unless given, on a leader to `leaderEnd`, which jogs where the + end is off the feature's line. - Never draw a dimension from lines and text. [docs/dimensions.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/dimensions.md) has the rest. @@ -628,7 +631,6 @@ writeFileSync("plan.dxf", toDXF(drawing)); ## What tsdraft cannot draw yet -- Arc length and ordinate dimensions. - A block read from another file. A block is drawn in the drawing that inserts it. An xref references a whole DWG file, as an overlay, and the pictures draw it only from a drawing you give. diff --git a/cli/src/state.ts b/cli/src/state.ts index 9042fd4..ddd7e05 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -356,7 +356,8 @@ export interface DimensionSummary { readonly layer: string; /** * `linear` measures along one direction, `aligned` from point to point, `radius`, `diameter` - * and `jogged-radius` a circle or an arc, `angular` the angle between two lines, and `arc-length` the length of an arc. + * and `jogged-radius` a circle or an arc, `angular` the angle between two lines, `arc-length` + * the length of an arc, and `ordinate` the X or the Y of a point from an origin. */ readonly kind: | "linear" @@ -365,7 +366,8 @@ export interface DimensionSummary { | "diameter" | "jogged-radius" | "angular" - | "arc-length"; + | "arc-length" + | "ordinate"; /** The dimension style as the dimension names it. */ readonly style: string; /** diff --git a/cli/src/worker.ts b/cli/src/worker.ts index 1d16f4d..d6e5d2f 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -1555,6 +1555,7 @@ const SUMMARY_KINDS = { "jogged-radius-dimension": "jogged-radius", "angular-dimension": "angular", "arc-length-dimension": "arc-length", + "ordinate-dimension": "ordinate", } as const; /** Each dimension among some entities, with what the library the drawing loaded says it reads. */ diff --git a/docs/command.md b/docs/command.md index 57a9060..47db94c 100644 --- a/docs/command.md +++ b/docs/command.md @@ -164,10 +164,11 @@ it holds, the tags of its attributes and how many inserts place it. `drawing.ins insert in model space: its `entity` index, `block`, `layer`, `id`, `at`, `scale`, `rotation` and the value it shows for each attribute, and `xref`, which is true for an insert of an xref. `drawing.dimensions` gives each -dimension in model space: its `entity` index, `id`, `layer`, `kind`, which is `linear` or -`aligned`, `style`, `measurement`, the length it measures in drawing units, and `text`, the -string the leading CAD app draws for it. The last two are `null` for a dimension whose style the -drawing does not define. A layout's `dimensions` lists those on its sheet in the same way. +dimension in model space: its `entity` index, `id`, `layer`, `kind`, which is `linear`, +`aligned`, `radius`, `diameter`, `jogged-radius`, `angular`, `arc-length` or `ordinate`, `style`, +`measurement`, the length it measures in drawing units or an angular one's angle in degrees, and +`text`, the string the leading CAD app draws for it. The last two are `null` for a dimension whose +style the drawing does not define. A layout's `dimensions` lists those on its sheet in the same way. `drawing.xrefs` gives each xref's `name`, its `path`, whether it is an `attach`ment or an overlay, how many `inserts` place it, in model space, in blocks and on layouts, `shown`, `units` and `xrefs`. The command opens no DWG file. It draws an xref when diff --git a/docs/dimensions.md b/docs/dimensions.md index d9ed491..796123d 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -265,6 +265,46 @@ app's own arc stops short of an extension line; one whose centered text leaves i each side; one whose measurement takes more digits than a length's writing holds; and words below with the arc symbol. +### Ordinate + +`d.ordinateDimension(feature, leaderEnd, options)` gives the distance from `options.origin`, or from +`[0, 0]`, to `feature` along X when `options.axis` is `"x"` and along Y when it is `"y"`, on a +leader from near `feature` to `leaderEnd`, with its text beyond. The distance has no sign, so a +feature on either side of the origin reads alike, and one at the origin reads 0. + +```ts +const datum = { style: "DIMS", origin: [4, 16] } as const; +d.ordinateDimension([7, 13], [7, 17.5], { ...datum, axis: "x" }); // 3.00 +d.ordinateDimension([7, 7.5], [2.5, 8.25], { ...datum, axis: "y" }); // 8.50 +``` + +An X ordinate's leader runs along Y and a Y ordinate's along X, from the style's offset off the +feature to `leaderEnd`, then on past it under the text. The text stands a gap beyond the end, reads +along the leader and stands a gap above it, or on it in a style that centers its text, where the +leader stops at the end. Words below stand under the leader. A leader whose end is off the +feature's line jogs across: from twice the arrow size along it, or from four arrow sizes short of +the end where that is further, to two arrow sizes short of the end. A leader that ends level with +its feature runs back, down or to the left. The leader takes the style's `extensionLineweight`, +and no arrowhead. + +The leading CAD app draws a jog straight, as one line from the feature's side to the end's, where +the end is across by no more than 1e-10 of the feature's X, for an X ordinate, or its Y, as the +drawing holds it and not as measured from `origin`, taken as the difference of the two numbers that +app holds for them once it has read the file: a jog of a hundred-thousandth at an X of a million is +a straight line, and so is a jog of a millionth at 100,000. That app reads a decimal in a way of its +own, which can come out a unit in the last place from the nearest number, so at exactly 1e-10 of +the coordinate the difference comes out a hair to one side or the other: 0.00001 at 100,000 and +0.000007 at 70,000 are a hair more, and are drawn, and 0.0001 at 1,000,000 and 0.000003 at 30,000 a +hair less, and are straight. The same reading decides whether the end is level with the feature: +that app holds 1,000,000,000,000 and 1,000,000,000,000.0001 as one number, so a leader that ends +that far along runs back, and one that also ends there across has no leader. tsdraft lays the +leader out in the numbers that app holds. + +`lint` refuses an ordinate dimension whose axis is neither `"x"` nor `"y"`, whose leader ends at +its feature, or whose measurement takes more digits than a length's writing holds, and warns of +one whose leader runs further across than along, which is most often an ordinate given the +other axis. + ## How a measurement is written A measurement is the length between the points as the file holds them, with 6 decimals, @@ -439,8 +479,9 @@ no dimension style holds nothing else for dimensions. ## What is not drawn yet -Ordinate dimensions, an arc length dimension of part of an arc or with a leader, or inside an arc -under a right angle, an angular dimension by two lines, and an angular dimension's +An ordinate dimension in a turned coordinate system or with a text a drafter placed, an arc length +dimension of part of an arc or with a leader, or inside an arc under a right angle, an angular +dimension by two lines, and an angular dimension's level text or text a drafter placed. A radial dimension's center mark, which the leading CAD app draws only without the line to the center, and a level text placed along its line. Tolerances and alternate units, and the unit formats but decimal and feet and inches. The other fits of a text, such as diff --git a/docs/reading.md b/docs/reading.md index 6c6f033..ee73b86 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -121,7 +121,7 @@ leader: - `dimension`: a linear or aligned dimension, with its two points, the point where its dimension line meets its second extension line, its direction, the middle of its text, what it measures, its text and the words below its line, which the file holds after `\X`, its style and the - block of its picture. Ordinate dimensions are counted under `other`. + block of its picture. - `radial-dimension`: a radius, a diameter or a jogged radius dimension, its `type`, with its center, the point of the circle or arc its line meets, a jogged one's start and jog, the middle of its text, `placed` where the file holds the text where it was placed, what it @@ -131,6 +131,10 @@ leader: `endAngle` of the arc it measures, a point its own arc passes through, `at`, the middle of its text, `placed`, `partial` where it measures part of the arc, what it measures, its text, its style and the block of its picture. +- `ordinate-dimension`: an ordinate dimension, with its `axis`, `"x"` or `"y"`, the `origin` it + measures from, its `feature`, its `leaderEnd`, the middle of its text, `textAt`, `placed`, what it + measures, its text, its style and the block of its picture. One drawn in a turned coordinate + system is counted under `other`. - `angular-dimension`: an angular dimension, its `type`, `"three-point"` with its `vertex` and a point of each line, `from` and `to`, or `"two-line"` with its `first` and `second` lines, each two points; a point its arc passes through, `at`, the middle of its text, `placed`, the angle it diff --git a/src/dimensions.ts b/src/dimensions.ts index fe0d42a..1a3e252 100644 --- a/src/dimensions.ts +++ b/src/dimensions.ts @@ -5,6 +5,7 @@ import type { AlignedDimension, AngularDimension, ArcLengthDimension, + OrdinateDimension, DiameterDimension, DimensionStyle, Drawing, @@ -30,7 +31,7 @@ import { type ParagraphLayout, type ParagraphToMeasure, } from "./paragraphs.ts"; -import { written } from "./format.ts"; +import { heldNumber, written } from "./format.ts"; import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; import { direction } from "./polylines.ts"; @@ -45,6 +46,7 @@ import { ARC_LENGTH_NO_ARC, ARC_LENGTH_NO_REACH, ARC_LENGTH_ON_ARC, + ORDINATE_NO_LEADER, ARC_LENGTH_SYMBOL_BELOW, ANGULAR_ARC_ON_LINE, ANGULAR_ARROWS_LONG, @@ -77,7 +79,12 @@ export type StraightDimension = LinearDimension | AlignedDimension; export type RadialDimension = RadiusDimension | DiameterDimension | JoggedRadiusDimension; /** A dimension of any kind. */ -export type Dimension = StraightDimension | RadialDimension | AngularDimension | ArcLengthDimension; +export type Dimension = + | StraightDimension + | RadialDimension + | AngularDimension + | ArcLengthDimension + | OrdinateDimension; /** Whether an entity is a dimension. */ export function isDimension( @@ -88,6 +95,7 @@ export function isDimension( entity.kind === "aligned-dimension" || entity.kind === "angular-dimension" || entity.kind === "arc-length-dimension" || + entity.kind === "ordinate-dimension" || isRadial(entity) ); } @@ -131,7 +139,8 @@ export function dimensionStyleHandle(name: string): string { /** * The handles of the block that holds a dimension's picture in an R2018 drawing, and of each * object in it: the block's record, the two objects that open and close its definition in a - * DXF, the two extension lines, the dimension line, the two arrowheads and the text. + * DXF, the two extension lines, the dimension line, the two arrowheads and the text. An ordinate + * dimension, which has no dimension line, takes its handle for the third line of a jogged leader. */ export interface DimensionPictureHandles { readonly record: string; @@ -651,7 +660,8 @@ export function dimensionAngle(dimension: Pick): numbe /** * The direction a dimension measures along, in degrees, and what it measures: for a linear * dimension the distance between its two points along its angle, and for an aligned one the - * distance between them. Every number is taken as the writers write it. + * distance between them; for an ordinate one its axis, 0 for X and 90 for Y, and the distance + * along it from its origin, without its sign. Every number is taken as the writers write it. */ export function dimensionMeasure(dimension: Dimension): { readonly angle: number; @@ -665,6 +675,14 @@ export function dimensionMeasure(dimension: Dimension): { const { start, sweep, radius } = arcLengthArc(dimension); return { angle: start + sweep / 2, measurement: radius * sweep * RADIANS }; } + if (dimension.kind === "ordinate-dimension") { + // Along its axis, and the distance along it from the origin, without its sign. + const i = dimension.axis === "x" ? 0 : 1; + return { + angle: i === 0 ? 0 : 90, + measurement: Math.abs(written(dimension.feature[i]) - written(dimension.origin[i])), + }; + } if (isRadial(dimension)) { const [x1, y1] = [written(dimension.center[0]), written(dimension.center[1])]; const [x2, y2] = [written(dimension.point[0]), written(dimension.point[1])]; @@ -708,6 +726,7 @@ export function dimensionPicture( if (dimension.kind === "angular-dimension") return angularPicture(dimension, style, textStyle); if (dimension.kind === "arc-length-dimension") return arcLengthPicture(dimension, style, textStyle); + if (dimension.kind === "ordinate-dimension") return ordinatePicture(dimension, style, textStyle); const from: Point = [written(dimension.from[0]), written(dimension.from[1])]; const to: Point = [written(dimension.to[0]), written(dimension.to[1])]; const { angle, measurement } = dimensionMeasure(dimension); @@ -921,6 +940,153 @@ export function dimensionPicture( }; } +/** + * Where an ordinate dimension's feature and leader end are, how far along its leader the end is + * from the feature, the direction from one to the other along it, how far across the end is, and + * whether the leader jogs, each in the numbers the leading CAD app holds for the written + * coordinates, as `heldNumber` reads them: two that are written apart may be held as one. A leader whose end is held level with its feature runs + * back, and one held across by no more than 1e-10 of the feature's coordinate that the dimension + * gives, in the drawing and not from the dimension's origin, is drawn straight. At exactly that in + * decimals the difference falls a hair to either side: 0.00001 at 100000 jogs, and 0.0001 at + * 1000000 and 0.000003 at 30000 are straight. + */ +export function ordinateLeader(dimension: OrdinateDimension): { + readonly feature: Point; + readonly end: Point; + readonly length: number; + readonly along: Point; + readonly across: number; + readonly jogged: boolean; +} { + // The leader is laid out in the numbers that app holds, so each point it places is one that + // app would place, and each choice is made from the numbers the point is placed from. + const feature: Point = [heldNumber(dimension.feature[0]), heldNumber(dimension.feature[1])]; + const end: Point = [heldNumber(dimension.leaderEnd[0]), heldNumber(dimension.leaderEnd[1])]; + const x = dimension.axis === "x"; + const run = x ? end[1] - feature[1] : end[0] - feature[0]; + const across = x ? end[0] - feature[0] : end[1] - feature[1]; + // A leader's end level with its feature runs the leader back: down, or to the left. + const way = run > 0 ? 1 : -1; + return { + feature, + end, + length: Math.abs(run), + along: x ? [0, way] : [way, 0], + across, + jogged: Math.abs(across) > 1e-10 * Math.abs(x ? feature[0] : feature[1]), + }; +} + +/** + * The picture of an ordinate dimension: its leader from the style's offset off the feature, and + * where it jogs a jog across, from twice the arrow size along the leader, or from four arrow sizes + * short of the end where that is further, to two arrow sizes short of the end; then on past the + * end under the text, which stands a gap beyond the end along the leader, read along it, a gap + * above it. A leader that does not jog is one line, from the feature's side to the end's. Centered, + * the leader stops at the end and the text stands on its line. The leader's lines take the + * extension lines' lineweight. + */ +function ordinatePicture( + dimension: OrdinateDimension, + style: DimensionStyle, + textStyle: DimensionFont | undefined, +): DimensionPicture { + const { measurement } = dimensionMeasure(dimension); + const sizes = dimensionSizes(style); + const { feature, end, length, along, jogged } = ordinateLeader(dimension); + const x = dimension.axis === "x"; + // A point `t` along the leader from the feature and `off` across it. + const at = (t: number, off: number): Point => + x + ? [feature[0] + off, feature[1] + along[1] * t] + : [feature[0] + along[0] * t, feature[1] + off]; + const move = (point: Point, by: Point, distance: number): Point => [ + point[0] + by[0] * distance, + point[1] + by[1] * distance, + ]; + const rotation = x ? 90 : 0; + const direction: Point = x ? [0, 1] : [1, 0]; + const above: Point = x ? [-1, 0] : [0, 1]; + const [aboveText, belowText] = dimensionTexts(dimension, measurement, style); + const font = textStyle?.font ?? STANDARD_FONT; + const lay = (value: string): ParagraphLayout => + layoutDimensionText({ + value, + height: sizes.textHeight, + font, + widthFactor: written(textStyle?.widthFactor ?? 1), + obliqueAngle: written(textStyle?.obliqueAngle ?? 0), + align: "center", + valign: "middle", + }); + const boxHeight = (layout: ParagraphLayout): number => layout.frame[3] - layout.frame[1]; + const widest = (layout: ParagraphLayout): number => + layout.lines.reduce((most, line) => Math.max(most, line.end - line.start), 0); + const topLayout = lay(mtextOfLabel(aboveText)); + const belowLayout = + belowText === undefined ? undefined : lay(belowText === "" ? "" : mtextOfLabel(belowText)); + const textWidth = Math.max(widest(topLayout), belowLayout ? widest(belowLayout) : 0); + const centered = style.textPlacement === "centered"; + const gap = sizes.textGap; + // The leader's line through the text, beyond its end. + const point = move(end, along, gap + textWidth / 2); + const offset = sizes.extensionOffset; + const size = sizes.arrowSize; + // A point that lies a distance from the end is placed from the end, and one on the feature's + // line from where the end stands across from it, which a far feature's arithmetic could lose. + const past = move(end, along, centered ? 0 : gap + textWidth); + const jogEnd = move(end, along, -2 * size); + const jogStart = + length - 4 * size >= 2 * size + ? move(x ? [feature[0], end[1]] : [end[0], feature[1]], along, -4 * size) + : at(2 * size, 0); + const extensionLines: (readonly [Point, Point])[] = !jogged + ? [[at(offset, 0), past]] + : [ + [at(offset, 0), jogStart], + [jogStart, jogEnd], + [jogEnd, past], + ]; + const textMiddle = + centered && belowLayout === undefined + ? point + : move(point, above, gap + boxHeight(topLayout) / 2); + const belowMiddle = belowLayout && move(point, above, -(gap + boxHeight(belowLayout) / 2)); + const textStyleName = style.textStyle; + const label = (value: string, middle: Point, layout: ParagraphLayout): DimensionLabel => ({ + value, + at: move(middle, above, layout.lines[0]?.baseline ?? 0), + height: sizes.textHeight, + rotation, + direction, + ...(textStyleName === undefined ? {} : { style: textStyleName }), + }); + const last = extensionLines[extensionLines.length - 1]!; + return { + measurement, + definitionPoint: [written(dimension.origin[0]), written(dimension.origin[1])], + extensionLines, + dimensionLine: [last[0], last[1]], + dimensionLines: [], + leader: [], + dimensionArcs: [], + arrowheads: [], + arrowheadEntities: [], + label: label(aboveText, textMiddle, topLayout), + textMiddle, + textPoint: belowLayout === undefined ? textMiddle : point, + textWidth, + ...(belowLayout && + belowMiddle && { + below: { label: label(belowText!, belowMiddle, belowLayout), middle: belowMiddle }, + }), + lineweights: { + dimension: lineweightCode(style.dimensionLineweight), + extension: lineweightCode(style.extensionLineweight), + }, + }; +} + /** What the leading CAD app writes before a radial dimension's measurement. */ export const RADIAL_PREFIXES = { "radius-dimension": "R", @@ -1913,6 +2079,38 @@ function arcLengthDrawnProblem( return pictureNumbersProblem(picture); } +/** + * What is wrong with an ordinate dimension in its style, or undefined: a leader that ends at its + * feature, and what it reads past the digits a length's writing holds. A feature at the origin + * reads 0, as the leading CAD app draws it. + */ +function ordinateDrawnProblem( + dimension: OrdinateDimension, + style: DimensionStyle, + textStyle: TextStyle | undefined, +): string | undefined { + const { length, across } = ordinateLeader(dimension); + if (length === 0 && across === 0) return ORDINATE_NO_LEADER; + const picture = dimensionPicture(dimension, style, textStyle); + const measurement = picture.measurement; + const scaled = measurement * written(style.measurementScale ?? 1); + if (!Number.isFinite(measurement) || !Number.isFinite(scaled)) { + return "it measures no finite length"; + } + if (written(measurement) !== 0) { + const digits = dimensionMeasureProblem( + measurement, + scaled, + roundedMeasurement(measurement, style), + true, + picture.label.value, + undefined, + ); + if (digits) return digits; + } + return pictureNumbersProblem(picture); +} + /** What an arc length dimension draws above its arc and below it, as `dimensionTexts` for a line. */ function arcLengthTexts( dimension: ArcLengthDimension, @@ -2023,6 +2221,8 @@ export function dimensionDrawnProblem( return angularDrawnProblem(dimension, style, textStyle); if (dimension.kind === "arc-length-dimension") return arcLengthDrawnProblem(dimension, style, textStyle); + if (dimension.kind === "ordinate-dimension") + return ordinateDrawnProblem(dimension, style, textStyle); // The arrowheads need room for the wider of the texts above and below the line. const [above, below] = dimensionTexts(dimension, measurement, style); let drawn = above; diff --git a/src/drawing.ts b/src/drawing.ts index 4bea488..156db7d 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -251,6 +251,7 @@ import { WIPEOUT_CROSSES, WIPEOUT_FLAT, WIPEOUT_POINTS, + ORDINATE_AXIS, } from "./rules.ts"; import type { Standard, @@ -777,6 +778,30 @@ export interface ArcLengthDimension extends Placed { readonly textBelow?: string; } +/** + * An ordinate dimension: the distance from `origin` to `feature` along X or along Y, as `axis` + * says, on a leader from near `feature` to `leaderEnd` with its text beyond. The leader runs along + * Y for `"x"` and along X for `"y"`, and jogs where `leaderEnd` is off that line. The distance has + * no sign, so features either side of the origin read alike. + */ +export interface OrdinateDimension extends Placed { + readonly kind: "ordinate-dimension"; + /** A dimension style of the drawing. */ + readonly style: string; + /** `"x"` gives the feature's X from the origin, with its leader along Y; `"y"` its Y. */ + readonly axis: "x" | "y"; + /** The point it measures from. */ + readonly origin: Point; + /** The point it gives the coordinate of. */ + readonly feature: Point; + /** Where its leader ends; its text stands beyond. */ + readonly leaderEnd: Point; + /** A text to draw in place of the measurement, as a linear dimension's `text`. */ + readonly text?: string; + /** Words drawn under its leader, opposite the text, as a linear dimension's `textBelow`. */ + readonly textBelow?: string; +} + /** Which side of the point where its shafts meet a leader's note is on. */ export type LeaderSide = (typeof LEADER_SIDES)[number]; @@ -1027,6 +1052,7 @@ export type Entity = | JoggedRadiusDimension | AngularDimension | ArcLengthDimension + | OrdinateDimension | Leader | Image | Hatch @@ -2350,6 +2376,18 @@ export type ArcLengthDimensionOptions< I extends string = string, > = DimensionOptions; +/** The options of `ordinateDimension()`. */ +export interface OrdinateDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, +> extends DimensionOptions { + /** `"x"` gives the feature's X from the origin, with its leader along Y; `"y"` its Y. */ + readonly axis: "x" | "y"; + /** The point it measures from. Defaults to `[0, 0]`. */ + readonly origin?: Point; +} + /** The options of `angularDimension()`. */ export type AngularDimensionOptions< S extends string = string, @@ -2404,6 +2442,19 @@ export interface StandardRadiusDimensionOptions< readonly textFromCenter?: number; } +/** The options of `ordinateDimension()` under the standard `Z`. */ +export interface StandardOrdinateDimensionOptions< + S extends string = string, + T extends string = string, + I extends string = string, + Z extends Standard = Standard, +> extends StandardAlignedDimensionOptions { + /** `"x"` gives the feature's X from the origin, with its leader along Y; `"y"` its Y. */ + readonly axis: "x" | "y"; + /** The point it measures from. Defaults to `[0, 0]`. */ + readonly origin?: Point; +} + /** The options of `linearDimension()` under the standard `Z`. */ export interface StandardLinearDimensionOptions< S extends string = string, @@ -4787,6 +4838,37 @@ export class DrawingBuilder< ); } + /** + * Draws an ordinate dimension on the current layer: the distance from `options.origin`, or from + * `[0, 0]`, to `feature` along `options.axis`, on a leader from near `feature` to `leaderEnd`. + */ + ordinateDimension( + feature: Point, + leaderEnd: Point, + options: Z extends Standard + ? StandardOrdinateDimensionOptions + : V extends "R12" + ? R12Dimensions + : OrdinateDimensionOptions, + ): this { + return this.#add(DrawingBuilder.prototype.ordinateDimension, idOf(options), () => { + const o = options as unknown as OrdinateDimensionOptions | undefined; + const axis: unknown = o?.axis; + if (axis !== "x" && axis !== "y") refuse("dimension", ORDINATE_AXIS); + const origin: unknown = o?.origin ?? [0, 0]; + return this.#dimension(o, (style, text) => ({ + kind: "ordinate-dimension", + layer: this.#current, + style, + axis, + origin: pt(origin as Point), + feature: pt(feature), + leaderEnd: pt(leaderEnd), + ...text, + })); + }); + } + /** A radius or a diameter dimension, with its text where `options.textFromCenter` says. */ #radial( kind: K, diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 2eefc0d..1dba5ca 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -1629,7 +1629,9 @@ function writeDimension( ? e.line : e.kind === "angular-dimension" || e.kind === "arc-length-dimension" ? e.at - : e.to; + : e.kind === "ordinate-dimension" + ? e.origin + : e.to; const picture = drawn ?? { definitionPoint: at, textPoint: at }; const jogged = e.kind === "jogged-radius-dimension"; g( @@ -1649,9 +1651,11 @@ function writeDimension( if (block !== undefined) g(2, block); point(g, 10, ...picture.definitionPoint); point(g, 11, ...picture.textPoint); - // The kind, and 32: the dimension has a picture of its own; 128: its text is where it was placed. + // The kind, and 32: the dimension has a picture of its own; 64: an ordinate gives X; 128: its + // text is where it was placed. const placed = "textFromCenter" in e && e.textFromCenter !== undefined ? 128 : 0; - g(70, DIMENSION_TYPES[e.kind] + 32 + placed); + const alongX = e.kind === "ordinate-dimension" && e.axis === "x" ? 64 : 0; + g(70, DIMENSION_TYPES[e.kind] + 32 + alongX + placed); const text = dimensionFileText(e); if (text !== undefined) g(1, dxfOnce(text)); g(71, 5); // the text is placed by its middle @@ -1674,6 +1678,12 @@ function writeDimension( point(g, 17, ...second); return; } + if (e.kind === "ordinate-dimension") { + g(100, "AcDbOrdinateDimension"); + point(g, 13, ...e.feature); + point(g, 14, ...e.leaderEnd); + return; + } if (e.kind === "angular-dimension") { g(100, "AcDb3PointAngularDimension"); point(g, 13, ...e.from); @@ -1749,6 +1759,7 @@ const DIMENSION_TYPES = { "jogged-radius-dimension": 9, "angular-dimension": 5, "arc-length-dimension": 5, + "ordinate-dimension": 6, } as const; /** The block of a dimension's picture, with what the writer needs for it. */ @@ -1796,8 +1807,16 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask string, number, ])[] = [ + // An ordinate's jogged leader, which has no dimension line, takes its handle for its third + // line. ...picture.extensionLines.map( - ([from, to], i) => [from, to, handles.extensionLines[i]!, weights.extension] as const, + ([from, to], i) => + [ + from, + to, + [...handles.extensionLines, handles.dimensionLine][i]!, + weights.extension, + ] as const, ), ...picture.dimensionLines.map( ([from, to], i) => [from, to, handles.dimensionLines[i]!, weights.dimension] as const, diff --git a/src/extents.ts b/src/extents.ts index fde0cdc..d41abf5 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -365,6 +365,7 @@ export function boxer( case "jogged-radius-dimension": case "angular-dimension": case "arc-length-dimension": + case "ordinate-dimension": dimension(e, from, add); break; case "leader": { diff --git a/src/format.ts b/src/format.ts index 7c381c8..840e49a 100644 --- a/src/format.ts +++ b/src/format.ts @@ -10,6 +10,31 @@ export function written(value: number): number { return Object.is(rounded, -0) ? 0 : rounded; } +/** A number as the writers print it: digits, perhaps a point and more, perhaps `e+` and more. */ +const PRINTED = /^(-?)(\d+)(?:\.(\d+))?(?:e\+(\d+))?$/; + +/** + * The double the leading CAD app holds for a number as the writers print it, which is not always + * the nearest double to the decimal: it sums the digits, without the point, as a whole number one + * digit at a time, then applies the power of ten left over a bit at a time, lowest first, each + * power the square of the one before, and reads only two digits of an exponent. About one 6-decimal + * value in six comes out one unit in the last place from the nearest double. + */ +export function heldNumber(value: number): number { + const match = PRINTED.exec(fmt(value)); + if (!match) return written(value); + const [, sign, whole = "", fraction = "", exponent = ""] = match; + let held = 0; + for (const digit of whole + fraction) held = held * 10 + (digit.charCodeAt(0) - 48); + const power = Number(exponent.slice(0, 2)) - fraction.length; + let step = 10; + for (let bits = Math.abs(power); bits > 0; bits >>= 1) { + if (bits & 1) held = power < 0 ? held / step : held * step; + step *= step; + } + return sign ? -held : held; +} + /** * A number with 15 significant digits and no exponent, which JavaScript writes for a number * under a millionth. Summed as a whole number, 15 digits stay under 2^53, so the double diff --git a/src/index.ts b/src/index.ts index dbf5af7..204d21e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -105,6 +105,8 @@ export { type AngularDimensionOptions, type ArcLengthDimension, type ArcLengthDimensionOptions, + type OrdinateDimension, + type OrdinateDimensionOptions, type InsertOptions, type Layer, type LayerOptions, @@ -143,6 +145,7 @@ export { type StandardAlignedDimensionOptions, type StandardLeaderOptions, type StandardLinearDimensionOptions, + type StandardOrdinateDimensionOptions, type StandardRadiusDimensionOptions, type StandardViewportOptions, type Text, @@ -438,6 +441,7 @@ export { type ReadRadialDimension, type ReadAngularDimension, type ReadArcLengthDimension, + type ReadOrdinateDimension, type ReadDimensionStyle, type ReadDrawingFile, type ReadEntity, diff --git a/src/inspect.ts b/src/inspect.ts index aff7140..2ea2526 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -606,6 +606,7 @@ function looked( case "jogged-radius-dimension": case "angular-dimension": case "arc-length-dimension": + case "ordinate-dimension": case "leader": return true; default: diff --git a/src/lint.ts b/src/lint.ts index 4846568..d6edcfc 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -20,6 +20,7 @@ import { callOf, type CallSite } from "./callsite.ts"; import { arrowheadEntityHandle, dimensionDrawnProblem, + ordinateLeader, pictureHandleList, pictureOwner, validDimensionPictureHandles, @@ -200,6 +201,8 @@ import { patternLineProblem, patternLinesProblem, undefinedHatchPatternProblem, + ORDINATE_ACROSS, + ORDINATE_AXIS, } from "./rules.ts"; import { hatchSpread, @@ -582,6 +585,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) case "jogged-radius-dimension": case "angular-dimension": case "arc-length-dimension": + case "ordinate-dimension": cost += long1(e.style) + long1(e.text) + long1(e.textBelow); break; case "leader": @@ -1293,6 +1297,17 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) return; } } + if (dimension.kind === "ordinate-dimension") { + const axis: unknown = dimension.axis; + if (axis !== "x" && axis !== "y") { + add("dimension", "error", ORDINATE_AXIS); + return; + } + if (sound) { + const { length, across } = ordinateLeader(dimension); + if (Math.abs(across) > length) add("dimension", "warning", ORDINATE_ACROSS); + } + } if (!style || !sound) return; // Its style's prefix and suffix are read again for each dimension that has the style. const reads = @@ -2642,7 +2657,8 @@ function costsBoxes(e: Readonly>): boolean { kind === "diameter-dimension" || kind === "jogged-radius-dimension" || kind === "angular-dimension" || - kind === "arc-length-dimension" + kind === "arc-length-dimension" || + kind === "ordinate-dimension" ); } @@ -2735,6 +2751,9 @@ function geometryProblems(e: Entity): string[] { case "angular-dimension": finite("its points", ...e.vertex, ...e.from, ...e.to, ...e.at); break; + case "ordinate-dimension": + finite("its points", ...e.origin, ...e.feature, ...e.leaderEnd); + break; case "arc-length-dimension": finite( "its points, radius and angles", diff --git a/src/read/check.ts b/src/read/check.ts index 3db05be..11ff7fd 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -255,6 +255,22 @@ const ENTITY: Readonly> = { "block?": "string", "blockHandle?": "string", }, + "ordinate-dimension": { + ...BASE, + kind: { oneOf: ["ordinate-dimension"] }, + axis: { oneOf: ["x", "y"] }, + origin: "point", + feature: "point", + leaderEnd: "point", + textAt: "point", + "placed?": "boolean", + "measurement?": "number", + "text?": "string", + "textBelow?": "string", + style: "string", + "block?": "string", + "blockHandle?": "string", + }, "angular-dimension": { ...BASE, kind: { oneOf: ["angular-dimension"] }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 0376af9..74a4892 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -1792,7 +1792,8 @@ class DxfReader { entity.kind !== "dimension" && entity.kind !== "radial-dimension" && entity.kind !== "angular-dimension" && - entity.kind !== "arc-length-dimension" + entity.kind !== "arc-length-dimension" && + entity.kind !== "ordinate-dimension" ) continue; const block = entity.block; diff --git a/src/read/entities.ts b/src/read/entities.ts index ea7dd3a..d040a10 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -11,6 +11,7 @@ import type { ReadRadialDimension, ReadAngularDimension, ReadArcLengthDimension, + ReadOrdinateDimension, ReadEntity, ReadEntityBase, ReadGradient, @@ -873,6 +874,7 @@ function dimension(r: Rec, base: ReadEntityBase, face: Facing, r12: boolean): Re const kind = (num(r, 70) ?? 0) & 15; if (kind === 3 || kind === 4 || kind === 9) return radialDimension(r, base, kind, r12); if (kind === 2 || kind === 5) return angularDimension(r, base, kind, r12); + if (kind === 6) return ordinateDimension(r, base, r12); if (kind > 1) return { other: `DIMENSION ${DIMENSION_KINDS[kind] ?? "of another kind"}` }; const angle = kind === 0 ? (num(r, 50) ?? 0) : 0; // The leading CAD app leaves the measurement out when it is 1. An R12 file holds none. @@ -935,6 +937,36 @@ function radialDimension(r: Rec, base: ReadEntityBase, kind: number, r12: boolea return { entity }; } +/** + * An ordinate dimension (group 70's kind 6): its origin (10), its feature (13) and its leader's + * end (14), giving X where group 70 holds 64 and Y where not. One drawn in a turned coordinate + * system, whose axes group 51 turns, is left out. + */ +function ordinateDimension(r: Rec, base: ReadEntityBase, r12: boolean): Reading { + const turned = num(r, 51) ?? 0; + if (turned !== 0) return { other: "DIMENSION ordinate in a turned coordinate system" }; + const measurement = num(r, 42) ?? (r12 ? undefined : 1); + const text = first(r, 1); + const block = name(r, 2); + const parts = text === undefined ? {} : dimensionTextParts(textOnce(text)); + const flags = num(r, 70) ?? 0; + const entity: ReadOrdinateDimension = { + ...base, + kind: "ordinate-dimension", + axis: (flags & 64) !== 0 ? "x" : "y", + origin: point(r, 10), + feature: point(r, 13), + leaderEnd: point(r, 14), + textAt: point(r, 11), + ...((flags & 128) !== 0 && { placed: true }), + ...(measurement !== undefined && { measurement }), + ...parts, + style: name(r, 3) ?? "Standard", + ...(block !== undefined && block !== "" && { block }), + }; + return { entity }; +} + /** * An arc length dimension: its center (group 15), the radius to the arc's first end (13), the arc's * angles (40 and 41, after the common group 70, in radians), a point of its own arc (10), and @@ -1323,6 +1355,7 @@ export function costOf(e: ReadEntity): number { return own + 5 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "angular-dimension": case "arc-length-dimension": + case "ordinate-dimension": return own + 6 + chars(e.text) + chars(e.textBelow) + chars(e.style) + chars(e.block); case "multileader": { let points = 3; diff --git a/src/read/model.ts b/src/read/model.ts index 45f9d55..11611ad 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -516,6 +516,30 @@ export interface ReadAngularDimension extends ReadEntityBase { readonly blockHandle?: string; } +/** + * An ordinate dimension: the distance from `origin` to `feature` along X or Y, as `axis` says, on + * a leader to `leaderEnd`. One drawn in a turned coordinate system is left out, as an entity + * of another kind. + */ +export interface ReadOrdinateDimension extends ReadEntityBase { + readonly kind: "ordinate-dimension"; + readonly axis: "x" | "y"; + readonly origin: Point; + readonly feature: Point; + readonly leaderEnd: Point; + /** The middle of its text. */ + readonly textAt: Point; + /** True where the file holds its text where it was placed, not where the leading CAD app puts it. */ + readonly placed?: boolean; + /** What it measures, as the file states it, as `ReadDimension`'s. */ + readonly measurement?: number; + readonly text?: string; + readonly textBelow?: string; + readonly style: string; + readonly block?: string; + readonly blockHandle?: string; +} + /** * An arc length dimension: the length of the arc about `center` of `radius` from `startAngle` to * `endAngle`, counterclockwise in degrees, as the file holds the arc. @@ -829,6 +853,7 @@ export type ReadEntity = | ReadRadialDimension | ReadAngularDimension | ReadArcLengthDimension + | ReadOrdinateDimension | ReadMultileader | ReadLeader | ReadSolid diff --git a/src/rules.ts b/src/rules.ts index 8009468..6b41742 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -4198,6 +4198,17 @@ export const ARC_LENGTH_INSIDE_SHORT = export const ARC_LENGTH_SYMBOL_BELOW = 'its words below the arc with the arc symbol is not laid out yet, so tsdraft refuses it. Use a style with arcSymbol "none"'; +/** An ordinate dimension without an axis. */ +export const ORDINATE_AXIS = 'axis must be "x" or "y": the coordinate it gives'; + +/** An ordinate dimension whose leader runs further across its axis than along it. */ +export const ORDINATE_ACROSS = + 'its leader runs further across than along: axis "x" gives the X coordinate, with its leader along Y, and "y" the Y, with its leader along X. Check that its axis is the one meant'; + +/** An ordinate dimension whose leader ends at its feature. */ +export const ORDINATE_NO_LEADER = + "its leader ends at its feature once they are written with the 6 decimals tsdraft writes and read as the leading CAD app reads them, so it has no leader"; + /** An angular dimension whose arc, or a piece of it, is all but a whole turn. */ export const ANGULAR_ARC_LOST = "its arc, or a piece of it, runs all but a whole turn, so its two angles are one once they are written with the 6 decimals tsdraft writes, and the leading CAD app draws such an arc as nothing"; diff --git a/src/shape.ts b/src/shape.ts index b959625..e349c34 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -30,6 +30,7 @@ import type { JoggedRadiusDimension, AngularDimension, ArcLengthDimension, + OrdinateDimension, Linetype, Paragraph, PatternLine, @@ -594,6 +595,18 @@ function shapes(all: boolean, typed = all): Shapes { }, { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, ), + "ordinate-dimension": fields( + { + kind, + layer: string, + style: ruled(string), + axis: ruled(string), + origin: point, + feature: point, + leaderEnd: point, + }, + { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + ), "angular-dimension": fields( { kind, diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 98e9125..2344090 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2201,6 +2201,20 @@ test("lint, inspectText, extents and toSVG stay bounded on any drawing, and lint textBelow: pick([long, "A\\P".repeat(5_000)]), })), ); + // Ordinate ones: straight, jogged or level, near the origin or far out. + (pick([drawing, layout]).entities as Data[]).push( + ...Array.from({ length: pick([1, 300]) }, (_, i): Data => ({ + kind: "ordinate-dimension", + layer: "0", + style: style.name, + axis: pick(["x", "y"]), + origin: [pick([0, -1e9]), 0], + feature: [pick([0.5, 1e6, 1e9]), i], + leaderEnd: [pick([0.5, 1e6 + 0.00001, -1e9]), i + pick([0, 3, -1e9])], + text: pick(["<>", long]), + textBelow: pick([long, "A\\P".repeat(5_000)]), + })), + ); style.arcSymbol = pick(["before", "above", "none"]); style.radialText = pick(["aligned", "horizontal"]); style.jogAngle = pick([5, 45, 90]); diff --git a/test/dimensions.test.ts b/test/dimensions.test.ts index 941c2ed..51c7e40 100644 --- a/test/dimensions.test.ts +++ b/test/dimensions.test.ts @@ -27,6 +27,7 @@ import { } from "../src/index.ts"; import { angleNumber, arrowRoom, measurementText, WIDEST_CHARACTERS } from "../src/dimensions.ts"; import { toDXFR2018 } from "../src/dxf-r2018.ts"; +import { heldNumber } from "../src/format.ts"; import { extents } from "../src/extents.ts"; const rule = (name: string) => (thrown: unknown) => @@ -1396,3 +1397,134 @@ test("an arc length dimension is refused where the leading CAD app would draw wh /arcSymbol must be "before", "above" or "none"/, ); }); + +test("an ordinate dimension is built, written and read back, its leader jogged or straight", async () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + d.ordinateDimension([3, 2], [3, 12], { style: "S", axis: "x" }); + d.ordinateDimension([-3, 2], [-13, -1], { style: "S", axis: "y", origin: [1, 1], id: "o" }); + // A jog of a hundred-thousandth at a million out is drawn straight, and one of a ten-thousandth + // jogs, and so do jogs of exactly 1e-10 of the coordinate in decimals. + d.ordinateDimension([1000000, 2], [1000000.00001, 12], { style: "S", axis: "x" }); + d.ordinateDimension([1000000, 2], [1000000.0002, 12], { style: "S", axis: "x" }); + d.ordinateDimension([2, 100000], [12, 100000.00001], { style: "S", axis: "y" }); + d.ordinateDimension([10000, 2], [10000.000001, 12], { style: "S", axis: "x" }); + // As the leading CAD app reads the written numbers, a jog of 1e-10 of the coordinate is a hair + // under at 30000, which a correctly rounded reading puts a hair over, and a hair over at 70000. + d.ordinateDimension([30000, 2], [30000.000003, 12], { style: "S", axis: "x" }); + d.ordinateDimension([70000, 2], [70000.000007, 12], { style: "S", axis: "x" }); + const drawing = d.build(); + assert.deepEqual(lint(drawing), []); + assert.deepEqual(fromJSON(toJSON(drawing)), drawing); + const style = drawing.dimensionStyles![0]!; + const [up, left, straight, jogged, ...edges] = drawing.entities.map((e) => + dimensionPicture(e as never, style), + ); + assert.equal(up!.label.value, "3.00"); + assert.deepEqual(up!.extensionLines, [ + [ + [3, 2.5], + [3, 12 + 0.5 + up!.textWidth], + ], + ]); + // Left from the feature, 3 below the line: a jog from 4 arrow sizes short of the end to 2. + assert.equal(left!.label.value, "1.00"); + assert.deepEqual( + left!.extensionLines.map(([a, b]) => [a, b]), + [ + [ + [-3.5, 2], + [-9, 2], + ], + [ + [-9, 2], + [-11, -1], + ], + [ + [-11, -1], + [-13 - 0.5 - left!.textWidth, -1], + ], + ], + ); + assert.deepEqual(straight!.extensionLines[0]![1], [ + heldNumber(1000000.00001), + 12 + 0.5 + straight!.textWidth, + ]); + assert.equal(straight!.extensionLines.length, 1); + assert.equal(jogged!.extensionLines.length, 3); + assert.deepEqual( + edges.map((picture) => picture.extensionLines.length), + [3, 3, 1, 3], + ); + // Two numbers written a ten-thousandth apart at 1e12 are one as the leading CAD app reads them, + // so the leader is level with its feature and runs back, down. + const level = { ...drawing.entities[0]!, feature: [3, 1e12], leaderEnd: [3.0001, 1e12 + 0.0001] }; + const [start, stop] = dimensionPicture(level as never, style).extensionLines[0]!; + assert.ok(start[1] < 1e12 && stop[1] < start[1], `${start} to ${stop}`); + // Each point is placed in the numbers the leading CAD app holds, so no line of a leader comes + // out of no length as that app reads it back, even where an arrow size is a hair at 1e12. + const hair = { ...style, arrowSize: 0.00014, extensionOffset: 0 }; + const thin = { ...drawing.entities[0]!, feature: [3, 1e12], leaderEnd: [4, 1e12 + 0.0007] }; + const lines = dimensionPicture(thin as never, hair).extensionLines; + assert.equal(lines.length, 3); + for (const [from, to] of lines) { + assert.notDeepEqual(from.map(heldNumber), to.map(heldNumber), `${from} to ${to}`); + } + // The end's side of the leader is placed from the end, however far out the feature is. + const far = { ...drawing.entities[0]!, feature: [3, 1e16], leaderEnd: [3, 1] }; + const centered = { ...style, textPlacement: "centered" } as const; + assert.deepEqual(dimensionPicture(far as never, centered).extensionLines.at(-1)![1], [3, 1]); + const above = dimensionPicture(far as never, style); + assert.deepEqual(above.extensionLines.at(-1)![1], [3, 1 - 0.5 - above.textWidth]); + const farJog = dimensionPicture({ ...far, leaderEnd: [4, 1] } as never, style); + assert.deepEqual( + farJog.extensionLines.slice(1).map(([from, to]) => [from, to]), + [ + [ + [3, 5], + [4, 3], + ], + [ + [4, 3], + [4, 1 - 0.5 - farJog.textWidth], + ], + ], + ); + const read = await readDXF(toDXF(drawing), { geometry: true }); + const ordinates = (read.model.entities ?? []).filter((e) => e.kind === "ordinate-dimension"); + assert.deepEqual( + ordinates.slice(0, 2).map((e) => [e.axis, e.origin, e.feature, e.leaderEnd, e.measurement]), + [ + ["x", [0, 0], [3, 2], [3, 12], 3], + ["y", [1, 1], [-3, 2], [-13, -1], 1], + ], + ); +}); + +test("an ordinate dimension needs an axis and a leader, and lint warns of one whose leader runs across", () => { + const d = createDrawing({ units: "in" }); + d.dimensionStyle({ ...sizes, name: "S" }); + assert.throws( + // @ts-expect-error: an ordinate dimension's axis is "x" or "y". + () => d.ordinateDimension([0, 0], [0, 5], { style: "S", axis: "z" }), + /axis must be "x" or "y"/, + ); + assert.throws( + // @ts-expect-error: an ordinate dimension has an axis. + () => d.ordinateDimension([0, 0], [0, 5], { style: "S" }), + /axis must be "x" or "y"/, + ); + assert.throws( + () => d.ordinateDimension([2, 3], [2.0000001, 3], { style: "S", axis: "x" }), + /has no leader/, + ); + assert.throws( + () => d.ordinateDimension([3, 1e12], [3, 1e12 + 0.0001], { style: "S", axis: "x" }), + /has no leader/, + ); + d.ordinateDimension([2, 3], [9, 4], { style: "S", axis: "x" }); + assert.deepEqual( + lint(d.build()).map((x) => [x.rule, x.severity]), + [["dimension", "warning"]], + ); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index fc899ad..e7efa7c 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -83,6 +83,11 @@ export function readProblems( const point = (p: Point): Point => [written(p[0]), written(p[1])]; const twice = (value: string): string => (by === "tsdraft" ? value : textTwice(exported(value))); const once = (value: string): string => (by === "tsdraft" ? value : textOnce(exported(value))); + // A dimension's text as a read holds it, which leaves out `<>` alone above words below. + const dimensionText = (want: { readonly text?: string; readonly textBelow?: string }) => + want.text === undefined || (want.text === "<>" && want.textBelow !== undefined) + ? undefined + : once(want.text); const sameName = (a: string | undefined, b: string): boolean => a !== undefined && layerKey(a) === layerKey(b); @@ -502,7 +507,7 @@ export function readProblems( const angle = want.kind === "linear-dimension" ? written(dimensionAngle(want)) : 0; if (!nearAngle(got.angle ?? 0, angle)) say(`${label}: along ${got.angle}, expected ${angle}`); - if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } const below = want.textBelow === undefined ? undefined : once(want.textBelow); @@ -558,7 +563,42 @@ export function readProblems( !nearPoint(got.jog ?? [NaN, NaN], point(want.jog))) ) say(`${label}: starts at ${got.start}, jogs at ${got.jog}`); - if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { + if ((got.text ?? undefined) !== dimensionText(want)) { + say(`${label}: text ${JSON.stringify(got.text)}`); + } + const below = want.textBelow === undefined ? undefined : once(want.textBelow); + if ((got.textBelow ?? undefined) !== below) { + say(`${label}: text below ${JSON.stringify(got.textBelow)}`); + } + const style = dimensionStyles.get(layerKey(want.style)); + if (!style) return; + const font = drawing.textStyles?.find((t) => sameName(t.name, style.textStyle ?? "")); + const picture = dimensionPicture(want, style, font); + if (by === "tsdraft" && !nearPoint(got.textAt, point(picture.textPoint))) { + say(`${label}: its text at ${got.textAt}, expected ${picture.textPoint}`); + } + const measurement = + dimensionMeasure(want).measurement * written(style.measurementScale ?? 1); + if ( + got.measurement === undefined || + Math.abs(got.measurement - measurement) > 1e-9 * Math.max(1, Math.abs(measurement)) + ) { + say(`${label}: measures ${got.measurement}, expected ${measurement}`); + } + return; + } + case "ordinate-dimension": { + if (!kind("ordinate-dimension") || got.kind !== "ordinate-dimension") return; + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if ( + got.axis !== want.axis || + !nearPoint(got.origin, point(want.origin)) || + !nearPoint(got.feature, point(want.feature)) || + !nearPoint(got.leaderEnd, point(want.leaderEnd)) + ) { + say(`${label}: ${got.axis} of ${got.feature} from ${got.origin}, to ${got.leaderEnd}`); + } + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } const below = want.textBelow === undefined ? undefined : once(want.textBelow); @@ -598,7 +638,7 @@ export function readProblems( `${label}: about ${got.center} of ${got.radius}, ${got.startAngle} to ${got.endAngle}`, ); } - if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } const style = dimensionStyles.get(layerKey(want.style)); @@ -627,7 +667,7 @@ export function readProblems( // The leading CAD app keeps a point of the arc of its own choosing. if (by === "tsdraft" && !nearPoint(got.at, point(want.at))) say(`${label}: arc at ${got.at}`); - if ((got.text ?? undefined) !== (want.text === undefined ? undefined : once(want.text))) { + if ((got.text ?? undefined) !== dimensionText(want)) { say(`${label}: text ${JSON.stringify(got.text)}`); } const below = want.textBelow === undefined ? undefined : once(want.textBelow); diff --git a/test/read.test.ts b/test/read.test.ts index 04f0ca1..331a6fc 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -1009,10 +1009,12 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only [370, -1], [48, 1], ]), + // An ordinate drawn in a turned coordinate system. [ [0, "DIMENSION"], [8, "A"], [70, 38], + [51, 330], ], [ [0, "MULTILEADER"], @@ -1064,7 +1066,7 @@ test("readDXF keeps the pen an entity sets itself, and counts what it reads only ); assert.deepEqual(Object.keys(plain(plainLine) as object).sort(), ["from", "kind", "layer", "to"]); assert.deepEqual(plain(read.model.other), { - "DIMENSION ordinate": 1, + "DIMENSION ordinate in a turned coordinate system": 1, "MULTILEADER in 3D": 1, }); assert.deepEqual(plain(read.unread.malformed), { "LINE with a number that is not finite": 1 }); diff --git a/test/shape.test.ts b/test/shape.test.ts index d4b49e8..ab47f0f 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -305,6 +305,18 @@ const kinds: { textBelow: "MIN.", id: "h-a", }, + "ordinate-dimension": { + kind: "ordinate-dimension", + layer: "0", + style: "ARCH", + axis: "x", + origin: [1, 2], + feature: [10, 5], + leaderEnd: [10, 15], + text: "<> TYP", + textBelow: "MIN.", + id: "h-o", + }, }; /** A polyline of one width, with every field the polyline of `kinds` leaves out. */ @@ -806,7 +818,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #20: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #21: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ From 36c19fdd1039250bce2a01c93babc7c1f7f17f22 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 05:25:31 -0500 Subject: [PATCH 21/35] Linetypes with text: a pipe's letters along it, written, read and plotted as CAD programs draw them Linetypes with text, in R2018 drawings: a pipe with its letters along it. - A linetype's `marks` draw a text, such as `W`, at the end of a length of its pattern, by `after`, in one of the drawing's text styles. `orient` turns it with the line (`relative`), from the X axis (`absolute`), or `upright`, so it reads from the left; `rotation` turns it further, and `offset` moves it along the line and to its left. - `parseLinetypes(text)` reads a firm's linetype file, texts and shapes included. tsdraft ships no linetype of text of its own. - A polyline's `linetypeGeneration` runs the pattern on past its vertices as one stretch, so a short run between bends keeps its letters instead of being drawn solid. Around a closed polyline the pattern is stretched to a whole number of repeats. A polyline with a tapered side starts the pattern on each side, as CAD programs do. - Both writers write marks and the flag, `readDXF` and `readDWG` read them back (`ReadLinetype.marks`, `ReadPolyline.linetypeGeneration`), and `toSVG` and `toPDF` draw the letters where CAD programs plot them: with each whole repeat of the pattern, along the side or arc they land on, in the style's font, at the size of the paper through a viewport and in an insert of any scale. - A linetype's shapes are written and read by their numbers in a shape file. The plot leaves a gap for each, and `lint` warns `linetype-shape` where such a linetype is drawn. A shape given by name is refused until the shape file can number it. - The plan set example's site sheet letters its water, sewer and electric runs this way. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 7 +- CHANGELOG.md | 12 + GUIDE.md | 4 + README.md | 6 +- docs/format.md | 3 + docs/reading.md | 7 +- docs/rules.md | 11 + examples/plan-set/lib/kit.ts | 16 + examples/plan-set/sheets/site.ts | 38 ++- src/drawing.ts | 89 ++++- src/dxf-r2018.ts | 78 ++++- src/index.ts | 17 +- src/linetypes.ts | 162 ++++++++- src/lint.ts | 49 ++- src/read/check.ts | 18 + src/read/dxf.ts | 103 +++++- src/read/entities.ts | 4 +- src/read/model.ts | 28 ++ src/rules.ts | 110 ++++++ src/shape.ts | 30 +- src/standard/lint.ts | 8 + src/svg.ts | 567 +++++++++++++++++++++++++++++-- test/linetypes.test.ts | 172 ++++++++++ test/polylines.test.ts | 32 ++ test/shape.test.ts | 40 ++- 25 files changed, 1534 insertions(+), 77 deletions(-) create mode 100644 test/linetypes.test.ts diff --git a/AGENTS.md b/AGENTS.md index 370979a..e1b0f65 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -227,7 +227,12 @@ are each half of the first dash and of what is left over, and a stretch shorter than its pattern is solid. A circle holds the whole number of patterns nearest its length, stretched alike to go round it, from a dash at angle 0. `cut` in `dashedPath` is the one place that - does it. `toSVG` draws a layout with `elements`, the + does it. A linetype's `marks` are placed by `markSpots`, with each whole pattern of a fitted + stretch, and `letterAt` sets each text in the frame of the side it lands on, the line's + direction in its own coordinates deciding `upright`; on an arc that frame is the straight piece + the leading CAD app cuts the arc into, `arcFrame`, 1/1200 inch from it on the paper, which + `Look.chord` holds. A polyline's `linetypeGeneration` cuts its sides as one course, `courseOf`, + from its second point when it is closed. `toSVG` draws a layout with `elements`, the walk it draws model space with, under a `Look` that says how wide and what color a pen is. - A rule the leading CAD app enforces lives in `src/rules.ts` twice: as a type, so a wrong literal is a compile error, and as a runtime check with the same message. The diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c26194..35bcff9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- Linetypes with text, in R2018 drawings: a pipe with its letters along it. A linetype's `marks` + draw a text, such as `W`, at the end of a length of its pattern, by `after`, in one of the + drawing's text styles, turned with the line, from the X axis, or `upright` so it reads from the + left, and moved by `offset` along the line and to its left. `parseLinetypes(text)` reads a firm's + linetype file. A polyline's `linetypeGeneration` runs the pattern on past its vertices as one + stretch, so a side shorter than the pattern is not drawn solid without its letters. Both + writers write them, `readDXF` and `readDWG` read them back, and `toSVG` and `toPDF` draw the + letters where CAD programs plot them: with each whole pattern, along the side they land on, at + the size of the paper in a viewport or an insert. A linetype's shapes are written and read as + their numbers in a shape file, and the plot leaves a gap for each, with the warning + `linetype-shape` where one is drawn. + - Ellipses and splines, in R2018 drawings. `d.ellipse(center, majorAxis, ratio)` draws an ellipse, or an arc of one with `startParameter` and `endParameter`. `d.spline(fitPoints)` draws the cubic CAD programs fit through the points, with `startTangent`, `endTangent` or `closed`, diff --git a/GUIDE.md b/GUIDE.md index 22e4148..7deb39b 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -510,6 +510,10 @@ d.layout("C-101", { paper: "ARCH D" }, (sheet) => { - In a drawing with a layout, `linetypeScale` is a length of paper: dashes plot as long as the pattern times it, in every viewport. The picture of model space draws the same dashes that many drawing units long, often too short to see, so judge linetypes on the sheet's picture. +- Letter a pipe with its linetype, not with texts beside it: `parseLinetypes(text)` reads the + firm's linetype file, a linetype's `marks` draw its letters at each repeat of its pattern, and a + polyline drawn with `linetypeGeneration: true` runs the pattern on past its vertices, so short + runs between bends still get their letters. The letters' text style must be one of the drawing's. - The sheet plots in black with `monochrome.ctb`. Pass `plotStyle: "acad.ctb"` to plot each layer in its color, or `"Grayscale.ctb"` in grays. `PLOT_STYLE_TABLES` lists them. - Define blocks outside `layout`, and insert them inside it. An `id` is unique across model diff --git a/README.md b/README.md index 5bb3b56..62de3cc 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,9 @@ Entities go on layer `0` unless they are drawn inside a `layer()` callback. Linetypes and lineweights are set on a layer, and an entity draws ByLayer unless it is given its own. `DASHED`, `HIDDEN`, `CENTER`, `PHANTOM`, `DASHDOT` and `DOT` are the leading CAD app's own definitions; `d.linetype({ name, pattern })` defines another, -with dashes as positive lengths, gaps as negative ones and dots as 0. A +with dashes as positive lengths, gaps as negative ones and dots as 0. Its `marks` draw texts +along the line, such as a water main's letters, and `parseLinetypes` reads a firm's linetype file. A +polyline's `linetypeGeneration` runs the pattern on past its vertices. A lineweight is in millimetres. A text is in the style `Standard` unless it names another. `d.textStyle({ name, @@ -317,7 +319,7 @@ layers or twist the view, and layers that are off, frozen, locked or not plotted [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. It does not yet have overlines in paragraph text, ellipses, splines or points, tables, color or transparency set on one -entity, linetypes with text or shapes, PDF underlays, or the other kinds of dimension. +entity, the shapes of a linetype in its plot, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit and write again. [Reading drawing files](docs/reading.md) has what it reads. diff --git a/docs/format.md b/docs/format.md index 42edbc0..2091bd6 100644 --- a/docs/format.md +++ b/docs/format.md @@ -33,6 +33,9 @@ A drawing lists its text styles in `textStyles`, and leaves the field out when i `"left"` and `"baseline"`, so a drawing that uses none of them has the JSON it had before they existed. +A linetype has `marks` only where it draws a text or a shape, and a polyline `linetypeGeneration` +only where it is `true`, so a drawing with neither has the JSON it had before they existed. + A drawing lists its blocks in `blocks`, and leaves the field out when it has none. A block has a `name`, its `entities`, and where they differ from their defaults a `base` point and its `attributes`: each a `tag`, a `value`, a `layer` and the fields of a text, with a `prompt` diff --git a/docs/reading.md b/docs/reading.md index ee73b86..c84c861 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -51,7 +51,9 @@ states and keeps each object's handle, and it keeps going past what it does not - `sha256` and `bytes` of the file, its `version`, and `header`: `$INSUNITS`, `$MEASUREMENT`, `$LTSCALE`, `$PSLTSCALE`, `$MSLTSCALE`, `$DIMSCALE` and the current styles. -- The tables: `layers` with their state, `linetypes`, `textStyles` and `dimensionStyles`, each +- The tables: `layers` with their state, `linetypes`, each with the `marks` it draws as a + `Linetype` holds them, a text's `style` by name and its `height` times its style's fixed height, + a shape by its number and its `file`, `textStyles` and `dimensionStyles`, each style with whether it is annotative, and a dimension style with the units it writes lengths in, where its text goes, how it writes a fraction, its lineweights and its arrowheads' block. Two entries of one name are both kept, in the order of the file. - `blocks`: each with its base point, its attribute definitions and its entities, below. What @@ -104,7 +106,8 @@ leader: - `line`, `circle` and `arc`, and `polyline` for a lightweight polyline or a 2D one, open or closed, with `bulges`, one for each side, when a side is an arc, and `width`, one width for every side, or `widths`, each side's width at its start and its end, when a side is wide, as - a `Polyline` holds them. A 2D polyline's vertex with no width of its own has the polyline's. + a `Polyline` holds them, and `linetypeGeneration` when its pattern runs on past its vertices. + A 2D polyline's vertex with no width of its own has the polyline's. - `text`: a text of one line, with its `value`. - `insert`: its block, by name and by the handle of its record in `blockHandle`, its point, scale and rotation, `tags`, and with `geometry` its `attributes`: each a text with its `tag` diff --git a/docs/rules.md b/docs/rules.md index 0054fd8..145293a 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -107,6 +107,14 @@ it would take `1e+100` for `1e+10` and report nothing. or gap would become a dot: use 0.000001 or more in size, or 0 for a dot. The lengths, added up without their signs, must be under 1e100, because the total is written too. +- A linetype's `marks` are each at the end of a length of its pattern, by `after`, in order, at + most one at a length. A text is a string of at least one character in one of the drawing's text + styles, `Standard` unless it names one, and its height is greater than 0 as written. A shape is a + whole number from 1 to 65535 in a named shape file, and its scale is greater than 0: a shape by + its name, as a linetype file gives it, is refused, since a drawing holds a shape by its number. + `orient` is `relative`, `absolute` or `upright`. A linetype's texts may take 256 characters + together, counting one more for each, since a DWG holds them in 512 bytes. R2018 only, as is a + polyline's `linetypeGeneration`. - A description is a single line, with no characters text cannot hold, and is at most 249 characters, where the leading CAD app cuts it. - A text style has one of the fonts in `FONTS`: an SHX font by its file name, @@ -304,6 +312,9 @@ it would take `1e+100` for `1e+10` and report nothing. - A viewport that reaches past its layout's paper. The leading CAD app plots a layout as far as its paper goes. - A viewport that shows none of the drawing: nothing in model space lies in the box it shows. +- `linetype-shape`: a linetype that a layer or an entity draws in, with shapes of a shape file. + CAD programs draw a shape from its file, which the drawing names and does not hold, and + tsdraft's plot leaves a gap where each goes. - `check-capped`: where `lint` stopped the checks it makes again for what a drawing repeats: each attribute an insert places and each handle it takes past its first 64, a tag of 256 characters or more each time an insert's values are searched for it, what each diff --git a/examples/plan-set/lib/kit.ts b/examples/plan-set/lib/kit.ts index c1c9067..8b7d161 100644 --- a/examples/plan-set/lib/kit.ts +++ b/examples/plan-set/lib/kit.ts @@ -181,6 +181,13 @@ export const LAYERS = { pAnno: "P-ANNO-TEXT", } as const; +/** The linetypes of the site's utilities: each name, its letters, and where they start in its gap. */ +export const UTILITY_LINETYPES = [ + ["UTIL-WATER", "W", -0.105], + ["UTIL-SEWER", "SS", -0.15], + ["UTIL-ELEC", "UE", -0.155], +] as const; + /** Defines every layer of the set, with its color, linetype and pen. */ export function defineLayers(d: D): void { const L = LAYERS; @@ -190,6 +197,15 @@ export function defineLayers(d: D): void { d.linetype(HIDDEN); d.linetype(CENTER); d.linetype(PHANTOM); + // The site's utilities, each lettered along its run in the notes' style. + for (const [name, letters, along] of UTILITY_LINETYPES) { + d.linetype({ + name, + description: `${letters} ---- ${letters} ----`, + pattern: [1.5, -0.2, -0.2], + marks: [{ after: 1, text: letters, style: NOTES, height: 0.16, offset: [along, -0.08] }], + }); + } layer(L.ttlb, 7, 0.35); layer(L.text, 7, 0.25); d.layer(L.vport, { color: 8, plot: false }); diff --git a/examples/plan-set/sheets/site.ts b/examples/plan-set/sheets/site.ts index e678d8e..32be2ee 100644 --- a/examples/plan-set/sheets/site.ts +++ b/examples/plan-set/sheets/site.ts @@ -138,19 +138,33 @@ function site(d: D): void { }); d.layer(LAYERS.util, {}, () => { // Water service from the meter, sewer lateral to its cleanout, underground electric. + // Each is lettered along its run, and the pattern runs on past its bends. + const run = (linetype: string) => ({ linetype, linetypeGeneration: true }); const meter: Point = [LOT.width - 60, -18]; - d.polyline([meter, [meter[0], HOUSE_AT[1] + 200], [HOUSE_AT[0] + W, HOUSE_AT[1] + 200]]); - d.polyline([ - [120, cl], - [120, -12], - [120, HOUSE_AT[1] + 340], - [HOUSE_AT[0], HOUSE_AT[1] + 340], - ]); - d.polyline([ - [60, cl - 60], - [60, HOUSE_AT[1] + 240], - [HOUSE_AT[0], HOUSE_AT[1] + 240], - ]); + d.polyline( + [meter, [meter[0], HOUSE_AT[1] + 200], [HOUSE_AT[0] + W, HOUSE_AT[1] + 200]], + false, + run("UTIL-WATER"), + ); + d.polyline( + [ + [120, cl], + [120, -12], + [120, HOUSE_AT[1] + 340], + [HOUSE_AT[0], HOUSE_AT[1] + 340], + ], + false, + run("UTIL-SEWER"), + ); + d.polyline( + [ + [60, cl - 60], + [60, HOUSE_AT[1] + 240], + [HOUSE_AT[0], HOUSE_AT[1] + 240], + ], + false, + run("UTIL-ELEC"), + ); }); d.layer(LAYERS.util, {}, () => { d.rect([LOT.width - 72, -30], 24, 24); diff --git a/src/drawing.ts b/src/drawing.ts index 156db7d..5b50bed 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -112,6 +112,7 @@ import { lineweightProblem, linetypeNameProblem, linetypeProblem, + marksProblem, linetypeScaleProblem, magnitudeProblem, layerNameProblem, @@ -214,6 +215,7 @@ import { type Positive, type R12Layouts, type Ratio, + type MARK_ORIENTS, type TEXT_ALIGNS, type TEXT_VERTICAL_ALIGNS, type LINE_SPACING_STYLES, @@ -362,8 +364,59 @@ export interface Linetype { readonly description: string; /** A dash is a positive length, a gap a negative one, and a dot 0. Empty for a solid line. */ readonly pattern: readonly number[]; + /** + * What the pattern draws besides its dashes: a text, such as a pipe's letters, or a shape of a + * shape file, each at the end of a length of the pattern. In order of `after`, one a length. + * R2018 only. + */ + readonly marks?: readonly LinetypeMark[]; +} + +/** + * How a linetype's mark is turned: `"relative"` to the line, `"absolute"` to the drawing's X + * axis, or `"upright"`, along the line and turned half a turn where the line runs leftward, from + * just past straight up to just short of straight down, so that it reads from the left. + */ +export type MarkOrient = (typeof MARK_ORIENTS)[number]; + +interface MarkBase { + /** The index of the length of the pattern the mark is drawn at the end of, from 0. */ + readonly after: number; + /** In degrees counterclockwise, from the line or the X axis as `orient` says. Defaults to 0. */ + readonly rotation?: number; + /** Defaults to `"relative"`. */ + readonly orient?: MarkOrient; + /** + * Where the mark is from the end of its length: along the line, and to its left. In the + * pattern's units, scaled as its lengths are. Defaults to `[0, 0]`. + */ + readonly offset?: Point; +} + +/** A text a linetype draws, such as the letters along a pipe. */ +export interface LinetypeText extends MarkBase { + readonly text: string; + /** A text style of the drawing. Defaults to `"Standard"`. */ + readonly style?: string; + /** The height of its capitals, in the pattern's units, scaled as its lengths are. */ + readonly height: number; } +/** + * A shape of a shape file a linetype draws, by its number in the file. tsdraft's plot leaves a + * gap where it goes. + */ +export interface LinetypeShape extends MarkBase { + /** Its number in its shape file. A name, as a linetype file gives it, is not written. */ + readonly shape: number | string; + /** The shape file, as the drawing names it, such as `"shapes.shx"`. */ + readonly file: string; + /** Its size, as a multiple of the shape's own, scaled as the pattern's lengths are. */ + readonly scale: number; +} + +export type LinetypeMark = LinetypeText | LinetypeShape; + /** * The lineweights the leading CAD app offers, in millimetres. A lineweight is how wide a line * plots, and how wide that app shows it when LWDISPLAY is on. @@ -437,6 +490,13 @@ export interface Polyline extends EntityBase { readonly width?: number; /** The width of each side at its start and at its end, one pair for each side. R2018 only. */ readonly widths?: readonly (readonly [start: number, end: number])[]; + /** + * Runs the linetype's pattern on past each vertex, as one stretch along the whole polyline, + * where it otherwise starts again on each side, so that a side shorter than the pattern is not + * drawn solid. Around a closed polyline the pattern is stretched to a whole number of times. + * R2018 only. + */ + readonly linetypeGeneration?: boolean; } export interface Circle extends EntityBase { @@ -1481,6 +1541,11 @@ export interface LinetypeDefinition< readonly description?: Description; /** A dash is a positive length, a gap a negative one, and a dot 0. Empty for a solid line. */ readonly pattern: Pattern

; + /** + * Texts and shapes the pattern draws, each at the end of a length of it, in order: see + * `Linetype.marks`. A text's style is one of the drawing's. + */ + readonly marks?: readonly LinetypeMark[]; } /** What a layer or an entity may be given as its linetype: a name, or a definition. */ @@ -1795,6 +1860,8 @@ export interface PolylineOptions< readonly bulges?: V extends "R12" ? R12Polylines : readonly number[]; /** The width of each side at its start and at its end, one pair for each side. R2018 only. */ readonly widths?: V extends "R12" ? R12Polylines : readonly (readonly [number, number])[]; + /** Runs the linetype's pattern on past each vertex: see `Polyline.linetypeGeneration`. R2018 only. */ + readonly linetypeGeneration?: V extends "R12" ? R12Polylines : boolean; /** * Rounds every corner with an arc of this radius, tangent to both sides, as a bar's bend or a * duct's turn is drawn. The polyline then holds the arcs' ends in place of its corners. With @@ -3717,9 +3784,15 @@ export class DrawingBuilder< readonly width?: unknown; readonly widths?: unknown; readonly radius?: unknown; + readonly linetypeGeneration?: unknown; }, ): Polyline { - const { width, widths, radius } = given; + const { width, widths, radius, linetypeGeneration } = given; + if (linetypeGeneration !== undefined) { + if (this.dxf === "R12") refuse("geometry", R12_ONLY.polylines); + if (typeof linetypeGeneration !== "boolean") + refuse("geometry", "linetypeGeneration must be true or false"); + } let { bulges } = given; if ( this.dxf === "R12" && @@ -3757,6 +3830,7 @@ export class DrawingBuilder< ([start, end]) => [start, end] as const, ), }), + ...(linetypeGeneration === true ? { linetypeGeneration } : {}), }; } @@ -6392,12 +6466,11 @@ export class DrawingBuilder< */ #define(definition: LinetypeDefinition, inline = false): string { const label = `Linetype ${JSON.stringify(definition.name)}`; - const problem = linetypeProblem( - definition.name, - definition.description ?? "", - definition.pattern, - ); + const problem = + linetypeProblem(definition.name, definition.description ?? "", definition.pattern) ?? + marksProblem(definition.marks, definition.pattern as readonly number[]); if (problem) refuse("linetype", `${label}: ${problem}`); + const marks = definition.marks?.map((m) => ({ ...m })) ?? []; // linetypeProblem has checked the types. const name = definition.name as string; const description = (definition.description ?? "") as string; @@ -6411,7 +6484,8 @@ export class DrawingBuilder< const same = existing.description === description && existing.pattern.length === lengths.length && - existing.pattern.every((length, i) => length === lengths[i]); + existing.pattern.every((length, i) => length === lengths[i]) && + JSON.stringify(existing.marks ?? []) === JSON.stringify(marks); if (!same) { refuse( "linetype", @@ -6425,6 +6499,7 @@ export class DrawingBuilder< name: stored, description, pattern: [...lengths], + ...(marks.length === 0 ? {} : { marks }), }); if (!this.#linetypesAudited.has(auditKey)) this.#linetypesAudited.set(auditKey, name); return stored; diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 1dba5ca..fa11f62 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -50,6 +50,7 @@ import type { Leader, LeaderStyle, Linetype, + LinetypeMark, Point, Text, TextStyle, @@ -152,7 +153,7 @@ import { validLeaderStyleHandle, } from "./leaders.ts"; import { entityLinetype, layerLinetype, lineweightCode, patternLength } from "./linetypes.ts"; -import { idKey, shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; +import { idKey, isStandardTextStyle, shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; /** `$INSUNITS` codes from the DXF Reference. */ const INSUNITS: Record = { in: 1, ft: 2, mm: 4, cm: 5, m: 6 }; @@ -318,6 +319,33 @@ export function toDXFR2018( const linetypeHandles = linetypes.map(() => handle()); // A leader style draws its shafts in the linetype ByBlock, which it holds by its handle. const linetypeByBlock = linetypeHandles[0]!; + const textStyles = drawing.textStyles ?? []; + // A linetype's mark holds its text style, or its shape file's, by its handle. The shape files + // are styles of their own after the text styles, one for each file, in the order first named. + const shapeFiles = [ + ...new Map( + linetypes.flatMap((t) => + (t.marks ?? []).flatMap((m) => ("shape" in m ? [[m.file.toLowerCase(), m.file]] : [])), + ) as [string, string][], + ).values(), + ]; + let styleHandles: { standard: string; list: string[]; shapes: string[] } | undefined; + const allocateStyles = () => ({ + standard: handle(), + list: textStyles.map(() => handle()), + shapes: shapeFiles.map(() => handle()), + }); + // A drawing whose linetypes have no marks numbers its styles after its linetypes' table. + if (linetypes.some((t) => (t.marks?.length ?? 0) > 0)) styleHandles = allocateStyles(); + const markStyle = (m: LinetypeMark): string => { + const handles = styleHandles!; + if ("shape" in m) + return handles.shapes[shapeFiles.findIndex((f) => f.toLowerCase() === m.file.toLowerCase())]!; + const name = m.style ?? STANDARD_TEXT_STYLE; + if (isStandardTextStyle(name)) return handles.standard; + const key = layerKey(name); + return handles.list[textStyles.findIndex((t) => layerKey(t.name) === key)] ?? handles.standard; + }; writeTable( g, handle, @@ -332,10 +360,25 @@ export function toDXFR2018( g(72, 65); // alignment: "A" g(73, linetype.pattern.length); g(40, patternLength(linetype.pattern.map(written))); - for (const length of linetype.pattern) { + const marks = linetype.marks ?? []; + linetype.pattern.forEach((length, i) => { g(49, length); - g(74, 0); // a plain dash, gap or dot - } + const m = marks.find((mark) => mark.after === i); + if (m === undefined) { + g(74, 0); // a plain dash, gap or dot + return; + } + const text = "text" in m; + const orient = m.orient ?? "relative"; + g(74, (text ? 2 : 4) | (orient === "absolute" ? 1 : 0) | (orient === "upright" ? 8 : 0)); + g(75, text ? 0 : (m.shape as number)); + g(340, markStyle(m)); + g(46, text ? m.height : m.scale); + g(50, m.rotation ?? 0); + g(44, m.offset?.[0] ?? 0); + g(45, m.offset?.[1] ?? 0); + if (text) g(9, dxfOnce(m.text)); + }); }, })), ); @@ -362,10 +405,10 @@ export function toDXFR2018( }, })), ); - const textStyles = drawing.textStyles ?? []; - const standardStyle = handle(); + styleHandles ??= allocateStyles(); + const standardStyle = styleHandles.standard; // Each text style has a handle of its own. A dimension style holds the first of a name. - const textStyleHandleList = textStyles.map(() => handle()); + const textStyleHandleList = styleHandles.list; const textStyleHandles = new Map( textStyles.map((style, i) => [layerKey(style.name), textStyleHandleList[i]!]).reverse() as [ string, @@ -411,6 +454,24 @@ export function toDXFR2018( } }, })), + // A shape file is a style with no name and flag 1, which the leading CAD app makes for a + // linetype's shapes. + ...shapeFiles.map((file, i) => ({ + type: "STYLE", + subclass: "AcDbTextStyleTableRecord", + name: "", + handle: styleHandles!.shapes[i]!, + flags: 1, + fields: (g: Group) => { + g(40, 0); + g(41, 1); + g(50, 0); + g(71, 0); + g(42, 0.2); + g(3, dxfOnce(file)); + g(4, ""); + }, + })), ]); // Keyed as style names are compared, so a text that names `notes` takes the style `NOTES`. const stylesByKey = new Map(textStyles.map((style) => [layerKey(style.name), style])); @@ -1323,7 +1384,8 @@ function writeEntity( case "polyline": { begin("LWPOLYLINE", "AcDbPolyline"); g(90, e.points.length); - g(70, e.closed ? 1 : 0); + // Flag 128 runs the linetype's pattern on past each vertex. + g(70, (e.closed ? 1 : 0) | (e.linetypeGeneration ? 128 : 0)); // A width for each side is written at each point, and a constant width once. if (e.widths === undefined) g(43, e.width ?? 0); e.points.forEach(([x, y], i) => { diff --git a/src/index.ts b/src/index.ts index 204d21e..02c3bda 100644 --- a/src/index.ts +++ b/src/index.ts @@ -128,6 +128,10 @@ export { type Linetype, type LinetypeChoice, type LinetypeDefinition, + type LinetypeMark, + type LinetypeShape, + type LinetypeText, + type MarkOrient, type Lineweight, type Paragraph, type ParagraphAlign, @@ -268,7 +272,17 @@ export { type LeaderSizes, } from "./leaders.ts"; export { DrawingError, lint, type Diagnostic, type LintOptions, type LintRule } from "./lint.ts"; -export { CENTER, DASHDOT, DASHED, DOT, HIDDEN, LINEWEIGHTS, PHANTOM } from "./linetypes.ts"; +export { + CENTER, + DASHDOT, + DASHED, + DOT, + HIDDEN, + LINETYPE_FILE_LENGTH, + LINEWEIGHTS, + parseLinetypes, + PHANTOM, +} from "./linetypes.ts"; export { lineSpacing, measureText, type TextMeasure, type TextToMeasure } from "./measure.ts"; export { bold, @@ -459,6 +473,7 @@ export { type ReadLayout, type ReadLine, type ReadLinetype, + type ReadLinetypeMark, type ReadMask, type ReadMtext, type ReadPatternLine, diff --git a/src/linetypes.ts b/src/linetypes.ts index 9674fc3..fa88b8e 100644 --- a/src/linetypes.ts +++ b/src/linetypes.ts @@ -1,6 +1,6 @@ // Linetypes and lineweights: the ones every drawing has, the ones plans use, and how the // writers name and number them. -import type { Layer, Lineweight, Linetype } from "./drawing.ts"; +import type { Layer, Lineweight, Linetype, LinetypeMark, MarkOrient } from "./drawing.ts"; import { layerKey } from "./layers.ts"; /** Every lineweight the leading CAD app offers, in millimetres, from thinnest to widest. */ @@ -87,3 +87,163 @@ export function lineweightCode(value: number | "ByLayer" | "ByBlock" | "Default" export function patternLength(pattern: readonly number[]): number { return pattern.reduce((sum, length) => sum + Math.abs(length), 0); } + +/** The most characters of a linetype file `parseLinetypes` reads. */ +export const LINETYPE_FILE_LENGTH = 1_000_000; + +/** + * The linetypes of a linetype file's text, in the format CAD programs read: a linetype starts at a + * line `*NAME,description`, and the line after it is `A,` and its pattern, each length a dash + * when positive, a gap when negative and a dot when 0. A text in brackets, `["W",STYLE,S=0.1, + * R=0,X=-0.05,Y=-0.05]`, or a shape, `[NAME,file.shx,S=0.1]`, is drawn at the end of the length + * before it, turned by `R=` from the line, `A=` from the X axis or `U=` upright. A `;` starts a + * comment. A shape is given by its name in its file, which the drawing does not hold: a drawing + * takes a shape by its number. + * + * @throws RangeError for a line it cannot read, naming its number, and for text past + * `LINETYPE_FILE_LENGTH` characters. + */ +export function parseLinetypes(text: string): Linetype[] { + if (typeof text !== "string") throw new RangeError("A linetype file's text must be a string"); + if (text.length > LINETYPE_FILE_LENGTH) + throw new RangeError(`A linetype file is at most ${LINETYPE_FILE_LENGTH} characters`); + const out: Linetype[] = []; + let open: { name: string; description: string; line: number } | undefined; + const rows = text.split(/\r\n|\r|\n/); + rows.forEach((row, index) => { + const line = withoutComment(row).trim(); + if (line === "") return; + const where = `line ${index + 1} of the linetype file`; + if (line.startsWith("*")) { + if (open) + throw new RangeError(`line ${open.line} of the linetype file: ${open.name} has no pattern`); + const at = line.indexOf(","); + const name = (at < 0 ? line.slice(1) : line.slice(1, at)).trim(); + if (name === "") throw new RangeError(`${where}: a linetype needs a name after *`); + open = { name, description: at < 0 ? "" : line.slice(at + 1).trim(), line: index + 1 }; + return; + } + if (!open) throw new RangeError(`${where}: a pattern before any *NAME`); + const items = splitItems(line, where); + if ((items[0] ?? "").trim().toUpperCase() !== "A") + throw new RangeError(`${where}: a pattern starts with A, its alignment`); + const pattern: number[] = []; + const marks: LinetypeMark[] = []; + for (const item of items.slice(1)) { + const value = item.trim(); + if (value.startsWith("[")) { + if (pattern.length === 0) + throw new RangeError(`${where}: a text or shape comes after the length it is drawn at`); + if (marks.at(-1)?.after === pattern.length - 1) + throw new RangeError(`${where}: one text or shape at the end of each length`); + marks.push(markOf(value, pattern.length - 1, where)); + continue; + } + const length = Number(value); + if (value === "" || !Number.isFinite(length)) + throw new RangeError(`${where}: ${JSON.stringify(value)} is not a length`); + pattern.push(length); + } + out.push({ + name: open.name, + description: open.description, + pattern, + ...(marks.length === 0 ? {} : { marks }), + }); + open = undefined; + }); + if (open) + throw new RangeError(`line ${open.line} of the linetype file: ${open.name} has no pattern`); + return out; +} + +/** A line up to its comment: a `;` outside the quotes of a text. */ +function withoutComment(row: string): string { + let quoted = false; + for (let i = 0; i < row.length; i++) { + if (row[i] === '"') quoted = !quoted; + else if (row[i] === ";" && !quoted) return row.slice(0, i); + } + return row; +} + +/** The items of a pattern, split at each comma outside a bracket and a text's quotes. */ +function splitItems(line: string, where: string): string[] { + const items: string[] = []; + let [start, depth, quoted] = [0, 0, false]; + for (let i = 0; i < line.length; i++) { + const c = line[i]; + if (c === '"') quoted = !quoted; + else if (quoted) continue; + else if (c === "[") depth++; + else if (c === "]") depth--; + else if (c === "," && depth === 0) { + items.push(line.slice(start, i)); + start = i + 1; + } + if (depth < 0 || depth > 1) throw new RangeError(`${where}: brackets that do not pair`); + } + if (quoted || depth !== 0) throw new RangeError(`${where}: a text or a bracket left open`); + items.push(line.slice(start)); + return items; +} + +/** An angle as a linetype file gives it: degrees, or with `r` radians or `g` grads. */ +function angleOf(value: string, where: string): number { + const v = value.trim(); + const unit = v.slice(-1).toLowerCase(); + const n = Number(/[dgr]/.test(unit) ? v.slice(0, -1) : v); + if (v === "" || !Number.isFinite(n)) + throw new RangeError(`${where}: ${JSON.stringify(v)} is not an angle`); + return unit === "r" ? (n * 180) / Math.PI : unit === "g" ? n * 0.9 : n; +} + +/** A text or a shape of a pattern, from its brackets, drawn at the end of the length `after`. */ +function markOf(item: string, after: number, where: string): LinetypeMark { + if (!item.endsWith("]")) + throw new RangeError(`${where}: ${JSON.stringify(item)} does not end in ]`); + const fields = splitItems(item.slice(1, -1), where).map((f) => f.trim()); + const [first = "", second = "", ...options] = fields; + const text = first.startsWith('"') && first.endsWith('"') && first.length >= 2; + if (!text && first === "") + throw new RangeError(`${where}: a shape needs its name, a text its quotes`); + let size = 1; + let rotation = 0; + let orient: MarkOrient = "relative"; + let [x, y] = [0, 0]; + for (const option of options) { + const at = option.indexOf("="); + const key = option.slice(0, at).trim().toUpperCase(); + const value = option.slice(at + 1); + const number = (): number => { + const n = Number(value.trim()); + if (value.trim() === "" || !Number.isFinite(n)) + throw new RangeError(`${where}: ${key}= takes a number, not ${JSON.stringify(value)}`); + return n; + }; + if (at < 0) throw new RangeError(`${where}: ${JSON.stringify(option)} is not KEY=value`); + else if (key === "S") size = number(); + else if (key === "X") x = number(); + else if (key === "Y") y = number(); + else if (key === "R" || key === "A" || key === "U") { + rotation = angleOf(value, where); + orient = key === "R" ? "relative" : key === "A" ? "absolute" : "upright"; + } else + throw new RangeError(`${where}: ${JSON.stringify(key)} is not one of S, R, A, U, X and Y`); + } + const common = { + after, + ...(rotation === 0 ? {} : { rotation }), + ...(orient === "relative" ? {} : { orient }), + ...(x === 0 && y === 0 ? {} : { offset: [x, y] as const }), + }; + if (text) + return { + ...common, + text: first.slice(1, -1), + ...(second === "" ? {} : { style: second }), + height: size, + }; + if (second === "") throw new RangeError(`${where}: a shape needs its shape file`); + return { ...common, shape: first, file: second, scale: size }; +} diff --git a/src/lint.ts b/src/lint.ts index d6edcfc..9db0c4b 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -141,6 +141,7 @@ import { lineweightProblem, linetypeNameProblem, linetypeProblem, + marksProblem, linetypeScaleProblem, R12_ONLY, controlSplineProblems, @@ -291,6 +292,7 @@ export type LintRule = | "title-block-field-unset" | "title-block-field-overflow" | "standard-check-capped" + | "linetype-shape" | "check-capped"; export interface Diagnostic { @@ -804,6 +806,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const linetypesAudited = new Map( BUILT_IN_LINETYPES.map((name) => [layerAuditKey(name), name]), ); + /** Each linetype with marks that are valid, whose texts' styles are checked once styles are known. */ + const marked: Linetype[] = []; + /** Each linetype a layer or an entity draws in, by `layerKey`. */ + const used = new Set(); const linetypeList = listed("linetypes", "linetype"); each(linetypeList, "linetypes", "linetype", TYPED.linetype, (linetype, i) => { if (malformed(WALKABLE.linetype, linetype, `linetypes[${i}]`, "linetype")) return; @@ -814,8 +820,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) error("linetype", `${label}: ${R12_ONLY.linetypes}`); return; } - const problem = linetypeProblem(linetype.name, linetype.description, linetype.pattern); + const problem = + linetypeProblem(linetype.name, linetype.description, linetype.pattern) ?? + marksProblem(linetype.marks, linetype.pattern); if (problem) error("linetype", `${label}: ${problem}`); + else if (linetype.marks !== undefined) marked.push(linetype); if (typeof linetype.name !== "string") return; const key = layerKey(linetype.name); const auditKey = layerAuditKey(linetype.name); @@ -1001,9 +1010,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (typeof name !== "string") return "a linetype is named by a string"; const problem = linetypeNameProblem(name); if (problem) return `Linetype ${shown(name)}: ${problem}`; - return builtInLinetype(name) || linetypes.has(layerKey(name)) - ? undefined - : undefinedLinetypeProblem(name); + if (builtInLinetype(name)) return undefined; + const key = layerKey(name); + if (!linetypes.has(key)) return undefinedLinetypeProblem(name); + used.add(key); + return undefined; }; // The leading CAD app compares text style names as it compares layer names. @@ -1061,6 +1072,19 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) textStyles.add(key); if (!textStylesAudited.has(auditKey)) textStylesAudited.set(auditKey, style.name); }); + for (const linetype of marked) { + for (const mark of linetype.marks ?? []) { + if (!("text" in mark) || mark.style === undefined || isStandardTextStyle(mark.style)) + continue; + if (textStyles.has(layerKey(mark.style))) continue; + out.push({ + rule: "undefined-text-style", + severity: "error", + message: `Linetype ${shown(linetype.name)}: ${undefinedTextStyleProblem(mark.style)}`, + ...named("linetype", linetype.name), + }); + } + } /** What is wrong with a text's style, justification or both, each with its rule. */ const textProblems = ( text: Pick, @@ -1975,7 +1999,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if ( r12 && entity.kind === "polyline" && - (entity.bulges !== undefined || entity.width !== undefined || entity.widths !== undefined) + (entity.bulges !== undefined || + entity.width !== undefined || + entity.widths !== undefined || + entity.linetypeGeneration !== undefined) ) { add("geometry", "error", R12_ONLY.polylines); } @@ -2453,6 +2480,18 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) out.push({ rule: "block-cycle", severity: "error", message, block: block.name }); } + // A shape is drawn from its shape file, which a drawing does not hold. + for (const linetype of marked) { + if (!used.has(layerKey(linetype.name))) continue; + if (!(linetype.marks ?? []).some((m) => "shape" in m)) continue; + out.push({ + rule: "linetype-shape", + severity: "warning", + message: `Linetype ${shown(linetype.name)} draws shapes of a shape file, where tsdraft's plot leaves a gap: CAD programs draw them from the file, which the drawing names and does not hold`, + ...named("linetype", linetype.name), + }); + } + if (stopped !== undefined) { out.push({ rule: "check-capped", diff --git a/src/read/check.ts b/src/read/check.ts index 11ff7fd..0dcf32b 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -23,6 +23,14 @@ type Type = type Fields = Readonly>; const counts: Type = { map: "count" }; + +/** What a linetype's mark of either kind holds. */ +const MARK: Fields = { + after: "number", + "rotation?": "number", + "orient?": { oneOf: ["absolute", "upright"] }, + "offset?": "point", +}; const strings: Type = { list: "string" }; const LAYER_CENSUS: Fields = { @@ -145,6 +153,7 @@ const ENTITY: Readonly> = { "bulges?": { list: "number" }, "width?": "number", "widths?": { list: "point" }, + "linetypeGeneration?": "boolean", }, circle: { ...BASE, kind: { oneOf: ["circle"] }, center: "point", radius: "number" }, arc: { @@ -444,6 +453,15 @@ const DRAWING_READ: Fields = { "description?": "string", pattern: { list: "number" }, complex: "boolean", + "marks?": { + list: { + either: [ + { ...MARK, text: "string", style: "string", height: "number" }, + { ...MARK, shape: "number", file: "string", scale: "number" }, + ], + named: "a linetype's mark", + }, + }, }, }, }, diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 74a4892..d174724 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -66,6 +66,7 @@ import { type ReadLayerCensus, type ReadLayout, type ReadLinetype, + type ReadLinetypeMark, type ReadMultileader, type ReadOptions, type ReadTextStyle, @@ -484,6 +485,10 @@ class DxfReader { readonly header: Record = map(); readonly layers: ReadLayer[] = []; readonly linetypes: ReadLinetype[] = []; + /** The marks of each linetype that has them, by its index, whose styles are named last. */ + readonly #marked: [number, PendingMark[]][] = []; + /** Each style's name and file, by its handle, for the marks of linetypes. */ + readonly #stylesByHandle = new Map(); readonly textStyles: ReadTextStyle[] = []; readonly dimensionStyles: (ReadDimensionStyle & { textStyleHandle?: string; @@ -720,21 +725,46 @@ class DxfReader { case "LTYPE": { const pattern: number[] = []; let complex = false; + // Each mark's groups follow the 49 and 74 of its length, its style by its handle, which + // the styles' table, after this one, names. + const marks: PendingMark[] = []; + let mark: PendingMark | undefined; for (let i = 0; i < r.codes.length; i++) { - if (r.codes[i] === 49) pattern.push(Number(r.values[i])); - if (r.codes[i] === 74 && Number(r.values[i]) !== 0) complex = true; + const [code, value] = [r.codes[i], r.values[i]!]; + if (code === 49) { + const length = Number(value); + mark = undefined; + if (!Number.isFinite(length)) continue; + pattern.push(length); + } else if (code === 74 && pattern.length > 0) { + const flags = Number(value); + if (flags !== 0) complex = true; + if ((flags & 6) === 0 || !Number.isFinite(flags)) continue; + mark = { after: pattern.length - 1, flags, values: new Map() }; + marks.push(mark); + } else if (mark !== undefined && MARK_CODES.has(code!)) { + if (!mark.values.has(code!)) mark.values.set(code!, value); + } } const description = name(r, 3); - this.linetypes.push({ + const linetype = { handle, name: recordName, ...(description !== undefined && { description }), - pattern: pattern.filter(Number.isFinite), + pattern, complex, - }); + }; + this.linetypes.push(linetype); + if (marks.length > 0) this.#marked.push([this.linetypes.length - 1, marks]); return; } case "STYLE": { + if (handle !== undefined) + this.#stylesByHandle.set(normalHandle(handle), { + name: recordName, + file: name(r, 3) ?? "", + height: num(r, 40) ?? 0, + }); // A style with flag 1 holds a shape file; one with no name is the font of a complex // linetype's shapes. if (recordName === "" && (flags & 1) !== 0) return; @@ -1266,6 +1296,7 @@ class DxfReader { points: owner.face === -1 ? owner.points.map((p) => placed(p, -1)) : owner.points, closed, ...sidesOf(owner.points.length, closed, owner.bulges, owner.widths, 0, owner.face), + ...((flags & 128) !== 0 && { linetypeGeneration: true }), }); } } @@ -1635,7 +1666,7 @@ class DxfReader { encoding: groups.encoding, header: header as ReadHeader, layers: this.layers, - linetypes: this.linetypes, + linetypes: withMarks(this.linetypes, this.#marked, this.#stylesByHandle), textStyles: this.textStyles, dimensionStyles, blocks: this.blocks.map((draft): ReadBlock => { @@ -1901,3 +1932,63 @@ function kept(code: string): boolean { if (/^\s*\\AcVar\s+(Filename|ctab|Date)\b/i.test(code)) return true; return /^\s*\\AcDiesel\b/i.test(code) && /\bctab\b/i.test(code); } + +/** A linetype's mark as its groups give it, before the styles' table names its style. */ +interface PendingMark { + readonly after: number; + readonly flags: number; + readonly values: Map; +} + +/** What a linetype's text height is multiplied by: a style's fixed height, or 1 for none. */ +const fixed = (height: number): number => (Number.isFinite(height) && height > 0 ? height : 1); + +/** A handle as a key: its digits in capitals. */ +const normalHandle = (handle: string): string => handle.trim().toUpperCase(); + +/** The groups of a mark after its 74: shape number, style, scale, rotation, offsets, text. */ +const MARK_CODES = new Set([75, 340, 46, 50, 44, 45, 9]); + +/** + * The linetypes with their marks, each text's style and each shape's file named from the style + * its handle finds. A mark whose numbers are not finite, or whose style is not found, is left out. + * A text is as high as its style's fixed height times its own, as the leading CAD app draws it. + */ +function withMarks( + linetypes: readonly ReadLinetype[], + marked: readonly (readonly [number, readonly PendingMark[]])[], + styles: ReadonlyMap, +): ReadLinetype[] { + const out = [...linetypes]; + for (const [index, pending] of marked) { + const marks: ReadLinetypeMark[] = []; + for (const m of pending) { + const number = (code: number, fallback: number): number => { + const v = m.values.get(code); + return v === undefined ? fallback : Number(v); + }; + const [size, rotation, x, y] = [number(46, 1), number(50, 0), number(44, 0), number(45, 0)]; + if (![size, rotation, x, y].every(Number.isFinite)) continue; + const style = styles.get(normalHandle(m.values.get(340) ?? "")); + if (style === undefined) continue; + const orient: "absolute" | "upright" | undefined = + (m.flags & 1) !== 0 ? "absolute" : (m.flags & 8) !== 0 ? "upright" : undefined; + const common = { + after: m.after, + ...(rotation !== 0 && { rotation }), + ...(orient !== undefined && { orient }), + ...((x !== 0 || y !== 0) && { offset: [x, y] as const }), + }; + if ((m.flags & 2) !== 0) { + const text = unescaped(m.values.get(9) ?? ""); + marks.push({ ...common, text, style: style.name, height: size * fixed(style.height) }); + } else { + const shape = number(75, 0); + if (!Number.isInteger(shape)) continue; + marks.push({ ...common, shape, file: style.file, scale: size }); + } + } + if (marks.length > 0) out[index] = { ...out[index]!, marks }; + } + return out; +} diff --git a/src/read/entities.ts b/src/read/entities.ts index d040a10..4d13e46 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -727,7 +727,8 @@ function lwpolyline(r: Rec, base: ReadEntityBase, face: Facing): Reading { else if (code === 40 || code === 41) vertex.widths[code - 40] = value; } close(); - const closed = ((num(r, 70) ?? 0) & 1) !== 0; + const flags = num(r, 70) ?? 0; + const closed = (flags & 1) !== 0; return { entity: { ...base, @@ -735,6 +736,7 @@ function lwpolyline(r: Rec, base: ReadEntityBase, face: Facing): Reading { points, closed, ...sidesOf(points.length, closed, bulges, widths, num(r, 43) ?? 0, face), + ...((flags & 128) !== 0 && { linetypeGeneration: true as const }), }, }; } diff --git a/src/read/model.ts b/src/read/model.ts index 11611ad..6dd701e 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -135,8 +135,34 @@ export interface ReadLinetype { readonly pattern: readonly number[]; /** True when an element holds a text or a shape. */ readonly complex: boolean; + /** + * The texts and shapes it draws, as `Linetype.marks` holds them: a text's style by its name, + * and a shape by its number and its file. Left out when it has none. + */ + readonly marks?: readonly ReadLinetypeMark[]; } +/** A mark of a linetype as a file holds it. */ +export type ReadLinetypeMark = + | { + readonly after: number; + readonly rotation?: number; + readonly orient?: "absolute" | "upright"; + readonly offset?: Point; + readonly text: string; + readonly style: string; + readonly height: number; + } + | { + readonly after: number; + readonly rotation?: number; + readonly orient?: "absolute" | "upright"; + readonly offset?: Point; + readonly shape: number; + readonly file: string; + readonly scale: number; + }; + export interface ReadTextStyle { readonly handle?: string | undefined; readonly name: string; @@ -323,6 +349,8 @@ export interface ReadPolyline extends ReadEntityBase { readonly width?: number; /** The width at the start and the end of each side, one pair for each. Left out when none is not 0. */ readonly widths?: readonly (readonly [start: number, end: number])[]; + /** True when the linetype's pattern runs on past each vertex, group 70's 128. Left out when not. */ + readonly linetypeGeneration?: true; } export interface ReadCircle extends ReadEntityBase { diff --git a/src/rules.ts b/src/rules.ts index 6b41742..aecbf06 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -1749,6 +1749,113 @@ export function linetypeProblem( return undefined; } +const MARK_FIELDS = ["after", "rotation", "orient", "offset"]; +const TEXT_MARK_FIELDS: readonly string[] = [...MARK_FIELDS, "text", "style", "height"]; +const SHAPE_MARK_FIELDS: readonly string[] = [...MARK_FIELDS, "shape", "file", "scale"]; + +/** What is wrong with marks that are not a list of objects. */ +export const MARKS_TYPE = "A linetype's marks must be an array of objects, each a text or a shape"; + +/** What is wrong with marks out of order, or two at one length. */ +export const MARKS_ORDER = + "A linetype's marks must be in order of after, at most one at each length of the pattern"; + +/** What is wrong with a linetype's texts past the room a drawing has for them. */ +export const MARK_TEXT_ROOM = + "A linetype's texts, each with one character more, may take 256 characters together: a DWG holds them in 512 bytes"; + +/** What is wrong with a shape given by name. */ +export const MARK_SHAPE_NAME = + "a shape by its name needs its shape file to number it: give the shape's number in the file"; + +/** + * Returns what is wrong with a linetype's marks, or undefined when they are valid. It takes + * `unknown` so that `lint` can report marks of the wrong type. Whether a text's style is one of + * the drawing's depends on the drawing, and is checked by the caller. + * + * @param pattern - The linetype's pattern, already checked. + */ +export function marksProblem(marks: unknown, pattern: readonly number[]): string | undefined { + if (marks === undefined) return undefined; + if (!Array.isArray(marks) || !(marks instanceof Array)) return MARKS_TYPE; + let last = -1; + let room = 0; + const list = marks as unknown[]; + for (let i = 0; i < list.length; i++) { + const mark = list[i]; + if (typeof mark !== "object" || mark === null || Array.isArray(mark)) return MARKS_TYPE; + const m = mark as Record; + const label = `its mark ${i}`; + const after = m.after; + if ( + typeof after !== "number" || + !Number.isInteger(after) || + after < 0 || + after >= pattern.length + ) + return `${label}: after must be the index of a length of the pattern, from 0 to ${pattern.length - 1}`; + if (after <= last) return MARKS_ORDER; + last = after; + const isText = "text" in m; + if (isText === "shape" in m) return `${label}: a mark is a text or a shape, with text or shape`; + const known = isText ? TEXT_MARK_FIELDS : SHAPE_MARK_FIELDS; + for (const key of Object.keys(m)) { + if (!known.includes(key)) + return `${label}: ${shown(key)} is not a field of a ${isText ? "text" : "shape"}`; + } + for (const key of ["rotation"] as const) { + const v = m[key]; + if (v === undefined) continue; + if (typeof v !== "number" || !Number.isFinite(v)) + return `${label}: ${key} must be a finite number`; + const problem = magnitudeProblem(v); + if (problem) return `${label}: ${key}: ${problem}`; + } + if (m.orient !== undefined && !(MARK_ORIENTS as readonly unknown[]).includes(m.orient)) + return `${label}: orient must be one of ${MARK_ORIENTS.map((o) => `"${o}"`).join(", ")}`; + if (m.offset !== undefined) { + const o = m.offset; + const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v); + if (!Array.isArray(o) || o.length !== 2 || !finite(o[0]) || !finite(o[1])) + return `${label}: offset must be [along, left], two finite numbers`; + const problem = magnitudeProblem(o[0]) ?? magnitudeProblem(o[1]); + if (problem) return `${label}: offset: ${problem}`; + } + const size = isText ? "height" : "scale"; + const v = m[size]; + if (typeof v !== "number" || !Number.isFinite(v) || !(v > 0) || written(v) === 0) + return `${label}: ${size} must be a number greater than 0 as written`; + const big = magnitudeProblem(v); + if (big) return `${label}: ${size}: ${big}`; + if (isText) { + const text = m.text; + if (typeof text !== "string" || text === "") + return `${label}: text must be a string with a character`; + if (text.length >= 256) return MARK_TEXT_ROOM; + const problem = textProblem(text); + if (problem) return `${label}: ${problem}`; + room += text.length + 1; + if (m.style !== undefined && typeof m.style !== "string") + return `${label}: style must be a string`; + if (typeof m.style === "string" && m.style.length > 255) + return `${label}: a text style's name has at most 255 characters`; + } else { + const shape = m.shape; + if (typeof shape === "string") return `${label}: ${MARK_SHAPE_NAME}`; + if (typeof shape !== "number" || !Number.isInteger(shape) || shape < 1 || shape > 65535) + return `${label}: shape must be a whole number from 1 to 65535`; + const file = m.file; + if (typeof file !== "string") return `${label}: file must name a shape file`; + if (file.length > 255) return `${label}: a shape file's name has at most 255 characters`; + if (file.trim() === "") return `${label}: file must name a shape file`; + const problem = textProblem(file); + if (problem) return `${label}: file: ${problem}`; + } + } + if (room > 256) return MARK_TEXT_ROOM; + return undefined; +} + /** * Returns what is wrong with a layer or an entity that names a linetype the * drawing does not have. The rule depends on the drawing, so it has no type. @@ -2692,6 +2799,9 @@ export function polylineSidesProblems( /** How a text is justified across its line, and up and down it. The first of each is the default. */ export const TEXT_ALIGNS = ["left", "center", "right"] as const; + +/** How a linetype's mark may be turned. */ +export const MARK_ORIENTS = ["relative", "absolute", "upright"] as const; export const TEXT_VERTICAL_ALIGNS = ["baseline", "bottom", "middle", "top"] as const; /** diff --git a/src/shape.ts b/src/shape.ts index e349c34..aec7d09 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -32,6 +32,8 @@ import type { ArcLengthDimension, OrdinateDimension, Linetype, + LinetypeShape, + LinetypeText, Paragraph, PatternLine, Polyline, @@ -512,7 +514,13 @@ function shapes(all: boolean, typed = all): Shapes { line: fields({ kind, layer: string, from: point, to: point }, shared), polyline: fields( { kind, layer: string, points: list(point), closed: boolean }, - { ...shared, bulges: list(number), width: number, widths: list(sideWidths) }, + { + ...shared, + bulges: list(number), + width: number, + widths: list(sideWidths), + linetypeGeneration: boolean, + }, ), circle: fields({ kind, layer: string, center: point, radius: number }, shared), arc: fields( @@ -737,10 +745,28 @@ function shapes(all: boolean, typed = all): Shapes { { description: ruled(string) }, ), ); + const markFields = { + rotation: ruled(number), + orient: ruled(string), + offset: ruled(point), + } as const; + const textMark = fields( + { after: ruled(number), text: ruled(string), height: ruled(number) }, + { ...markFields, style: ruled(string) }, + ); + const shapeMark = fields( + { after: ruled(number), shape: ruled(numberOrName), file: ruled(string), scale: ruled(number) }, + markFields, + ); + // A mark with a shape is a shape, and any other a text. + const mark: Check = (value, at, problems, extra) => { + if (!object(value)) problems.push(`${at} ${PLAIN_OBJECT}`); + else ("shape" in value ? shapeMark : textMark)(value, at, problems, extra); + }; const linetype = record( fields( { name: ruled(string), description: ruled(string), pattern: ruled(list(number)) }, - {}, + { marks: ruled(list(mark)) }, ), ); const textStyle = record( diff --git a/src/standard/lint.ts b/src/standard/lint.ts index 48fc9d2..97c0d9c 100644 --- a/src/standard/lint.ts +++ b/src/standard/lint.ts @@ -242,6 +242,14 @@ export function lintStandard( about, ); } + // A standard's linetype draws no text or shape, so one with marks is not the standard's. + if (Array.isArray(linetype.marks) && linetype.marks.length > 0) { + error( + "linetype-differs-from-standard", + `${label} draws texts or shapes, and the standard's linetype of its name draws none`, + about, + ); + } if (linetype.description !== own.description) { error( "linetype-differs-from-standard", diff --git a/src/svg.ts b/src/svg.ts index bce1876..ef18cf2 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -24,6 +24,9 @@ import { type Leader, type LeaderStyle, type Line, + type Linetype, + type LinetypeMark, + type LinetypeText, type Paragraph, type Point, type Polyline, @@ -114,6 +117,7 @@ import { arrowheadInfo, DEFAULT_ARROWHEAD } from "./arrowheads.ts"; import { DEFAULT_PLOT_STYLE_TABLE, paperInfo } from "./papers.ts"; import { drawnEllipse, + MARK_ORIENTS, shown as quoted, SplineMemo, turning, @@ -354,6 +358,33 @@ interface Dashes { readonly total: number; /** True when one has no length: a dot, which draws as a round cap. */ readonly dot: boolean; + /** The texts and shapes the pattern draws, where each is along it. */ + readonly marks?: readonly ScaledMark[]; +} + +/** A linetype's pattern as `alternating` gives it, with where along it each mark is drawn. */ +interface LinePattern { + readonly runs: readonly number[]; + /** Each mark, `at` its distance from the start of `runs`, in the pattern's units. */ + readonly marks: readonly { + readonly at: number; + /** True for a mark at the end of the pattern's last length. */ + readonly end: boolean; + readonly mark: LinetypeMark; + }[]; +} + +/** A mark of a pattern scaled for a space. */ +interface ScaledMark { + /** Its distance from the start of the scaled pattern, in the units the pattern is cut in. */ + readonly at: number; + /** True for a mark at the end of the pattern's last length. */ + readonly end: boolean; + readonly mark: LinetypeMark; + /** A text's style, as the drawing has it. */ + readonly style: TextStyle | undefined; + /** What its offset and its height are multiplied by, in the units of the space it is drawn in. */ + readonly size: number; } /** @@ -990,19 +1021,49 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): }); /** Each pattern scaled for each space, worked out when first drawn with. */ - const scaled = new Map>(); - const dashesOf = (pattern: readonly number[], scale: number, where: () => string): Dashes => { + const scaled = new Map>(); + /** Each pattern's marks scaled for a space, by its scale and size. */ + const marked = new Map>(); + const dashesOf = ( + pattern: LinePattern, + scale: number, + where: () => string, + size: number, + styles: ReadonlyMap, + ): Dashes => { let byScale = scaled.get(pattern); if (!byScale) scaled.set(pattern, (byScale = new Map())); let found = byScale.get(scale); if (!found) { // A pattern the leading CAD app takes has at most 12 lengths, but one given as data may hold any number. - if (!spend(Math.floor(pattern.length / 32))) refuse(where()); - const lengths = pattern.map((length) => length * scale); + if (!spend(Math.floor((pattern.runs.length + pattern.marks.length) / 32))) refuse(where()); + const lengths = pattern.runs.map((length) => length * scale); found = { lengths, total: lengths.reduce((a, b) => a + b, 0), dot: lengths.includes(0) }; byScale.set(scale, found); } - return found; + if (pattern.marks.length === 0) return found; + let bySpace = marked.get(pattern); + if (!bySpace) marked.set(pattern, (bySpace = new Map())); + const space = `${scale} ${size}`; + const known = bySpace.get(space); + if (known) return known; + if (!spend(Math.floor(pattern.marks.length / 32))) refuse(where()); + const made: Dashes = { + ...found, + marks: pattern.marks.map(({ at, end, mark }) => ({ + at: at * scale, + end, + mark, + style: fontOnly( + "text" in mark && typeof mark.style === "string" + ? styles.get(key(mark.style)) + : undefined, + ), + size, + })), + }; + bySpace.set(space, made); + return made; }; /** @@ -1054,7 +1115,13 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // the block's own units shrunk by the insert's scale. dashes: pattern && Number.isFinite(look.dashScale / placed) && placed > 0 - ? dashesOf(pattern, look.dashScale / placed, where) + ? dashesOf( + pattern, + look.dashScale / placed, + where, + look.dashScale, + tablesOf(named).textStyles, + ) : undefined, lineweight: code < 0 ? DEFAULT_LINEWEIGHT : code, }; @@ -1239,6 +1306,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const plotted = (scale: number, indent: string): Look => ({ color, dashScale: linetypeScale / scale, + chord: (paper.units === "in" ? 1 : 25.4) / 1200 / scale, indent, stroke: (lineweight) => pen !== undefined || lineweight === DEFAULT_LINEWEIGHT @@ -1438,6 +1506,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const onScreen: Look = { color: aciColor, dashScale: linetypeScale, + chord: 1 / 1200, indent: " ", stroke: (lineweight) => `${ @@ -1471,6 +1540,12 @@ interface Look { readonly color: (index: number) => string; /** What a linetype's pattern is multiplied by, to give dashes in the space's own units. */ readonly dashScale: number; + /** + * How far, in the space's own units, a curve in a linetype may stray from the straight pieces + * the leading CAD app cuts it into before its pattern, which its texts follow: 1/1200 inch on + * the paper. + */ + readonly chord: number; /** The attributes that set an element's stroke width, for a lineweight in hundredths of a millimetre. */ readonly stroke: (lineweight: number) => string; /** The white space before an element, which what an insert holds is set in from. */ @@ -1481,7 +1556,7 @@ interface Look { interface Tables { /** Keyed as the leading CAD app looks layers up, so an entity on `wall` takes the color of layer `WALL`. */ readonly layers: ReadonlyMap; - readonly patterns: ReadonlyMap; + readonly patterns: ReadonlyMap; readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; readonly leaderStyles: ReadonlyMap; @@ -1498,9 +1573,7 @@ function tablesFor(drawing: Drawing): Tables { } return { layers: new Map(filled(drawing.layers).map((l) => [layerKey(l.name), l])), - patterns: new Map( - filled(drawing.linetypes).map((t) => [layerKey(t.name), alternating(filled(t.pattern))]), - ), + patterns: new Map(filled(drawing.linetypes).map((t) => [layerKey(t.name), linePattern(t)])), textStyles: new Map(filled(drawing.textStyles).map((t) => [layerKey(t.name), t])), dimensionStyles: new Map(filled(drawing.dimensionStyles).map((t) => [layerKey(t.name), t])), leaderStyles: new Map(filled(drawing.leaderStyles).map((t) => [layerKey(t.name), t])), @@ -2052,10 +2125,17 @@ function entityToSvg( return polylineToSvg(e, plan, mark, pen, look, matrix, room, sides); } if (e.kind !== "text" && pen.dashes) { - const d = dashedPath(e, pen.dashes, matrix, room, sides); + const letters = lettersOf(pen, look); + const d = dashedPath(e, pen.dashes, matrix, room, sides, undefined, letters, look.chord); // A pattern with a dot draws it as a round cap on a path of no length. const cap = pen.dashes.dot ? ` stroke-linecap="round"` : ""; - if (d !== undefined) return ``; + if (d !== undefined) { + if (!letters?.out.length) return ``; + // The texts of its linetype are drawn after its dashes, in a group with them. + const stroked = `stroke="${pen.color}"${look.stroke(pen.lineweight)}`; + const parts = [``, ...letters.out]; + return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; + } } switch (e.kind) { case "line": { @@ -2177,6 +2257,59 @@ function roundToSvg(center: Point, round: ReturnType, s: string) * is turned to start with the dash after it. Undefined for a pattern with no gap, with no dash * or dot, or with no length, and the caller then draws the entity solid. */ +/** True for a mark whose fields a text can be drawn from, as `lint` holds them. */ +function drawable(mark: unknown): mark is LinetypeText { + if (typeof mark !== "object" || mark === null || !("text" in mark)) return false; + const m = mark as Record; + const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v); + const offset = m.offset; + return ( + typeof m.text === "string" && + Number.isInteger(m.after) && + finite(m.height) && + (m.height as number) > 0 && + (m.rotation === undefined || finite(m.rotation)) && + (m.orient === undefined || (MARK_ORIENTS as readonly unknown[]).includes(m.orient)) && + (m.style === undefined || typeof m.style === "string") && + (offset === undefined || + (Array.isArray(offset) && offset.length === 2 && finite(offset[0]) && finite(offset[1]))) + ); +} + +/** + * A linetype's pattern as `alternating` gives it, with each of its marks at the end of its length, + * measured from where the runs start. Undefined where `alternating` gives none. + */ +function linePattern(t: Linetype): LinePattern | undefined { + const pattern = filled(t.pattern); + const runs = alternating(pattern); + if (runs === undefined) return undefined; + const total = runs.reduce((a, b) => a + b, 0); + const first = pattern.findIndex((length) => length >= 0); + const ends: number[] = []; + let sum = 0; + for (const length of pattern) ends.push((sum += Math.abs(length))); + const shift = first > 0 ? ends[first - 1]! : 0; + const marks: readonly LinetypeMark[] = Array.isArray(t.marks) ? filled(t.marks) : []; + // A shape draws nothing, and of two marks at one length only the first is drawn, so a pattern + // has no more marks than lengths. + const seen = new Set(); + return { + runs, + marks: marks.flatMap((mark) => { + if (!drawable(mark)) return []; + const end = ends[mark.after]; + if (end === undefined || seen.has(mark.after)) return []; + seen.add(mark.after); + // A mark on the length the pattern ends with, which a pattern that starts with a gap ends + // where its runs start, is at the end of the pattern, whatever its lengths add up to. + const last = mark.after === (first > 0 ? first - 1 : pattern.length - 1) && end > 0; + const at = last ? 0 : (((end - shift) % total) + total) % total; + return [{ at, end: last, mark }]; + }), + }; +} + function alternating(pattern: readonly number[]): number[] | undefined { const first = pattern.findIndex((length) => length >= 0); if (first < 0) return undefined; @@ -2203,12 +2336,15 @@ function alternating(pattern: readonly number[]): number[] | undefined { */ function dashedPath( e: Exclude, - { lengths: dashes, total }: Dashes, + pattern: Dashes, matrix: Matrix | undefined, room: number, known: Known, wide?: { readonly fills: string[]; readonly ends: string[] }, + letters?: Letters, + spaceChord = 0, ): string | undefined { + const { lengths: dashes, total } = pattern; // Dashes that add up to no length would never reach the end of a stretch. if (!(total > 0)) return undefined; const place = (px: number, py: number): string => { @@ -2267,11 +2403,47 @@ function dashedPath( if (fitted && size <= room) dash(draw, dotted ? length : last, length); return true; }; - const straight = (a: Point, b: Point): boolean => { + /** Draws the marks of a stretch, each where `frame` puts its point and its direction. */ + const markAlong = ( + length: number, + frame: (s: number) => readonly [Point, Point], + fitted: boolean, + stretch = 1, + ): void => { + if (letters === undefined || pattern.marks === undefined) return; + for (const { s, mark } of markSpots(length, pattern, fitted, stretch)) { + if (size > room) return; + const [p, t] = frame(s); + const drawn = letterAt(mark, p, t, matrix, letters.text); + if (drawn === undefined) continue; + size += drawn.length + 1; + letters.out.push(drawn); + } + }; + // An insert that scales one way more than the other draws a straight side longer or shorter + // than the pattern's shrink allows for, and the pattern is fitted to it as it is drawn. + const shrink = matrix ? Math.sqrt(Math.abs(matrix[0] * matrix[3] - matrix[1] * matrix[2])) : 1; + // `Look.chord` in the entity's own units. + const chord = shrink > 0 && Number.isFinite(spaceChord / shrink) ? spaceChord / shrink : 0; + const gauge = (a: Point, b: Point, length: number): number => { + if (!matrix || !(shrink > 0)) return 1; + const [dx, dy] = [b[0] - a[0], b[1] - a[1]]; + const drawn = Math.hypot(matrix[0] * dx + matrix[2] * dy, matrix[1] * dx + matrix[3] * dy); + const g = drawn / (length * shrink); + return Number.isFinite(g) && g > 0 && Math.abs(g - 1) > 1e-9 ? g : 1; + }; + /** Cuts a straight stretch; a side of a polyline too fine for its pattern as drawn is drawn solid. */ + const straight = (a: Point, b: Point, side = false): boolean => { const length = Math.hypot(b[0] - a[0], b[1] - a[1]); + if (length === 0) return true; + const g = gauge(a, b, length); const along = (t: number) => - place(a[0] + ((b[0] - a[0]) * t) / length, a[1] + ((b[1] - a[1]) * t) / length); - return length === 0 || cut(length, (from, to) => `M ${along(from)} L ${along(to)}`, true); + place(a[0] + ((b[0] - a[0]) * t) / g / length, a[1] + ((b[1] - a[1]) * t) / g / length); + const draw = (from: number, to: number) => `M ${along(from)} L ${along(to)}`; + const done = cut(length * g, draw, true) || (side && (dash(draw, 0, length * g), true)); + const frame = sideFrame({ from: a, to: b }, undefined, length); + markAlong(length * g, (at) => frame(at / g), true); + return done; }; const round = ( center: Point, @@ -2280,15 +2452,25 @@ function dashedPath( turn: number, fitted: boolean, stretch = 1, + marked = true, ): boolean => { const along = (t: number) => { const angle = rad(start) + t / radius; return place(center[0] + radius * Math.cos(angle), center[1] + radius * Math.sin(angle)); }; + // The pattern is fitted to the straight pieces the arc is cut into, and drawn along the arc. + const length = radius * rad(turn); + const pieces = piecesLength(radius, rad(turn), chord); + const k = pieces > 0 ? length / pieces : 1; + if (marked) { + const frame = arcFrame(center, radius, rad(start), rad(turn), length, chord); + markAlong(pieces, (at) => frame(at * k), fitted, stretch); + } const shape = rounded(radius, matrix); return cut( - radius * rad(turn), - (from, to) => { + pieces, + (a, b) => { + const [from, to] = [a * k, b * k]; // SVG draws no arc between two equal points, so a dot is a line of no length. if (to === from) return `M ${along(from)} L ${along(to)}`; const arc = `A ${fmt(shape.rx)} ${fmt(shape.ry)} ${fmt(shape.turn)}`; @@ -2310,6 +2492,92 @@ function dashedPath( break; case "polyline": { const plan = planOf(e, known); + // A polyline with a side whose width changes along it starts the pattern again at each + // vertex whatever its flag says, as the leading CAD app does. + const tapered = plan?.parts.some(({ side }) => side.startWidth !== side.endWidth) ?? false; + if (e.linetypeGeneration === true && !tapered) { + const course = courseOf(e, plan, known).map((piece) => { + const { arc } = piece; + const local = arc ? piecesLength(arc.radius, Math.abs(arc.sweep), chord) : piece.length; + const g = arc ? 1 : gauge(piece.side.from, piece.side.to, piece.length); + return { ...piece, local, length: local * g, gauge: g }; + }); + if (course.length === 0) return undefined; + const ends: number[] = []; + let length = 0; + for (const piece of course) ends.push((length += piece.length)); + if (length / total > MAX_DASHES) return undefined; + // Around a closed polyline the pattern goes a whole number of times, stretched alike, + // and the course starts at its second point. + const patterns = Math.round(length / total); + if (e.closed && patterns < 1) return undefined; + const stretch = e.closed ? length / (patterns * total) : 1; + /** The piece that holds `at` along the course, and how far into it. */ + const locate = (at: number): readonly [number, number] => { + // The first piece that ends at or past `at`, found by halving. + let [lo, hi] = [0, course.length - 1]; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (at > ends[mid]!) lo = mid + 1; + else hi = mid; + } + return [lo, at - (ends[lo]! - course[lo]!.length)]; + }; + const strokes = out; + const piece = (i: number, from: number, to: number): string => { + const { side, arc, length: l } = course[i]!; + if (isWide(side)) { + wide?.fills.push(bandPiece(side, arc, from / l, to / l, place, matrix)); + return ""; + } + return pieceTrace(side, arc, from / l, to / l, place, matrix); + }; + cut( + length, + (from, to) => { + const [i] = locate(from); + const [j] = locate(to); + const drawn: string[] = []; + // Whether the last piece drawn was a line, which the next runs on from. + let joined = false; + for (let k = i; k <= j; k++) { + const start = ends[k]! - course[k]!.length; + const a = Math.max(from, start) - start; + const b = Math.min(to, ends[k]!) - start; + const traced = piece(k, a, Math.max(a, b)); + if (traced === "") joined = false; + else { + drawn.push(joined ? traced.replace(/^M \S+ \S+ /, "") : traced); + joined = true; + } + } + return drawn.join(" "); + }, + !e.closed, + stretch, + ); + out = strokes.filter((d) => d !== ""); + // An open course that ends on a wide straight side ends in the thinnest line across it. + const end = course.at(-1)!; + if (!e.closed && isWide(end.side) && !end.arc && length >= total * (1 - 1e-9)) { + const ended = bandPiece(end.side, undefined, 1, 1, place, matrix).split(" L "); + const across = `${ended[0]!} L ${ended[2]!}`; + size += across.length + 1; + wide?.ends.push(across); + } + markAlong( + length, + (at) => { + const [i, into] = locate(at); + const { side, arc, local, gauge: g } = course[i]!; + return sideFrame(side, arc, local, chord)(into / g); + }, + !e.closed, + stretch, + ); + ok = true; + break; + } if (plan) { // A side the pattern is too fine for draws the whole polyline solid. if (plan.longest / total > MAX_DASHES) return undefined; @@ -2317,17 +2585,28 @@ function dashedPath( for (const { side, arc, fit } of plan.parts) { if (size > room) break; if (!isWide(side)) { - if (!arc) straight(side.from, side.to); + if (!arc) straight(side.from, side.to, true); else { - // An arc that turns clockwise is cut from its end, which fits the same dashes. + // An arc that turns clockwise is cut from its end, which fits the same dashes, and + // its marks from its start. const from = arc.sweep > 0 ? arc.start : arc.start + arc.sweep; - round(arc.center, arc.radius, degrees(from), degrees(Math.abs(arc.sweep)), true); + const turn = degrees(Math.abs(arc.sweep)); + round(arc.center, arc.radius, degrees(from), turn, true, 1, false); + const pieces = piecesLength(arc.radius, Math.abs(arc.sweep), chord); + markAlong(pieces, sideFrame(side, arc, pieces, chord), true); } continue; } - // Each dash of a wide side is filled, square at both ends. + // Each dash of a wide side is filled, square at both ends, fitted to the side as drawn. out = []; - cut(fit, (from, to) => bandPiece(side, arc, from / fit, to / fit, place, matrix), true); + const g = arc ? 1 : gauge(side.from, side.to, fit); + const drawn = fit * g; + const band = (from: number, to: number) => + bandPiece(side, arc, from / drawn, to / drawn, place, matrix); + // A side too fine for its pattern as it is drawn is filled whole. + if (!cut(drawn, band, true)) dash(band, 0, drawn); + const frame = sideFrame(side, arc, fit, chord); + markAlong(drawn, (at) => frame(at / g), true); if (out.length > 0) wide?.fills.push(out.join(" ")); out = strokes; // A straight side cut into dashes ends in the thinnest line across its end, and so does @@ -2355,9 +2634,9 @@ function dashedPath( if ((closing > longest ? closing : longest) / total > MAX_DASHES) return undefined; for (const end of ends) { if (size > room) break; - straight(points[end - 1]!, points[end]!); + straight(points[end - 1]!, points[end]!, true); } - if (closing > 0) straight(last!, first!); + if (closing > 0) straight(last!, first!, true); ok = true; break; } @@ -2365,7 +2644,7 @@ function dashedPath( // A circle holds the whole number of patterns nearest its length, each stretched or // shrunk alike to go round it exactly, from a dash at its angle 0. One shorter than its // pattern is solid. - const around = 2 * Math.PI * e.radius; + const around = piecesLength(e.radius, 2 * Math.PI, chord); if (!(around >= total)) return undefined; ok = round(e.center, e.radius, 0, 360, false, around / (Math.round(around / total) * total)); break; @@ -2442,6 +2721,237 @@ function dashedPath( return ok && (out.length > 0 || (wide?.fills.length ?? 0) > 0) ? out.join(" ") : undefined; } +/** A style's font alone: the leading CAD app draws a linetype's text in neither its width nor its slant. */ +function fontOnly(style: TextStyle | undefined): TextStyle | undefined { + return style === undefined ? undefined : { name: style.name, font: style.font }; +} + +/** Where the texts of a pen's linetype go, when it has any: drawn in its color, with no mark. */ +function lettersOf(pen: Pen, look: Look): Letters | undefined { + if (!pen.dashes?.marks?.some((m) => "text" in m.mark)) return undefined; + void look; + return { out: [], text: (t, style) => textToSvg(t, style, pen, "", undefined, false) }; +} + +/** Where the texts of a linetype go, and how a text is drawn: as the entity's own text. */ +interface Letters { + readonly out: string[]; + readonly text: (t: Text, style: TextStyle | undefined) => string; +} + +/** + * Where along a stretch of `length` each mark of a pattern is drawn, from the stretch's start. + * A fitted stretch draws them in each of its whole patterns, from where its first dash's pattern + * would start, one at the end of the pattern at the end of each and at the end of the stretch, + * and one shorter than its pattern none. One that is not fitted draws them in each + * time its stretched pattern goes along it. + */ +function* markSpots( + length: number, + dashes: Dashes, + fitted: boolean, + stretch: number, +): Generator<{ readonly s: number; readonly mark: ScaledMark }> { + const { marks, total, lengths } = dashes; + if (marks === undefined || !(total > 0) || length / total > MAX_DASHES) return; + if (fitted) { + if (length < total * (1 - 1e-9)) return; + const first = lengths[0]!; + const count = Math.floor(length / total + 1e-9); + const start = (length + first - count * total) / 2 - first; + for (let k = 0; k < count; k++) + for (const mark of marks) yield { s: start + k * total + (mark.end ? total : mark.at), mark }; + // A mark at the end of the pattern comes once more at the end of the stretch. + for (const mark of marks) if (mark.end) yield { s: length, mark }; + return; + } + const count = Math.round(length / (total * stretch)); + // Round a closed course, a mark at the end of the pattern comes at the end of each but the last, + // where the course closes. + for (let k = 0; k < count; k++) { + for (const mark of marks) { + if (mark.end && k === count - 1) continue; + yield { s: (k * total + (mark.end ? total : mark.at)) * stretch, mark }; + } + } +} + +/** + * A point of a side `length` long, `s` along it from its start, and the way it runs there, in + * the side's own coordinates. Past either end of a straight side it runs on along it. + */ +function sideFrame( + side: Pick, + arc: SideArc | undefined, + length: number, + chord = 0, +): (s: number) => readonly [Point, Point] { + if (!arc) { + const [dx, dy] = [(side.to[0] - side.from[0]) / length, (side.to[1] - side.from[1]) / length]; + return (s) => [ + [side.from[0] + dx * s, side.from[1] + dy * s], + [dx, dy], + ]; + } + return arcFrame(arc.center, arc.radius, arc.start, arc.sweep, length, chord); +} + +/** How many straight pieces the leading CAD app cuts an arc turning `sweep` radians into. */ +function pieceCount(radius: number, sweep: number, chord: number): number { + const most = chord > 0 && chord < radius ? 2 * Math.acos(1 - chord / radius) : Math.PI; + const step = Math.min(most, (2 * Math.PI) / 32); + const count = Math.ceil(sweep / step - 1e-9); + return Number.isFinite(count) ? Math.max(1, Math.min(MAX_DASHES, count)) : 1; +} + +/** How long those pieces are together, which a pattern is fitted to. The arc's own length with no chord. */ +function piecesLength(radius: number, sweep: number, chord: number): number { + if (!(chord > 0)) return radius * sweep; + const count = pieceCount(radius, sweep, chord); + return 2 * radius * count * Math.sin(sweep / (2 * count)); +} + +/** + * A point of an arc `length` long, `s` along it from its start, and the way it runs there: on + * the straight pieces the leading CAD app cuts it into, of equal turns from its start, each + * straying at most `chord` from it, and a whole circle into 32 at least. + */ +function arcFrame( + center: Point, + radius: number, + start: number, + sweep: number, + length: number, + chord: number, +): (s: number) => readonly [Point, Point] { + const pieces = pieceCount(radius, Math.abs(sweep), chord); + const at = (k: number): Point => { + const angle = start + (sweep * k) / pieces; + return [center[0] + radius * Math.cos(angle), center[1] + radius * Math.sin(angle)]; + }; + return (s) => { + const t = Math.min(Math.max((s / length) * pieces, 0), pieces); + const k = Math.min(pieces - 1, Math.floor(t)); + const [a, b] = [at(k), at(k + 1)]; + const [dx, dy] = [b[0] - a[0], b[1] - a[1]]; + const l = Math.hypot(dx, dy); + const u = t - k; + return [ + [a[0] + dx * u, a[1] + dy * u], + l > 0 ? [dx / l, dy / l] : [-Math.sin(start), Math.cos(start)], + ]; + }; +} + +/** + * The sides of a polyline that have a length, in order, as one course for a pattern that runs on + * past each vertex. A closed one's course starts at its second point, where the leading CAD app + * starts it. + */ +function courseOf( + e: Polyline, + plan: Plan | undefined, + known: Known, +): { readonly side: PolylineSide; readonly arc: SideArc | undefined; readonly length: number }[] { + let course: { side: PolylineSide; arc: SideArc | undefined; length: number }[]; + if (plan) { + course = plan.parts.map(({ side, arc }) => ({ side, arc, length: sideLength(side, arc) })); + } else { + const { points, ends } = sidesOf(e.points, known); + const straight = (from: Point, to: Point) => ({ + side: { from, to, bulge: 0, startWidth: 0, endWidth: 0 }, + arc: undefined, + length: Math.hypot(to[0] - from[0], to[1] - from[1]), + }); + course = ends.map((end) => straight(points[end - 1]!, points[end]!)); + const [first, last] = [points[0], points.at(-1)]; + if (e.closed && first && last) { + const closing = straight(last, first); + if (closing.length > 0) course.push(closing); + } + } + if (e.closed && course.length > 1) course = [...course.slice(1), course[0]!]; + return course.filter((piece) => piece.length > 0); +} + +/** The path of a side of no width from `t0` to `t1` of the way along it, where `matrix` puts it. */ +function pieceTrace( + side: PolylineSide, + arc: SideArc | undefined, + t0: number, + t1: number, + place: (x: number, y: number) => string, + matrix: Matrix | undefined, +): string { + if (!arc) { + const at = (t: number) => + place( + side.from[0] + (side.to[0] - side.from[0]) * t, + side.from[1] + (side.to[1] - side.from[1]) * t, + ); + return `M ${at(t0)} L ${at(t1)}`; + } + const at = (t: number) => { + const [x, y] = arcPoint(arc, t); + return place(x, y); + }; + if (t1 === t0) return `M ${at(t0)} L ${at(t1)}`; + const round = rounded(arc.radius, matrix); + const flag = arc.sweep > 0 ? round.sweep : 1 - round.sweep; + const a = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${flag}`; + // An arc of more than half a turn is drawn as two halves. + if (Math.abs(arc.sweep * (t1 - t0)) > Math.PI) { + return `M ${at(t0)} ${a} ${at((t0 + t1) / 2)} ${a} ${at(t1)}`; + } + return `M ${at(t0)} ${a} ${at(t1)}`; +} + +/** + * A linetype's text at a point of its line where the line runs along `t`, both in the entity's + * own coordinates, drawn where `matrix` puts it. Its offset is along the line and to its left as + * the line is drawn, and an upright text turns half a turn about the middle of its box where the + * line runs leftward in its own coordinates. A shape draws nothing. + */ +function letterAt( + m: ScaledMark, + p: Point, + t: Point, + matrix: Matrix | undefined, + draw: Letters["text"], +): string | undefined { + const mark = m.mark; + if (!("text" in mark) || typeof mark.text !== "string") return undefined; + const [px, py] = matrix ? mapPoint(matrix, p) : p; + let [tx, ty] = matrix + ? [matrix[0] * t[0] + matrix[2] * t[1], matrix[1] * t[0] + matrix[3] * t[1]] + : t; + const along = Math.hypot(tx, ty); + if (!(along > 0)) return undefined; + [tx, ty] = [tx / along, ty / along]; + const offset = mark.offset; + const [ox, oy] = offset === undefined ? [0, 0] : [offset[0], offset[1]]; + const k = m.size; + let x = px + (ox * tx - oy * ty) * k; + let y = py + (ox * ty + oy * tx) * k; + const height = mark.height * k; + const orient = mark.orient ?? "relative"; + let rotation = (orient === "absolute" ? 0 : degrees(Math.atan2(ty, tx))) + (mark.rotation ?? 0); + const text: Text = { kind: "text", layer: "0", at: [x, y], height, value: mark.text, rotation }; + if (orient === "upright") { + const local = ((degrees(Math.atan2(t[1], t[0])) % 360) + 360) % 360; + if (local > 90 + 1e-9 && local < 270 - 1e-9) { + const laid = layoutText(inStyle(text, m.style)); + const trueType = fontInfo(m.style?.font ?? STANDARD_FONT)?.pitchAndFamily !== undefined; + const w = trueType ? laid.advances : laid.end - laid.start; + const r = rad(rotation); + x += w * Math.cos(r) - height * Math.sin(r); + y += w * Math.sin(r) + height * Math.cos(r); + rotation += 180; + } + } + return draw({ ...text, at: [x, y], rotation }, m.style); +} + /** * The path of the filled piece of a side from `t0` to `t1` of the way along it, square to the * side at both ends, where `matrix` puts it: its left edge from `t0` to `t1`, then its right edge @@ -2523,7 +3033,9 @@ function polylineToSvg( const dashed = pen.dashes ? { fills: [] as string[], ends: [] as string[], d: undefined as string | undefined } : undefined; - if (pen.dashes && dashed) dashed.d = dashedPath(e, pen.dashes, matrix, room, known, dashed); + const letters = lettersOf(pen, look); + if (pen.dashes && dashed) + dashed.d = dashedPath(e, pen.dashes, matrix, room, known, dashed, letters, look.chord); if (dashed && (dashed.d !== undefined || dashed.fills.length > 0)) { const cap = pen.dashes?.dot ? ` stroke-linecap="round"` : ""; if (dashed.d) parts.push(``); @@ -2531,6 +3043,7 @@ function polylineToSvg( if (dashed.ends.length > 0) { parts.push(``); } + parts.push(...(letters?.out ?? [])); } else { let run: string[] = []; let used = 0; diff --git a/test/linetypes.test.ts b/test/linetypes.test.ts new file mode 100644 index 0000000..4d07252 --- /dev/null +++ b/test/linetypes.test.ts @@ -0,0 +1,172 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + createDrawing, + lint, + parseLinetypes, + readDXF, + toDXF, + toSVG, + type Drawing, + type LinetypeDefinition, +} from "../src/index.ts"; +import { MARK_SHAPE_NAME, MARKS_ORDER } from "../src/rules.ts"; + +const WATER: LinetypeDefinition = { + name: "WATER", + description: "Water ---- W ----", + pattern: [0.75, -0.1, -0.1], + marks: [{ after: 1, text: "W", style: "LT", height: 0.1, offset: [-0.035, -0.05] }], +}; + +function pipe(length: number, linetypeGeneration?: boolean): Drawing { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "LT", font: "Arial" }); + d.linetype(WATER); + d.polyline( + [ + [0, 0], + [length / 2, 0], + [length / 2, length / 2], + ], + false, + { linetype: "WATER", ...(linetypeGeneration === undefined ? {} : { linetypeGeneration }) }, + ); + return d.build(); +} + +const letters = (svg: string): number => (svg.match(/]*>W<\/text>/g) ?? []).length; + +test("a pipe's letters run on past each vertex only with linetype generation", () => { + // Sides of 0.9 are shorter than the pattern, 0.95, so each is drawn solid without its letters. + assert.equal(letters(toSVG(pipe(1.8))), 0); + assert.equal(letters(toSVG(pipe(1.8, true))), 1); + // A polyline whose width changes along a side starts the pattern on each side whatever its flag. + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "LT", font: "Arial" }); + d.linetype(WATER); + const points = [ + [0, 0], + [0.9, 0], + [0.9, 0.9], + ] as const; + d.polyline(points, false, { + linetype: "WATER", + linetypeGeneration: true, + widths: [ + [0, 0.05], + [0.05, 0], + ], + }); + assert.equal(letters(toSVG(d.build())), 0); +}); + +test("marks and linetype generation are written and read back", async () => { + const read = await readDXF(toDXF(pipe(4, true)), { geometry: true }); + const linetype = read.linetypes.find((t) => t.name === "WATER"); + assert.deepEqual(linetype?.marks, [ + { after: 1, offset: [-0.035, -0.05], text: "W", style: "LT", height: 0.1 }, + ]); + const polyline = read.model.entities?.find((e) => e.kind === "polyline"); + assert.equal(polyline?.kind === "polyline" && polyline.linetypeGeneration, true); +}); + +test("a mark's rules hold in the type and when the code runs", () => { + const d = createDrawing({ units: "in" }); + assert.throws( + () => + d.linetype({ + name: "BAD", + pattern: [1, -0.1], + // @ts-expect-error orient is relative, absolute or upright + marks: [{ after: 1, text: "X", height: 0.1, orient: "sideways" }], + }), + /orient must be one of/, + ); + assert.throws( + () => + d.linetype({ + name: "TWICE", + pattern: [1, -0.1, -0.1], + marks: [ + { after: 1, text: "X", height: 0.1 }, + { after: 1, text: "Y", height: 0.1 }, + ], + }), + new RegExp(MARKS_ORDER), + ); + // A shape by its name needs its shape file to number it. + assert.throws( + () => + d.linetype({ + name: "FENCE", + pattern: [1, -0.1], + marks: [{ after: 1, shape: "CIRC1", file: "shapes.shx", scale: 0.1 }], + }), + (e: Error) => e.message.includes(MARK_SHAPE_NAME), + ); +}); + +test("lint finds a mark's text style, and warns of shapes it plots as gaps", () => { + const drawing: Drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "F", color: 7, linetype: "FENCE" }], + linetypes: [ + { + name: "FENCE", + description: "", + pattern: [1, -0.1, -0.1], + marks: [ + { after: 1, text: "F", style: "NONE", height: 0.1 }, + { after: 2, shape: 133, file: "shapes.shx", scale: 0.1 }, + ], + }, + ], + entities: [], + }; + const rules = lint(drawing).map((d) => `${d.rule} ${d.severity}`); + assert.ok(rules.includes("undefined-text-style error")); + assert.ok(rules.includes("linetype-shape warning")); +}); + +test("parseLinetypes reads a linetype file's texts and shapes, each after its length", () => { + const [gas, fence] = parseLinetypes( + [ + ";; a firm's linetypes", + "*GAS,Gas line ---- GAS ----", + 'A,.5,-.2,["G,A;S",STANDARD,S=.1,U=0.0,X=-0.1,Y=-.05],-.25 ; the gas main', + "*FENCE,Fence ---O---", + "A,.25,-.1,[CIRC1,shapes.shx,x=-.1,s=.1,r=1.5708r],-.1,1", + ].join("\r\n"), + ); + assert.deepEqual(gas, { + name: "GAS", + description: "Gas line ---- GAS ----", + pattern: [0.5, -0.2, -0.25], + marks: [ + { + after: 1, + orient: "upright", + offset: [-0.1, -0.05], + text: "G,A;S", + style: "STANDARD", + height: 0.1, + }, + ], + }); + const shape = fence?.marks?.[0]; + assert.ok(shape && "shape" in shape && shape.shape === "CIRC1" && shape.file === "shapes.shx"); + assert.ok(Math.abs((shape.rotation ?? 0) - 90) < 1e-3); + for (const [text, message] of [ + ["A,1,-1", /before any \*NAME/], + ['*X\nA,["T",S],1', /comes after the length/], + ['*X\nA,1,["T",S,Q=1]', /not one of S, R, A, U, X and Y/], + ['*X\nA,1,["T,S', /left open/], + ["*X", /has no pattern/], + ["*X\nB,1", /starts with A/], + ] as const) { + assert.throws(() => parseLinetypes(text), message); + } +}); diff --git a/test/polylines.test.ts b/test/polylines.test.ts index 942f27f..6127f19 100644 --- a/test/polylines.test.ts +++ b/test/polylines.test.ts @@ -651,3 +651,35 @@ test("lint stops where toDXF would, on polylines whose boxes pay for a list read thrown instanceof DrawingError && thrown.diagnostics.some((d) => d.rule === "check-capped"), ); }); + +test("a side of a polyline too fine for its pattern as an uneven insert draws it is drawn solid", () => { + const drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + linetypes: [{ name: "FINE", description: "", pattern: [0.05, -0.05] }], + blocks: [ + { + name: "B", + entities: [ + { + kind: "polyline", + layer: "0", + linetype: "FINE", + points: [ + [0, 0], + [480, 0], + [480, 1], + ], + closed: false, + width: 1, + }, + ], + }, + ], + entities: [{ kind: "insert", layer: "0", block: "B", at: [0, 0], scale: [4, 1] }], + } as unknown as Drawing; + // The long side, 1,920 long as drawn and too fine to dash, is filled whole beside the short one.s dashes. + assert.ok(/> = { closed: false, bulges: [0.25, 0], width: 0.25, + linetypeGeneration: true, id: "j", ...styled, }; @@ -411,7 +413,7 @@ const keyed: Required< /** One of everything an R2018 drawing can hold, with every field of every object. */ const full: Required & { - readonly linetypes: readonly [Required]; + readonly linetypes: readonly [Required, Required]; readonly patterns: readonly [ Required & { readonly lines: readonly [Required] }, ]; @@ -444,7 +446,41 @@ const full: Required & { linetypeScale: 2, imageFrame: false, wipeoutFrame: false, - linetypes: [{ name: "DD", description: "Dash dot", pattern: [0.5, -0.25, 0, -0.25] }], + linetypes: [ + { + name: "DD", + description: "Dash dot", + pattern: [0.5, -0.25, 0, -0.25], + marks: [ + { + after: 1, + text: "W", + style: "Standard", + height: 0.1, + rotation: 0, + orient: "upright", + offset: [0, -0.05], + }, + ], + }, + // A linetype of shapes that nothing draws in, which lint does not warn of. + { + name: "SHAPES", + description: "Shapes", + pattern: [0.5, -0.25], + marks: [ + { + after: 1, + shape: 3, + file: "shapes.shx", + scale: 0.1, + rotation: 0, + orient: "relative", + offset: [0, 0], + }, + ], + }, + ], patterns: [ { name: "STRIPES", From 67521bd9a9e38eb2cb21dabfa720a5bfdd9f69e7 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 06:43:59 -0500 Subject: [PATCH 22/35] Tables: one table entity, written, read and plotted as CAD programs draw it Tables, in R2018 drawings. `d.tableStyle(style)` defines a table style: its cells' text style and height, its margins, and the cell style of its title, header and data rows, each with its own text style, height, alignment, text color, fill and border lineweight. `d.table(options)` draws a table from its upper left corner: `columns` gives each column's width, `title` a cell across them all, and `header` and `rows` a cell for each column. A cell is a string, or an object with `text`, a `block` scaled to fit or by `blockScale`, `columnSpan` and `rowSpan`, and its own `align`, `valign`, `textHeight`, `color` and `fill`. A cell another spans is `null`. Both writers write one table entity and its style as CAD programs hold them, so a drafter adds a row, resizes a column and edits a cell. Each is written with the picture CAD programs draw for it: text wrapped at its column, a word too long for its cell broken between characters, each row as tall as its cells need, fills, borders and blocks. Each style lists its tables, so a change to the style in a CAD program reaches them. `toSVG`, `toPDF` and `inspectText` draw and check a table as it plots, and `measureTable` gives the size it takes. `readDXF` and `readDWG` read a table's rows, columns and cells, and each table style into `tableStyles`, which every read now holds. `lint` and the builder refuse a style or a table that cannot be written, a row of the wrong length, a span past the table or over another cell, a `null` nothing spans, a block its fit would scale to 0, a table in a block, and more than 100,000 cells. A table in a referenced drawing draws the block in each of its cells too, and `tableBox` gives the box of what a table draws, its cells' blocks included. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 19 + GUIDE.md | 31 + cli/test/fixtures/read/reader-a/read.js | 1 + docs/format.md | 9 + docs/reading.md | 25 +- docs/tables.md | 125 +++ examples/plan-set/lib/kit.ts | 93 +- examples/plan-set/sheets/cover.ts | 134 ++- .../plan-set/sheets/elevations-section.ts | 46 +- examples/plan-set/sheets/elevations.ts | 28 +- examples/plan-set/sheets/mep-e101.ts | 93 +- examples/plan-set/sheets/mep-m101.ts | 109 +-- examples/plan-set/sheets/mep-p101.ts | 135 +-- examples/plan-set/sheets/roof.ts | 29 +- examples/plan-set/sheets/schedules.ts | 118 +-- examples/plan-set/sheets/site.ts | 51 +- examples/plan-set/sheets/structure-details.ts | 49 +- examples/plan-set/sheets/structure-framing.ts | 66 +- src/blocks.ts | 21 +- src/drawing.ts | 300 ++++++- src/dxf-r2018.ts | 401 ++++++++- src/extents.ts | 119 ++- src/index.ts | 41 + src/inspect.ts | 77 +- src/lint.ts | 205 ++++- src/paragraphs.ts | 75 +- src/read/check.ts | 54 ++ src/read/dxf.ts | 156 +++- src/read/entities.ts | 9 + src/read/model.ts | 84 +- src/read/table.ts | 416 +++++++++ src/rules.ts | 383 ++++++++- src/shape.ts | 32 + src/svg.ts | 203 ++++- src/table-pictures.ts | 79 ++ src/tables.ts | 794 ++++++++++++++++++ test/bounded.test.ts | 24 + test/read-agreement.ts | 166 +++- test/read-fuzz.ts | 20 + test/read.test.ts | 112 +++ test/shape.test.ts | 48 +- test/tables.test.ts | 233 +++++ 42 files changed, 4720 insertions(+), 493 deletions(-) create mode 100644 docs/tables.md create mode 100644 src/read/table.ts create mode 100644 src/table-pictures.ts create mode 100644 src/tables.ts create mode 100644 test/tables.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 35bcff9..8f029bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ ## Unreleased +- Tables, in R2018 drawings. `d.tableStyle(style)` defines a table style: the text style and + height of its cells, its margins, and the cell style of its title, header and data rows, each + with its own text style, height, alignment, text color, fill and border lineweight. + `d.table(options)` draws a table at its upper left corner: `columns` gives each column's width, + `title` a cell across them all, `header` and `rows` a cell for each column, each a string or an + object with `text`, a `block` scaled to fit or by `blockScale`, `columnSpan` and `rowSpan`, and + its own `align`, `valign`, `textHeight`, `color` and `fill`; a cell another spans is `null`. + Both writers write one table entity and its style as CAD programs hold them, so a drafter adds + a row, resizes a column and edits a cell, with the picture CAD programs draw for it: text + wrapped at its column, a word too long for it broken, each row as tall as its cells need, + fills, borders and blocks. Each style lists its tables, so a change to the style in a CAD + program reaches them. `toSVG`, `toPDF` and `inspectText` draw and check it as it plots, and + `measureTable` gives the size it takes. `readDXF` and `readDWG` read a table's rows, columns and + cells and each table style into `tableStyles`, which every read now holds, so a reader the + command runs answers with it too. `lint` and the builder refuse, under the rules + `table-style`, `duplicate-table-style`, `undefined-table-style` and `table`, a style or a table + that cannot be written, a row of the wrong length, a span past the table or over another cell, a + `null` that nothing spans, a block its fit would scale to 0, a table in a block and more than + 100,000 cells. `tableBox` gives the box of what a table draws, its cells' blocks included. - Linetypes with text, in R2018 drawings: a pipe with its letters along it. A linetype's `marks` draw a text, such as `W`, at the end of a length of its pattern, by `after`, in one of the drawing's text styles, turned with the line, from the X axis, or `upright` so it reads from the diff --git a/GUIDE.md b/GUIDE.md index 7deb39b..ef27851 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -440,6 +440,37 @@ d.leader(["EXISTING TREE", "TO REMAIN"], { style: "NOTE", at: [62, 38], to: [52, [docs/leaders.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/leaders.md) has the rest. +## Tables + +Define a table style, then draw a schedule as one table: + +```ts +d.tableStyle({ + name: "SCHEDULE", + textStyle: "NOTES", + textHeight: 0.1, + title: { textHeight: 0.15 }, +}); +d.table({ + style: "SCHEDULE", + at: [1, 22], + columns: [0.6, 0.8, 0.8, 2.4], + title: "DOOR SCHEDULE", + header: ["MARK", { text: "SIZE", columnSpan: 2 }, null, "NOTES"], + rows: [["D1", "3'-0\"", "7'-0\"", "SOLID CORE"]], +}); +``` + +- Each row holds a cell for each column. A cell is a string, or an object with `text`, or with a + `block` in place of a text, and its own `columnSpan`, `rowSpan`, `align`, `valign`, + `textHeight`, `color` and `fill`. A cell another spans is `null`. +- Rows grow to fit their text, which wraps at the column's width; `rowHeights` sets the least + height of each data row. `measureTable` gives the size a table takes, for what goes below it. +- A `fill` makes a cell a color swatch, and a `block` a symbol in a legend. +- Never draw a schedule from lines and text. + [docs/tables.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/tables.md) has + the rest. + ## Blocks Draw a symbol that repeats once, as a block, and place it with inserts: diff --git a/cli/test/fixtures/read/reader-a/read.js b/cli/test/fixtures/read/reader-a/read.js index aa692bc..12b588e 100644 --- a/cli/test/fixtures/read/reader-a/read.js +++ b/cli/test/fixtures/read/reader-a/read.js @@ -45,6 +45,7 @@ export async function readDrawingFile(chunks, name) { linetypes: [], textStyles: [], dimensionStyles: [], + tableStyles: [], blocks: [], xrefs: [], images: [], diff --git a/docs/format.md b/docs/format.md index 2091bd6..44342b1 100644 --- a/docs/format.md +++ b/docs/format.md @@ -83,6 +83,15 @@ of its own it has a `side`, an `attachment`, a `verticalAttachment`, a `width`, or lineweight. A drawing with no leader has the JSON it had before leaders existed. [Leaders](leaders.md) describes them. +A table is an entity of kind `"table"`, in `drawing.entities` or a layout's `entities`, never a +block's, with its `layer`, `style`, `at` and `columns`, and `rows`, each a list of a cell for each +column: a string, an object with the fields it sets, or `null` where another cell spans it. Where +it has them it has a `rotation`, a `title`, a `titleHeight`, a `header`, a `headerHeight` and +`rowHeights`. Its table style is in `drawing.tableStyles`, with its `name` and `textHeight` and +where it sets them a `textStyle`, margins and the cell styles `title`, `header` and `data`. A +drawing with no table has the JSON it had before tables existed. [Tables](tables.md) describes +them. + A paragraph is an entity of kind `"paragraph"`, in `drawing.entities`, a block's `entities` or a layout's `entities`, with its `layer`, `at`, `height`, `value` and `rotation`, as a text has them, and where they are set a `width`, a `style`, an `align` of `"center"` or `"right"`, a `valign` of diff --git a/docs/reading.md b/docs/reading.md index c84c861..ce275e0 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -56,6 +56,12 @@ states and keeps each object's handle, and it keeps going past what it does not a shape by its number and its `file`, `textStyles` and `dimensionStyles`, each style with whether it is annotative, and a dimension style with the units it writes lengths in, where its text goes, how it writes a fraction, its lineweights and its arrowheads' block. Two entries of one name are both kept, in the order of the file. +- `tableStyles`: each table style the file's dictionary of them, `ACAD_TABLESTYLE`, names, in the + dictionary's order, by its name there: its `horizontalMargin` and `verticalMargin`, and a cell + style for its `title`, its `header` and its `data` rows. A cell style has its `textStyle`, its + `textHeight`, its `alignment`, 1 to 3 along the top from the left, 4 to 6 the middle and 7 to 9 + the bottom, its text's `color`, 0 for ByBlock, its `fill` where its cells are filled, and its + borders' `lineweight`, -2 for ByBlock. A field a style leaves out is the leading CAD app's own. - `blocks`: each with its base point, its attribute definitions and its entities, below. What else a block draws is counted under `other` by kind, such as `HATCH` or `LWPOLYLINE in 3D`, and so is what stands in another plane than the block's. An entity the file marks invisible, @@ -66,8 +72,8 @@ states and keeps each object's handle, and it keeps going past what it does not is `invisible`, as one whose own flag hides it is, and a space counts such a definition under `other`. The blocks keep `BLOCK_ITEMS`, 400,000 items in all, counted as below, and count what comes past that under `past the limit`. - The pictures the leading CAD app makes for dimensions, the blocks named `*D` and a number, are - kept by a read with `geometry` alone. + The pictures the leading CAD app makes for dimensions and tables, the blocks named `*D` or `*T` + and a number, are kept by a read with `geometry` alone. - `xrefs`: each with its name, its path as the file holds it, and whether it is an overlay. - `images`: each image definition of the file's dictionary of them, with its name, its path as the file holds it, the pixels it states, whether it is loaded, and how many images name it. One @@ -210,6 +216,21 @@ leader: `fitPoints`. One whose counts disagree with its groups, whose degree is not a whole number from 1 to 11, or whose knots do not fit its control points is counted under `unread.malformed`, and one with a point off the plane under `other`. +- `table`: its `style`, where the dictionary of table styles names it, its upper left corner + `at`, the `direction` its rows run, one unit long, the height of each of its `rows` from the top + and the width of each of its `columns` from the left, and whether its first row is a `title` + and its next a `header`, as its style and its own groups say. `cells` holds each cell that + starts a span or stands alone, in reading order: its `row` and `column` from 0 at the top left, + its `rowSpan` and `columnSpan`, its `text` with a paragraph's codes or its `block` by name, with + `blockScale` where the block is not scaled to fit the cell, and what it changes of its row's + cell style where its flags say so: `alignment`, `textHeight`, its text's `color` and its + `fill`. `block` and `blockHandle` name the block of its picture, which CAD programs show and + plot, and which a read with `geometry` keeps among `blocks`. A table is read from its own + groups, which every file holds; the objects of its dictionary, which hold the same content + again, are not read. A table of more than 1,000 columns or 100,000 cells, the core's + limits, or of more rows or items than the read may still keep, is counted under `other`, and + one whose rows, columns or cells are not as many as it says under `unread.malformed`. One out + of the plane is counted under `other`. - An `mtext` with a background holds `mask`: its `offsetFactor`, and its `color` or `trueColor` where it is not in the drawing's background. diff --git a/docs/tables.md b/docs/tables.md new file mode 100644 index 0000000..b2c3951 --- /dev/null +++ b/docs/tables.md @@ -0,0 +1,125 @@ +# Tables + +A table is a schedule, a legend or a calculation in rows and columns: a title row across its +columns, a header row and data rows. In the file it is one table entity and not lines and text, +so a drafter adds a row, resizes a column or edits a cell with CAD's own table commands. tsdraft +draws tables in R2018 drawings only. + +```ts +const d = createDrawing({ units: "in" }); +d.layer("A-ANNO-SCHD", { color: 7 }); +d.textStyle({ name: "NOTES", font: "Arial" }); +d.block("SWATCH-CONC", {}, () => d.rect([0, 0], 1, 0.5)); + +d.tableStyle({ + name: "SCHEDULE", + textStyle: "NOTES", + textHeight: 0.1, + title: { textHeight: 0.15 }, + header: { lineweight: 0.35 }, + data: { align: "left", valign: "middle" }, +}); + +d.layout("A-601", { paper: "ARCH D" }, () => { + d.layer("A-ANNO-SCHD", {}, () => { + d.table({ + style: "SCHEDULE", + at: [1, 22], + columns: [0.6, 0.8, 0.8, 2.4], + title: "DOOR SCHEDULE", + header: ["MARK", { text: "SIZE", columnSpan: 2 }, null, "NOTES"], + rows: [ + ["D1", "3'-0\"", "7'-0\"", "SOLID CORE, 20 MIN. RATED, CLOSER"], + [{ text: "D2", rowSpan: 2 }, "2'-8\"", "6'-8\"", "HOLLOW CORE"], + [null, "2'-6\"", "6'-8\"", { block: "SWATCH-CONC" }], + ], + }); + }); +}); +``` + +## A table style + +Every table names a table style, which says how its cells are drawn. `d.tableStyle(definition)` +defines one, once, under a name no other style has, and before the first table that names it. +`"Standard"` is the leading CAD app's own, which tsdraft writes beside a drawing's styles, and a +drawing neither defines it nor draws in it. + +| Field | What it sets | +| ------------------ | ----------------------------------------------------------------------------------------------- | +| `name` | The style's name, held to the rules of a dimension style's name. | +| `textStyle` | The text style of its cells. `"Standard"` unless given. | +| `textHeight` | The height of its cells' capitals, for each kind of row that gives none. Greater than 0. | +| `horizontalMargin` | The room between a cell's sides and its content. A third of `textHeight` unless given. | +| `verticalMargin` | The room between a cell's top and bottom and its content. A third of `textHeight` unless given. | +| `title` | The cell style of the title row. | +| `header` | The cell style of the header row. | +| `data` | The cell style of the data rows. | + +A cell style may set `textStyle`, `textHeight`, `align` (`"left"`, `"center"` or `"right"`), +`valign` (`"top"`, `"middle"` or `"bottom"`), `color` and `fill`, each a color index from 1 to +255, and `lineweight`, the lineweight in millimetres of its cells' borders. A title's and a +header's content is centered across and up and down unless its style says otherwise, and a data +cell's is centered across at the top. + +## A table + +`d.table(options)` draws a table on the current layer, its upper left corner at `at`. + +| Field | What it sets | +| -------------- | -------------------------------------------------------------------------------- | +| `style` | A table style of the drawing. | +| `at` | Its upper left corner. | +| `rotation` | Degrees counterclockwise. 0 unless given. | +| `columns` | The width of each column, from the left. | +| `title` | The title, in one cell across every column. Missing, the table has no title row. | +| `header` | The header row, a cell for each column. Missing, the table has no header row. | +| `rows` | The data rows, from the top, each a list of a cell for each column. | +| `titleHeight` | The least height of the title row. | +| `headerHeight` | The least height of the header row. | +| `rowHeights` | The least height of each data row, or `null` for as tall as its cells need. | + +Each row holds a cell for each column. A cell is its text, as a string, or an object: + +| Field | What it sets | +| ----------------- | ---------------------------------------------------------------------------------- | +| `text` | Its text, with a paragraph's codes. `\P` breaks a line. | +| `block` | A block of the drawing in place of a text. It takes no attribute values. | +| `blockScale` | The block's scale. Missing, the block is scaled to fit the cell, less its margins. | +| `columnSpan` | How many columns it spans, to the right. 1 unless given. | +| `rowSpan` | How many rows it spans, down. 1 unless given. | +| `align`, `valign` | Where its content sits in it, in place of its row's cell style. | +| `textHeight` | The height of its text's capitals. | +| `color` | The color index of its text. | +| `fill` | The color index it is filled with, as a swatch. | + +A cell that another spans is `null`, so `rows[r][c]` is always column `c`. A span stays inside +the header or inside the data rows. + +## How a table is laid out + +The leading CAD app lays a table out again whenever a drafter edits it, so tsdraft draws it as +that app does: + +- A cell's text wraps at the column's width less two horizontal margins, as paragraph text does, + but a word wider than that breaks before each character whose ink would pass it. +- Each row is as tall as its tallest cell needs: its text's box, and at least four thirds of its + text's height, plus two vertical margins; or its block, at its scale, plus the margins. A row + is never shorter than the height given for it. A cell that spans rows grows the last of them. +- A block in a cell is placed by its box, as a text would be by `align` and `valign`. A block + scaled to fit takes all it draws, a layer that does not plot included. +- A table in a referenced drawing draws the block in each of its cells too. +- A border between two cells is drawn in the lineweight of the row it is the top of, and pieces of + one line run on while they share a lineweight. + +`measureTable(options, style, textStyles, blocks)` gives a table's width and height, and the +height of each row, as `d.table` lays it out, for placing what goes below it. + +## What lint reports + +| Rule | What it reports | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `table-style` | A table style that cannot be written, or one in an R12 drawing. | +| `duplicate-table-style` | A second table style of a name the drawing has, compared as the leading CAD app does. | +| `undefined-table-style` | A table whose style the drawing does not have, or that names `"Standard"`. | +| `table` | A table with a row of the wrong length, a span past the table or over another, a `null` no span covers, a cell of a block the drawing lacks, a block its fit would scale to 0, a table in a block, or one in an R12 drawing. | diff --git a/examples/plan-set/lib/kit.ts b/examples/plan-set/lib/kit.ts index 8b7d161..5a41e70 100644 --- a/examples/plan-set/lib/kit.ts +++ b/examples/plan-set/lib/kit.ts @@ -6,11 +6,17 @@ import { DASHED, fromPaper, HIDDEN, + measureTable, measureText, PHANTOM, type DrawingBuilder, + type ParagraphAlign, type Point, + type TableCell, + type TableOptions, + type TableStyle, type TextAlign, + type TextStyle, type TextVerticalAlign, } from "../../../src/index.ts"; import { arrowhead, feetInches } from "../../lib/drafting.ts"; @@ -19,6 +25,8 @@ export type D = DrawingBuilder; export const FONT = "Arial" as const; export const NOTES = "NOTES"; export const TITLE = "TITLE"; +/** The table style of the set's schedules. */ +export const SCHEDULE = "SCHEDULE"; /** Text heights on paper, in inches. */ export const H = { @@ -30,6 +38,33 @@ export const H = { title: 1 / 4, }; +const NOTES_STYLE: TextStyle = { name: NOTES, font: FONT }; + +const SCHEDULE_STYLE: TableStyle = { + name: SCHEDULE, + textStyle: NOTES, + textHeight: H.note, + horizontalMargin: 0.05, + verticalMargin: 0.04, + title: { textHeight: H.label, align: "left", lineweight: 0.35 }, + header: { align: "left", valign: "middle", lineweight: 0.35 }, + data: { align: "left", valign: "middle", lineweight: 0.13 }, +}; + +/** A row's cells, each aligned as `aligns` says for its column, or as the style says. */ +export const aligned = ( + cells: readonly string[], + aligns: Readonly>, +): TableCell[] => + cells.map((text, c) => { + const align = aligns[c]; + return align ? { text, align } : text; + }); + +/** The y of a schedule's bottom edge, for stacking what goes under it. */ +export const tableBottom = (table: TableOptions): number => + table.at[1] - measureTable(table, SCHEDULE_STYLE, [NOTES_STYLE]).height; + /** A view: its ratio and the paper-to-model helper for it. */ export interface View { readonly ratio: number; @@ -267,6 +302,7 @@ export function defineLayers(d: D): void { export function defineSymbols(d: D): void { d.textStyle({ name: NOTES, font: FONT }); d.textStyle({ name: TITLE, font: FONT, widthFactor: 0.9 }); + d.tableStyle(SCHEDULE_STYLE); // Symbols are drawn in paper inches. In model space they are inserted at `view.p(1)`. d.block("NORTH ARROW", {}, () => { @@ -712,63 +748,6 @@ export function noteColumn( return y; } -/** - * A table on the sheet: a heading, a header row and rows, in columns of the given widths. Each - * cell is checked to fit; a value too long for its cell throws, so the table is fixed in code. - */ -export function table( - d: D, - at: Point, - heading: string, - columns: readonly { name: string; width: number; align?: TextAlign }[], - rows: readonly (readonly string[])[], - o: { height?: number; rowHeight?: number } = {}, -): number { - const h = o.height ?? H.note; - const rh = o.rowHeight ?? h * 2.4; - const total = columns.reduce((s, c) => s + c.width, 0); - let y = at[1]; - d.layer(LAYERS.text, {}, () => { - if (heading) { - put(d, [at[0], y], heading, H.label, { valign: "top" }); - y -= H.label + 0.1; - } - const top = y; - const all = [columns.map((c) => c.name), ...rows]; - all.forEach((cells, r) => { - let x = at[0]; - cells.forEach((cell, c) => { - const col = columns[c]!; - const pad = 0.05; - const textWidth = width(cell, h); - if (textWidth > col.width - 2 * pad) { - throw new Error( - `Table "${heading}": "${cell}" is ${textWidth.toFixed(2)} in long for a cell ${col.width} in wide`, - ); - } - const align = col.align ?? "left"; - const tx = - align === "center" - ? x + col.width / 2 - : align === "right" - ? x + col.width - pad - : x + pad; - put(d, [tx, y - rh / 2], cell, h, { align, valign: "middle" }); - x += col.width; - }); - y -= rh; - d.line([at[0], y], [at[0] + total, y], { lineweight: r === 0 ? 0.35 : 0.13 }); - }); - d.rect([at[0], y], total, top - y, { lineweight: 0.35 }); - let x = at[0]; - for (const col of columns.slice(0, -1)) { - x += col.width; - d.line([x, y], [x, top]); - } - }); - return y; -} - /** The arrow and slope of a roof, in model space for view `v`. */ export function slopeArrow(d: D, v: View, at: Point, angle: number, text: string): void { const len = v.p(0.6); diff --git a/examples/plan-set/sheets/cover.ts b/examples/plan-set/sheets/cover.ts index 5417d08..170088f 100644 --- a/examples/plan-set/sheets/cover.ts +++ b/examples/plan-set/sheets/cover.ts @@ -1,17 +1,19 @@ // G-001: the cover. Everything here is on the paper: the project, the index read from the sheet // list, the code data and design criteria read from `project.ts`, the areas worked out from the // house, a vicinity map and the legend of the set's symbols. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { CRITERIA, FIRM, PROJECT, SHEETS as SHEET_LIST } from "../project.ts"; import { areas, ROOF } from "../model/house.ts"; import { frame } from "../lib/frame.ts"; import { + aligned, AREA, H, LAYERS, noteColumn, put, - table, + SCHEDULE, + tableBottom, TITLE, type D, type SheetDraw, @@ -43,15 +45,14 @@ function cover(d: D): void { // Column 1: project data, criteria, areas. const c1 = AREA.left + 0.2; - let y = table( - dd, - [c1, colTop], - "PROJECT DATA", - [ - { name: "ITEM", width: 2.6 }, - { name: "VALUE", width: 4.6 }, - ], - [ + const draw = (t: TableOptions) => dd.layer(LAYERS.text, {}, () => dd.table(t)); + const projectData: TableOptions = { + style: SCHEDULE, + at: [c1, colTop], + columns: [2.6, 4.6], + title: "PROJECT DATA", + header: ["ITEM", "VALUE"], + rows: [ ["SCOPE", "NEW SINGLE-FAMILY DWELLING"], ["OCCUPANCY", "R-3 / FBC-R DWELLING"], ["CONSTRUCTION TYPE", CRITERIA.construction], @@ -69,17 +70,16 @@ function cover(d: D): void { ["HEIGHT LIMIT", `${CRITERIA.zoning.maxHeight}'-0" (D.F.E. TO MEAN ROOF)`], ["PLATE HEIGHTS", `1ST 10'-0", 2ND 9'-1 1/8"`], ], - ); - y -= 0.3; - y = table( - dd, - [c1, y], - "AREA TABULATION (GROSS, TO OUTSIDE FACE)", - [ - { name: "AREA", width: 4.2 }, - { name: "SQ. FT.", width: 3.0, align: "right" }, - ], - [ + }; + draw(projectData); + const right = { 1: "right" } as const; + const areaTable: TableOptions = { + style: SCHEDULE, + at: [c1, tableBottom(projectData) - 0.3], + columns: [4.2, 3.0], + title: "AREA TABULATION (GROSS, TO OUTSIDE FACE)", + header: aligned(["AREA", "SQ. FT."], right), + rows: [ ["FIRST FLOOR, CONDITIONED", sf(a.l1)], ["SECOND FLOOR, CONDITIONED", sf(a.l2)], ["TOTAL CONDITIONED", sf(a.living)], @@ -87,19 +87,17 @@ function cover(d: D): void { ["ENTRY PORCH", sf(a.porch)], ["COVERED LANAI", sf(a.lanai)], ["TOTAL UNDER ROOF", sf(a.total)], - ], - ); - y -= 0.3; + ].map((row) => aligned(row, right)), + }; + draw(areaTable); const w = CRITERIA.wind; - table( - dd, - [c1, y], - "DESIGN CRITERIA (ASCE 7-22)", - [ - { name: "ITEM", width: 3.6 }, - { name: "VALUE", width: 3.6 }, - ], - [ + draw({ + style: SCHEDULE, + at: [c1, tableBottom(areaTable) - 0.3], + columns: [3.6, 3.6], + title: "DESIGN CRITERIA (ASCE 7-22)", + header: ["ITEM", "VALUE"], + rows: [ ["ULTIMATE WIND SPEED, VULT", `${w.vult} MPH`], ["NOMINAL WIND SPEED, VASD", `${w.vasd} MPH`], ["RISK CATEGORY", w.risk], @@ -111,11 +109,11 @@ function cover(d: D): void { ["ROOF LIVE / DEAD LOAD", `${CRITERIA.live.roof} / ${CRITERIA.dead.roof} PSF`], ["SOIL BEARING (ASSUMED)", `${CRITERIA.soil.toLocaleString("en-US")} PSF`], ], - ); + }); // Column 2: code data and general notes. const c2 = AREA.left + 7.9; - y = noteColumn(dd, [c2, colTop], 7.4, "APPLICABLE CODES", [...CRITERIA.codes], { + let y = noteColumn(dd, [c2, colTop], 7.4, "APPLICABLE CODES", [...CRITERIA.codes], { numbered: false, }); y -= 0.25; @@ -134,45 +132,39 @@ function cover(d: D): void { // Column 3: the index, read from the sheet list. const c3 = AREA.left + 15.8; - y = table( - dd, - [c3, colTop], - "SHEET INDEX", - [ - { name: "SHEET", width: 1.0 }, - { name: "TITLE", width: 5.6 }, - ], - SHEET_LIST.map((s) => [ + const index: TableOptions = { + style: SCHEDULE, + at: [c3, colTop], + columns: [1.0, 5.6], + title: "SHEET INDEX", + header: ["SHEET", "TITLE"], + rows: SHEET_LIST.map((s) => [ s.number, [s.title, s.title2].filter(Boolean).join(" ").replace(", ", " ") + (s.number === "M-101" ? " (ADDED, REV. 1)" : ""), ]), - { rowHeight: 0.26 }, - ); - y -= 0.3; - table( - dd, - [c3, y], - "ABBREVIATIONS", - [ - { name: "", width: 1.0 }, - { name: "", width: 2.3 }, - { name: "", width: 1.0 }, - { name: "", width: 2.3 }, - ], - [ - ["A.F.F.", "ABOVE FINISH FLOOR", "GWB", "GYPSUM WALLBOARD"], - ["BFE", "BASE FLOOD ELEVATION", "MAX.", "MAXIMUM"], - ["CLG.", "CEILING", "MIN.", "MINIMUM"], - ["CMU", "CONCRETE MASONRY UNIT", "NAVD", "N. AMER. VERT. DATUM"], - ["CONC.", "CONCRETE", "O.C.", "ON CENTER"], - ["DFE", "DESIGN FLOOD ELEV.", "OSB", "ORIENTED STRAND BD."], - ["EL.", "ELEVATION", "P.T.", "PRESSURE TREATED"], - ["F.F.E.", "FINISH FLOOR ELEV.", "T.O.", "TOP OF"], - ["FTG.", "FOOTING", "TYP.", "TYPICAL"], - ], - { rowHeight: 0.24 }, - ); + rowHeights: SHEET_LIST.map(() => 0.26), + }; + draw(index); + const abbreviations = [ + ["A.F.F.", "ABOVE FINISH FLOOR", "GWB", "GYPSUM WALLBOARD"], + ["BFE", "BASE FLOOD ELEVATION", "MAX.", "MAXIMUM"], + ["CLG.", "CEILING", "MIN.", "MINIMUM"], + ["CMU", "CONCRETE MASONRY UNIT", "NAVD", "N. AMER. VERT. DATUM"], + ["CONC.", "CONCRETE", "O.C.", "ON CENTER"], + ["DFE", "DESIGN FLOOD ELEV.", "OSB", "ORIENTED STRAND BD."], + ["EL.", "ELEVATION", "P.T.", "PRESSURE TREATED"], + ["F.F.E.", "FINISH FLOOR ELEV.", "T.O.", "TOP OF"], + ["FTG.", "FOOTING", "TYP.", "TYPICAL"], + ]; + draw({ + style: SCHEDULE, + at: [c3, tableBottom(index) - 0.3], + columns: [1.0, 2.3, 1.0, 2.3], + title: "ABBREVIATIONS", + rows: abbreviations, + rowHeights: abbreviations.map(() => 0.24), + }); // Column 4: vicinity map, legend and the team. const c4 = AREA.left + 23.0; diff --git a/examples/plan-set/sheets/elevations-section.ts b/examples/plan-set/sheets/elevations-section.ts index c6beb22..037d3a7 100644 --- a/examples/plan-set/sheets/elevations-section.ts +++ b/examples/plan-set/sheets/elevations-section.ts @@ -2,11 +2,12 @@ // room and the lanai, the owner's bath, closet and bedroom above) at 1/4" = 1'-0", and the // typical wall section through the first-floor CMU wall and the second-floor wood wall, from // the footing to the roof, at 1/2" = 1'-0". -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { CRITERIA } from "../project.ts"; import { DEPTH, HEIGHTS, L1, L2, LANAI, LANAI_SLAB, ROOF, W } from "../model/house.ts"; import { frame } from "../lib/frame.ts"; import { + aligned, AREA, dimString, ftIn, @@ -14,8 +15,9 @@ import { LAYERS, noteColumn, put, + SCHEDULE, sectionCut, - table, + tableBottom, view, viewport, width, @@ -710,17 +712,17 @@ function envelopeTable(d: D, at: Point, w: number): number { ["WINDOWS", "U-0.40", "SHGC 0.25, IMPACT"], ]; const c2 = 0.8; - return table( - d, + const center = { 1: "center" } as const; + const envelope: TableOptions = { + style: SCHEDULE, at, - "ENVELOPE (FBC-ENERGY R402, CLIMATE ZONE 2)", - [ - { name: "ASSEMBLY", width: (w - c2) * 0.48 }, - { name: "R / U", width: c2, align: "center" }, - { name: "MATERIAL", width: (w - c2) * 0.52 }, - ], - rows, - ); + columns: [(w - c2) * 0.48, c2, (w - c2) * 0.52], + title: "ENVELOPE (FBC-ENERGY R402, CLIMATE ZONE 2)", + header: aligned(["ASSEMBLY", "R / U", "MATERIAL"], center), + rows: rows.map((row) => aligned(row, center)), + }; + d.layer(LAYERS.text, {}, () => d.table(envelope)); + return tableBottom(envelope); } /** @@ -738,17 +740,17 @@ function strapTable(d: D, at: Point, w: number): number { ]; const c2 = 0.95; const c3 = 0.85; - return table( - d, + const center = { 1: "center", 2: "center" } as const; + const loadPath: TableOptions = { + style: SCHEDULE, at, - "UPLIFT LOAD PATH (SCHEDULE ON S-102)", - [ - { name: "CONNECTION", width: w - c2 - c3 }, - { name: "TAG", width: c2, align: "center" }, - { name: "SEE", width: c3, align: "center" }, - ], - rows, - ); + columns: [w - c2 - c3, c2, c3], + title: "UPLIFT LOAD PATH (SCHEDULE ON S-102)", + header: aligned(["CONNECTION", "TAG", "SEE"], center), + rows: rows.map((row) => aligned(row, center)), + }; + d.layer(LAYERS.text, {}, () => d.table(loadPath)); + return tableBottom(loadPath); } function sectionSheet(d: D): void { diff --git a/examples/plan-set/sheets/elevations.ts b/examples/plan-set/sheets/elevations.ts index 121f581..5ec2f41 100644 --- a/examples/plan-set/sheets/elevations.ts +++ b/examples/plan-set/sheets/elevations.ts @@ -1,7 +1,7 @@ // A-201 and A-202: the four exterior elevations at 1/4" = 1'-0", drawn from the model: the // walls, the openings at their real positions and heights, the hip roof, the lanai, the grade // and the flood levels. A-301, the building and wall sections, is in elevations-section.ts. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { CRITERIA } from "../project.ts"; import { DEPTH, @@ -20,6 +20,7 @@ import { } from "../model/house.ts"; import { frame } from "../lib/frame.ts"; import { + aligned, AREA, dimString, ftIn, @@ -27,7 +28,8 @@ import { LAYERS, noteColumn, put, - table, + SCHEDULE, + tableBottom, view, viewport, width, @@ -738,17 +740,19 @@ function levelTable(d: D, at: Point, w: number): number { ]; const c2 = 1.0; const c3 = 0.9; - return table( - d, + const right = { 1: "right", 2: "right" } as const; + const levels: TableOptions = { + style: SCHEDULE, at, - "LEVELS", - [ - { name: "LEVEL", width: w - c2 - c3 }, - { name: "ABOVE F.F.", width: c2, align: "right" }, - { name: "NAVD 88", width: c3, align: "right" }, - ], - rows.map(([name, z]) => [name, z >= 0 ? ftIn(z) : `-${ftIn(-z)}`, `${navd(z).toFixed(2)}'`]), - ); + columns: [w - c2 - c3, c2, c3], + title: "LEVELS", + header: aligned(["LEVEL", "ABOVE F.F.", "NAVD 88"], right), + rows: rows.map(([name, z]) => + aligned([name, z >= 0 ? ftIn(z) : `-${ftIn(-z)}`, `${navd(z).toFixed(2)}'`], right), + ), + }; + d.layer(LAYERS.text, {}, () => d.table(levels)); + return tableBottom(levels); } const VP = { h: 10.25 }; diff --git a/examples/plan-set/sheets/mep-e101.ts b/examples/plan-set/sheets/mep-e101.ts index cf16921..8d2c131 100644 --- a/examples/plan-set/sheets/mep-e101.ts +++ b/examples/plan-set/sheets/mep-e101.ts @@ -1,7 +1,7 @@ // E-101: the power and lighting plans of both floors at 3/16" = 1'-0", over a screened base // plan, with the legend, the panel schedule, the load calculation and the notes, all from the // circuits and devices in `mep-power.ts`. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { L1, L2, type Level } from "../model/house.ts"; import { frame } from "../lib/frame.ts"; import { arrowhead } from "../../lib/drafting.ts"; @@ -11,7 +11,9 @@ import { LAYERS, noteColumn, put, - table, + aligned, + SCHEDULE, + tableBottom, view, viewport, width, @@ -473,20 +475,20 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { phase[ph] += Number(left[4] || 0) + Number(right[4] || 0); rows.push([...left, ph, ...right.slice(1).reverse(), right[0]!]); } - const cols = [ - { name: "CKT", width: 0.42, align: "center" as const }, - { name: "DESCRIPTION", width: 2.75 }, - { name: "BKR", width: 0.72, align: "center" as const }, - { name: "WIRE", width: 0.5, align: "center" as const }, - { name: "VA", width: 0.55, align: "right" as const }, - { name: "PH", width: 0.36, align: "center" as const }, - { name: "VA", width: 0.55, align: "right" as const }, - { name: "WIRE", width: 0.5, align: "center" as const }, - { name: "BKR", width: 0.72, align: "center" as const }, - { name: "DESCRIPTION", width: 2.75, align: "right" as const }, - { name: "CKT", width: 0.42, align: "center" as const }, - ]; - const total = cols.reduce((s, c) => s + c.width, 0); + const columns = [0.42, 2.75, 0.72, 0.5, 0.55, 0.36, 0.55, 0.5, 0.72, 2.75, 0.42]; + const aligns = { + 0: "center", + 2: "center", + 3: "center", + 4: "right", + 5: "center", + 6: "right", + 7: "center", + 8: "center", + 9: "right", + 10: "center", + } as const; + const total = columns.reduce((s, w) => s + w, 0); let y = at[1]; d.layer(LAYERS.text, {}, () => { put(d, [at[0], y], `PANEL "${PANEL.name}" SCHEDULE`, H.label, { valign: "top" }); @@ -495,7 +497,19 @@ function panelSchedule(d: D, at: Point): { y: number; width: number } { put(d, [at[0], y], info, H.note, { valign: "top" }); y -= H.note + 0.1; }); - y = table(d, [at[0], y], "", cols, rows, { height: H.note, rowHeight: 0.2 }); + const panel: TableOptions = { + style: SCHEDULE, + at: [at[0], y], + columns, + header: aligned( + ["CKT", "DESCRIPTION", "BKR", "WIRE", "VA", "PH", "VA", "WIRE", "BKR", "DESCRIPTION", "CKT"], + aligns, + ), + rows: rows.map((row) => aligned(row, aligns)), + rowHeights: rows.map(() => 0.2), + }; + d.layer(LAYERS.text, {}, () => d.table(panel)); + y = tableBottom(panel); const connected = phase.A + phase.B; d.layer(LAYERS.text, {}, () => { y -= 0.2; @@ -538,17 +552,18 @@ function loadCalcTable(d: D, at: Point, w: number): number { ["TOTAL DEMAND LOAD", f(lc.total)], [`SERVICE: ${f(lc.total)} VA / 240 V`, `${lc.amps.toFixed(0)} A`], ]; - const y = table( - d, + const right = { 1: "right" } as const; + const calc: TableOptions = { + style: SCHEDULE, at, - "SERVICE LOAD CALCULATION (NEC 220.82)", - [ - { name: "LOAD", width: w - 0.85 }, - { name: "VA", width: 0.85, align: "right" }, - ], - rows, - { height: H.note, rowHeight: 0.2 }, - ); + columns: [w - 0.85, 0.85], + title: "SERVICE LOAD CALCULATION (NEC 220.82)", + header: aligned(["LOAD", "VA"], right), + rows: rows.map((row) => aligned(row, right)), + rowHeights: rows.map(() => 0.2), + }; + d.layer(LAYERS.text, {}, () => d.table(calc)); + const y = tableBottom(calc); let yy = y - 0.18; d.layer(LAYERS.text, {}, () => { const ok = lc.amps <= PANEL.amps; @@ -602,20 +617,18 @@ function fixtureSchedule(d: D, at: Point): number { mount, String(DEVICES.filter((x) => x.block === block).length), ]); - return table( - d, + const aligns = { 0: "center", 2: "right", 4: "right" } as const; + const schedule: TableOptions = { + style: SCHEDULE, at, - "LIGHTING FIXTURE SCHEDULE", - [ - { name: "TYPE", width: 0.5, align: "center" }, - { name: "DESCRIPTION", width: 5.6 }, - { name: "VA", width: 0.5, align: "right" }, - { name: "MOUNTING", width: 1.6 }, - { name: "QTY", width: 0.5, align: "right" }, - ], - rows, - { height: H.note, rowHeight: 0.22 }, - ); + columns: [0.5, 5.6, 0.5, 1.6, 0.5], + title: "LIGHTING FIXTURE SCHEDULE", + header: aligned(["TYPE", "DESCRIPTION", "VA", "MOUNTING", "QTY"], aligns), + rows: rows.map((row) => aligned(row, aligns)), + rowHeights: rows.map(() => 0.22), + }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } /** The service one-line diagram, not to scale, from the utility to panel A. */ diff --git a/examples/plan-set/sheets/mep-m101.ts b/examples/plan-set/sheets/mep-m101.ts index e6f8bc8..961445b 100644 --- a/examples/plan-set/sheets/mep-m101.ts +++ b/examples/plan-set/sheets/mep-m101.ts @@ -1,6 +1,6 @@ // M-101: the mechanical plans of both floors at 3/16" = 1'-0" over a screened base plan, with the // equipment, fan and room airflow schedules and the notes, all from `mep-hvac.ts`. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { ATTIC_ACCESS, L1, L2, type Level, type Rect } from "../model/house.ts"; import { CRITERIA } from "../project.ts"; import { frame } from "../lib/frame.ts"; @@ -13,7 +13,9 @@ import { leaderNote, noteColumn, put, - table, + aligned, + SCHEDULE, + tableBottom, view, viewport, width, @@ -548,26 +550,40 @@ function equipmentSchedule(d: D, at: Point): number { "AHRI MATCHED W/ AHU-2; LOCKING CAPS", ), ]; - return table( - d, + const aligns = { + 3: "center", + 4: "right", + 5: "right", + 6: "center", + 7: "center", + 9: "center", + } as const; + const schedule: TableOptions = { + style: SCHEDULE, at, - "MECHANICAL EQUIPMENT SCHEDULE", - [ - { name: "TAG", width: 0.55 }, - { name: "TYPE", width: 2.85 }, - { name: "LOCATION", width: 2.75 }, - { name: "TONS", width: 0.5, align: "center" }, - { name: "CFM", width: 0.55, align: "right" }, - { name: "COOL BTUH", width: 0.95, align: "right" }, - { name: "HEAT", width: 1.25, align: "center" }, - { name: "SEER2/HSPF2", width: 1.15, align: "center" }, - { name: "ELECTRICAL", width: 2.4 }, - { name: "CKT", width: 0.75, align: "center" }, - { name: "REMARKS", width: 3.5 }, - ], - rows, - { height: H.note, rowHeight: 0.22 }, - ); + columns: [0.55, 2.85, 2.75, 0.5, 0.55, 0.95, 1.25, 1.15, 2.4, 0.75, 3.5], + title: "MECHANICAL EQUIPMENT SCHEDULE", + header: aligned( + [ + "TAG", + "TYPE", + "LOCATION", + "TONS", + "CFM", + "COOL BTUH", + "HEAT", + "SEER2/HSPF2", + "ELECTRICAL", + "CKT", + "REMARKS", + ], + aligns, + ), + rows: rows.map((row) => aligned(row, aligns)), + rowHeights: rows.map(() => 0.22), + }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } function fanSchedule(d: D, at: Point): number { @@ -579,21 +595,21 @@ function fanSchedule(d: D, at: Point): number { x.capNote, circuit(x.ckt).label, ]); - const y = table( - d, + const aligns = { 2: "right", 5: "center" } as const; + const schedule: TableOptions = { + style: SCHEDULE, at, - "EXHAUST SCHEDULE", - [ - { name: "TAG", width: 0.55 }, - { name: "SERVES", width: 1.85 }, - { name: "CFM", width: 0.5, align: "right" }, - { name: "DUCT", width: 1.45 }, - { name: "TERMINATION, BACKDRAFT DAMPER", width: 2.65 }, - { name: "CKT", width: 0.7, align: "center" }, - ], - rows, - { height: H.note, rowHeight: 0.22 }, - ); + columns: [0.55, 1.85, 0.5, 1.45, 2.65, 0.7], + title: "EXHAUST SCHEDULE", + header: aligned( + ["TAG", "SERVES", "CFM", "DUCT", "TERMINATION, BACKDRAFT DAMPER", "CKT"], + aligns, + ), + rows: rows.map((row) => aligned(row, aligns)), + rowHeights: rows.map(() => 0.22), + }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + const y = tableBottom(schedule); const dl = dryerLength(); let yy = y - 0.2; d.layer(LAYERS.text, {}, () => { @@ -630,20 +646,17 @@ function airSchedule(d: D, at: Point): number { s.cfm.toLocaleString("en-US"), ]); } - return table( - d, + const aligns = { 1: "center", 2: "center", 3: "center", 4: "right" } as const; + const schedule: TableOptions = { + style: SCHEDULE, at, - "SUPPLY AND RETURN AIR BY ROOM", - [ - { name: "ROOM", width: 2.4 }, - { name: "UNIT", width: 0.7, align: "center" }, - { name: "OUTLETS", width: 0.75, align: "center" }, - { name: "NECK", width: 0.6, align: "center" }, - { name: "CFM", width: 0.65, align: "right" }, - ], - rows, - { height: H.note, rowHeight: 0.19 }, - ); + columns: [2.4, 0.7, 0.75, 0.6, 0.65], + title: "SUPPLY AND RETURN AIR BY ROOM", + header: aligned(["ROOM", "UNIT", "OUTLETS", "NECK", "CFM"], aligns), + rows: rows.map((row) => aligned(row, aligns)), + }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } const NOTES = (): string[] => { diff --git a/examples/plan-set/sheets/mep-p101.ts b/examples/plan-set/sheets/mep-p101.ts index bae55d0..ed20213 100644 --- a/examples/plan-set/sheets/mep-p101.ts +++ b/examples/plan-set/sheets/mep-p101.ts @@ -2,7 +2,7 @@ // an isometric of the pipes at the fixtures' real places in the plans; the DWV diagram is an // elevation of the stacks along the house, west to east. The fixture schedule adds up the // drainage and water supply fixture units of the same fixtures. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { HEIGHTS } from "../model/house.ts"; import { HOUSE_AT, LOT } from "./site.ts"; import { frame } from "../lib/frame.ts"; @@ -16,7 +16,9 @@ import { leaderNote, noteColumn, put, - table, + aligned, + SCHEDULE, + tableBottom, view, viewport, viewTitle, @@ -874,25 +876,29 @@ function fixtureSchedule(d: D, at: Point): number { num(f.wsfu[0]), ]); rows.push(["", "TOTAL", "", "", "", "", num(t.dfu), num(t.cold), num(t.hot), num(t.wsfu)]); - return table( - d, + const aligns = { + 3: "center", + 4: "center", + 5: "center", + 6: "right", + 7: "right", + 8: "right", + 9: "right", + } as const; + const schedule: TableOptions = { + style: SCHEDULE, at, - "PLUMBING FIXTURE SCHEDULE", - [ - { name: "TAG", width: 0.6 }, - { name: "FIXTURE", width: 2.75 }, - { name: "LOCATION", width: 1.45 }, - { name: "TRAP", width: 0.9, align: "center" }, - { name: "CW", width: 0.5, align: "center" }, - { name: "HW", width: 0.5, align: "center" }, - { name: "DFU", width: 0.5, align: "right" }, - { name: "WSFU CW", width: 0.8, align: "right" }, - { name: "WSFU HW", width: 0.8, align: "right" }, - { name: "WSFU TOT.", width: 0.85, align: "right" }, - ], - rows, - { height: H.note, rowHeight: 0.21 }, - ); + columns: [0.6, 2.75, 1.45, 0.9, 0.5, 0.5, 0.5, 0.8, 0.8, 0.85], + title: "PLUMBING FIXTURE SCHEDULE", + header: aligned( + ["TAG", "FIXTURE", "LOCATION", "TRAP", "CW", "HW", "DFU", "WSFU CW", "WSFU HW", "WSFU TOT."], + aligns, + ), + rows: rows.map((row) => aligned(row, aligns)), + rowHeights: rows.map(() => 0.21), + }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } function sizing(d: D, at: Point, w: number): number { @@ -925,17 +931,18 @@ function sizing(d: D, at: Point, w: number): number { [`BUILDING SEWER, 4" AT 1/8" PER FT., INV. AT P.L. C.O.`, `${sw.cleanout.toFixed(2)}' NAVD`], ]; if (t.dfu > 180) throw new Error(`The building drain carries ${t.dfu} DFU, more than 180`); - return table( - d, + const right = { 1: "right" } as const; + const basis: TableOptions = { + style: SCHEDULE, at, - "PIPE SIZING BASIS (FBC-R P2903.7)", - [ - { name: "ITEM", width: w - 1.8 }, - { name: "VALUE", width: 1.8, align: "right" }, - ], - rows, - { height: H.note, rowHeight: 0.2 }, - ); + columns: [w - 1.8, 1.8], + title: "PIPE SIZING BASIS (FBC-R P2903.7)", + header: aligned(["ITEM", "VALUE"], right), + rows: rows.map((row) => aligned(row, right)), + rowHeights: rows.map(() => 0.2), + }; + d.layer(LAYERS.text, {}, () => d.table(basis)); + return tableBottom(basis); } /** @@ -965,7 +972,7 @@ function heaterDetail(d: D, v: View): void { seed: 7, margin: 0.4, }); - earth(d, [ox - 24, oy - 16, 88, 12], [], v.p(0.12)); + earth(d, [ox - 24, oy - 12, 88, 8], [], v.p(0.12)); hatch(d, [ox - 8, oy, 8, 124], v.p(0.06), 1); hatch(d, [ox - 8, oy, 8, 124], v.p(0.06), -1); }); @@ -1039,34 +1046,35 @@ const WIRE_OF = (amps: number) => /** The water heater schedule. */ function heaterSchedule(d: D, at: Point): number { - return table( - d, + const aligns = { 2: "center", 3: "center", 4: "center", 5: "center", 6: "center" } as const; + const schedule: TableOptions = { + style: SCHEDULE, at, - "WATER HEATER SCHEDULE", - [ - { name: "TAG", width: 0.6 }, - { name: "TYPE", width: 2.4 }, - { name: "CAP.", width: 0.75, align: "center" }, - { name: "ELEMENTS", width: 1.3, align: "center" }, - { name: "ELECTRICAL", width: 1.9, align: "center" }, - { name: "RECOVERY", width: 1.6, align: "center" }, - { name: "UEF", width: 0.6, align: "center" }, - { name: "LOCATION", width: 2.6 }, - ], - [ - [ - "WH-1", - "ELECTRIC STORAGE, LISTED", - "50 GAL.", - "2 X 4500 W", - "240 V, 30 A/2P (E-101)", - "21 GPH AT 90 F", - "0.92", - "GARAGE NE CORNER, PLATFORM", - ], + columns: [0.6, 2.4, 0.75, 1.3, 1.9, 1.6, 0.6, 2.6], + title: "WATER HEATER SCHEDULE", + header: aligned( + ["TAG", "TYPE", "CAP.", "ELEMENTS", "ELECTRICAL", "RECOVERY", "UEF", "LOCATION"], + aligns, + ), + rows: [ + aligned( + [ + "WH-1", + "ELECTRIC STORAGE, LISTED", + "50 GAL.", + "2 X 4500 W", + "240 V, 30 A/2P (E-101)", + "21 GPH AT 90 F", + "0.92", + "GARAGE NE CORNER, PLATFORM", + ], + aligns, + ), ], - { height: H.note, rowHeight: 0.21 }, - ); + rowHeights: [0.21], + }; + d.layer(LAYERS.text, {}, () => d.table(schedule)); + return tableBottom(schedule); } function legend(d: D, at: Point, w: number): number { @@ -1134,21 +1142,22 @@ function p101(d: D): void { { numbered: false }, ); const hs = heaterSchedule(dd, [rx, Math.min(n1, n2) - 0.4]); - // The water heater detail, through a viewport, under the schedules. + // The water heater detail, through a viewport, under the schedules. The view holds the whole + // detail, from the earth under the slab to the top of the wall, so no pattern is cut at its edge. const vd = view(dd, 16); - const vpTop = hs - 0.5; - const vpH = vpTop - 2.0; + const vpTop = hs - 0.3; + const vpH = vpTop - 1.9; const vpW = AREA.right - rx - 0.1; viewport(dd, sheet, { - corner: [rx, 2.0], + corner: [rx, 1.9], size: [vpW, vpH], - center: [WH_ORIGIN[0] + 28, WH_ORIGIN[1] + 58], + center: [WH_ORIGIN[0] + 28, WH_ORIGIN[1] + 56], v: vd, id: "vp-P-101-wh", number: "3", sheetNo: "P-101", title: "WATER HEATER INSTALLATION", - titleAt: [rx + 0.1, 1.5], + titleAt: [rx + 0.1, 1.4], }); void width; }); diff --git a/examples/plan-set/sheets/roof.ts b/examples/plan-set/sheets/roof.ts index 100b33c..e08d808 100644 --- a/examples/plan-set/sheets/roof.ts +++ b/examples/plan-set/sheets/roof.ts @@ -1,7 +1,7 @@ // A-103: the roof plan at 1/4" = 1'-0": the hip roof from `ROOF`, the lanai's shed roof, slopes, // gutters and downspouts, the walls below dashed, and the attic ventilation worked out from the // attic's area. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { DEPTH, HEIGHTS, LANAI, ROOF, ROOF_VENTS, W } from "../model/house.ts"; import { frame } from "../lib/frame.ts"; import { @@ -14,7 +14,9 @@ import { put, revisionCloud, slopeArrow, - table, + aligned, + SCHEDULE, + tableBottom, view, viewport, type D, @@ -185,15 +187,14 @@ function sheet(d: D): void { "DOWNSPOUTS DISCHARGE TO SPLASH BLOCKS DIRECTED TO THE SIDE SWALES. SEE C-101.", ]); y -= 0.3; - y = table( - dd, - [x, y], - "ATTIC VENTILATION (FBC-R R806.2)", - [ - { name: "ITEM", width: 4.0 }, - { name: "SQ. FT.", width: w - 4.0, align: "right" }, - ], - [ + const right = { 1: "right" } as const; + const vents: TableOptions = { + style: SCHEDULE, + at: [x, y], + columns: [4.0, w - 4.0], + title: "ATTIC VENTILATION (FBC-R R806.2)", + header: aligned(["ITEM", "SQ. FT."], right), + rows: [ ["ATTIC FLOOR AREA", attic.toFixed(0)], ["NET FREE AREA REQ. AT 1/150", required150.toFixed(2)], ["NET FREE AREA REQ. AT 1/300 (BALANCED)", required.toFixed(2)], @@ -208,8 +209,10 @@ function sheet(d: D): void { ], [`SOFFIT VENT, ${soffitLength.toFixed(0)} LF AT 9 SQ. IN./FT.`, soffitVent.toFixed(2)], ["TOTAL PROVIDED", (upper + soffitVent).toFixed(2)], - ], - ); + ].map((row) => aligned(row, right)), + }; + dd.layer(LAYERS.text, {}, () => dd.table(vents)); + y = tableBottom(vents); noteColumn( dd, [x, y - 0.25], diff --git a/examples/plan-set/sheets/schedules.ts b/examples/plan-set/sheets/schedules.ts index 3eb689b..fd23aff 100644 --- a/examples/plan-set/sheets/schedules.ts +++ b/examples/plan-set/sheets/schedules.ts @@ -1,7 +1,7 @@ // A-601: the door and window schedules, read from the openings of `model/house.ts`, with each // window's wind zone and design pressure worked out, the egress check of each bedroom window, // and elevations of the window types drawn on the sheet. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { L1, L2, @@ -15,13 +15,15 @@ import { alongXOf, widthOf } from "../model/geometry.ts"; import { designPressure, endZone, meanRoofHeight, psf, qh } from "../model/wind.ts"; import { frame } from "../lib/frame.ts"; import { + aligned, AREA, ftIn, H, LAYERS, noteColumn, put, - table, + SCHEDULE, + tableBottom, type D, type SheetDraw, } from "../lib/kit.ts"; @@ -100,24 +102,29 @@ function sheet(d: D): void { ]); } } - let y = table( - dd, - [x0, AREA.top - 0.1], - "DOOR SCHEDULE", - [ - { name: "NO.", width: 0.55, align: "center" }, - { name: "ROOM", width: 2.0 }, - { name: "TYPE", width: 0.6, align: "center" }, - { name: "WIDTH", width: 0.8, align: "center" }, - { name: "HEIGHT", width: 0.8, align: "center" }, - { name: "THICK.", width: 0.7, align: "center" }, - { name: "MATERIAL", width: 2.2 }, - { name: "DP (PSF)", width: 1.3, align: "center" }, - { name: "REMARKS", width: 3.6 }, - ], - doors, - { rowHeight: 0.24 }, - ); + const draw = (t: TableOptions) => dd.layer(LAYERS.text, {}, () => dd.table(t)); + const doorAligns = { + 0: "center", + 2: "center", + 3: "center", + 4: "center", + 5: "center", + 7: "center", + } as const; + const doorSchedule: TableOptions = { + style: SCHEDULE, + at: [x0, AREA.top - 0.1], + columns: [0.55, 2.0, 0.6, 0.8, 0.8, 0.7, 2.2, 1.3, 3.6], + title: "DOOR SCHEDULE", + header: aligned( + ["NO.", "ROOM", "TYPE", "WIDTH", "HEIGHT", "THICK.", "MATERIAL", "DP (PSF)", "REMARKS"], + doorAligns, + ), + rows: doors.map((row) => aligned(row, doorAligns)), + rowHeights: doors.map(() => 0.24), + }; + draw(doorSchedule); + let y = tableBottom(doorSchedule); // The door types, drawn at 1/4" = 1'-0". y -= 0.3; @@ -186,40 +193,27 @@ function sheet(d: D): void { } y -= 0.35; const listTop = y; - table( - dd, - [x0, y], - "WINDOW LIST", - [ - { name: "MARK", width: 0.7, align: "center" }, - { name: "TYPE", width: 0.6, align: "center" }, - { name: "ROOM", width: 2.2 }, - { name: "WIND ZONE", width: 1.1, align: "center" }, - { name: "DP (PSF, ASD)", width: 1.6, align: "center" }, - { name: "EGRESS (5.7 SF)", width: 1.6, align: "center" }, - ], - windows, - { rowHeight: 0.22 }, - ); + const listAligns = { 0: "center", 1: "center", 3: "center", 4: "center", 5: "center" } as const; + draw({ + style: SCHEDULE, + at: [x0, y], + columns: [0.7, 0.6, 2.2, 1.1, 1.6, 1.6], + title: "WINDOW LIST", + header: aligned( + ["MARK", "TYPE", "ROOM", "WIND ZONE", "DP (PSF, ASD)", "EGRESS (5.7 SF)"], + listAligns, + ), + rows: windows.map((row) => aligned(row, listAligns)), + rowHeights: windows.map(() => 0.22), + }); // The window types, with an elevation of each at 1/2" = 1'-0". const x2 = x0 + 8.4; - y = table( - dd, - [x2, listTop], - "WINDOW TYPES", - [ - { name: "TYPE", width: 0.6, align: "center" }, - { name: "QTY.", width: 0.6, align: "center" }, - { name: "SIZE (W X H)", width: 1.4, align: "center" }, - { name: "OPERATION", width: 1.7 }, - { name: "HEAD", width: 0.8, align: "center" }, - { name: "CLEAR OPENING", width: 1.3, align: "center" }, - { name: "GLAZING", width: 3.2 }, - ], - Object.entries(WINDOW_TYPES).map(([tag, t]) => { - const e = egress(tag); - return [ + const typeAligns = { 0: "center", 1: "center", 2: "center", 4: "center", 5: "center" } as const; + const typeRows = Object.entries(WINDOW_TYPES).map(([tag, t]) => { + const e = egress(tag); + return aligned( + [ tag, String(count[tag] ?? 0), `${ftIn(t.width)} X ${ftIn(t.height)}`, @@ -227,10 +221,24 @@ function sheet(d: D): void { `7'-2"/8'-0"`, `${e.w}" X ${e.h}"`, t.note, - ]; - }), - { rowHeight: 0.24 }, - ); + ], + typeAligns, + ); + }); + const windowTypes: TableOptions = { + style: SCHEDULE, + at: [x2, listTop], + columns: [0.6, 0.6, 1.4, 1.7, 0.8, 1.3, 3.2], + title: "WINDOW TYPES", + header: aligned( + ["TYPE", "QTY.", "SIZE (W X H)", "OPERATION", "HEAD", "CLEAR OPENING", "GLAZING"], + typeAligns, + ), + rows: typeRows, + rowHeights: typeRows.map(() => 0.24), + }; + draw(windowTypes); + y = tableBottom(windowTypes); y -= 0.5; dd.layer(LAYERS.text, {}, () => { put(dd, [x2, y], "WINDOW TYPE ELEVATIONS", H.label, { valign: "top" }); diff --git a/examples/plan-set/sheets/site.ts b/examples/plan-set/sheets/site.ts index 32be2ee..36a472e 100644 --- a/examples/plan-set/sheets/site.ts +++ b/examples/plan-set/sheets/site.ts @@ -2,7 +2,7 @@ // front left property corner. The lot, setbacks, the house, the pool, the drive, utilities, // grades and drainage, with site data and notes on the sheet. `INTENT` holds the setbacks the // house and the pool keep, which every build checks. -import type { Intent, Point } from "../../../src/index.ts"; +import type { Intent, Point, TableOptions } from "../../../src/index.ts"; import { CRITERIA, PROJECT } from "../project.ts"; import { DEPTH, ENTRY, FOOTPRINT, LANAI, LANAI_SLAB, ROOF, W } from "../model/house.ts"; import { frame } from "../lib/frame.ts"; @@ -14,7 +14,9 @@ import { leaderNote, noteColumn, put, - table, + aligned, + SCHEDULE, + tableBottom, view, viewport, type D, @@ -457,15 +459,13 @@ function sheet(d: D): void { const w = AREA.right - x; let y = AREA.top - 0.1; const sf = (n: number) => `${Math.round(n).toLocaleString("en-US")} SF`; - y = table( - dd, - [x, y], - "SITE DATA", - [ - { name: "ITEM", width: 3.6 }, - { name: "VALUE", width: w - 3.6 }, - ], - [ + const siteData: TableOptions = { + style: SCHEDULE, + at: [x, y], + columns: [3.6, w - 3.6], + title: "SITE DATA", + header: ["ITEM", "VALUE"], + rows: [ ["PARCEL", PROJECT.parcel], ["PARCEL ID", PROJECT.parcelId], ["ZONING", CRITERIA.zoning.district], @@ -491,27 +491,28 @@ function sheet(d: D): void { `${heightAboveDfe.toFixed(2)}' D.F.E. TO MEAN ROOF (${CRITERIA.zoning.maxHeight}' MAX.)`, ], ], - ); + }; + dd.layer(LAYERS.text, {}, () => dd.table(siteData)); + y = tableBottom(siteData); y -= 0.25; const ft = (n: number) => `${n.toFixed(1)}'`; const z = CRITERIA.zoning; - y = table( - dd, - [x, y], - "SETBACKS", - [ - { name: "SIDE", width: 1.6 }, - { name: "REQUIRED", width: 1.4, align: "center" }, - { name: "PROVIDED", width: 1.4, align: "center" }, - { name: "POOL REQ.", width: w - 4.4, align: "center" }, - ], - [ + const center = { 1: "center", 2: "center", 3: "center" } as const; + const setbacks: TableOptions = { + style: SCHEDULE, + at: [x, y], + columns: [1.6, 1.4, 1.4, w - 4.4], + title: "SETBACKS", + header: aligned(["SIDE", "REQUIRED", "PROVIDED", "POOL REQ."], center), + rows: [ ["FRONT (S)", ft(z.front), ft(provided.front), "-"], ["REAR (N)", ft(z.rear), ft(provided.rear), ft(z.poolRear)], ["SIDE (W)", ft(z.side), ft(provided.left), ft(z.poolSide)], ["SIDE (E)", ft(z.side), ft(provided.right), ft(z.poolSide)], - ], - ); + ].map((row) => aligned(row, center)), + }; + dd.layer(LAYERS.text, {}, () => dd.table(setbacks)); + y = tableBottom(setbacks); y -= 0.25; y = noteColumn(dd, [x, y], w, "SITE NOTES", [ "BOUNDARY, BEARINGS AND EXISTING GRADES FROM A SURVEY BY OTHERS (FICTIONAL), NAVD 88. VERIFY BEFORE CONSTRUCTION.", diff --git a/examples/plan-set/sheets/structure-details.ts b/examples/plan-set/sheets/structure-details.ts index a60a377..85797e2 100644 --- a/examples/plan-set/sheets/structure-details.ts +++ b/examples/plan-set/sheets/structure-details.ts @@ -1,6 +1,6 @@ // S-501: four structural details, each in its own viewport at its own scale, with the // structural general notes and the design criteria table on the paper. -import type { Point } from "../../../src/index.ts"; +import type { Point, TableOptions } from "../../../src/index.ts"; import { CRITERIA } from "../project.ts"; import { HEIGHTS } from "../model/house.ts"; import { endZone, meanRoofHeight, qh, roofAngle, roofPressures } from "../model/structure-wind.ts"; @@ -12,7 +12,9 @@ import { LAYERS, leaderNote, noteColumn, - table, + aligned, + SCHEDULE, + tableBottom, view, viewport, type D, @@ -496,31 +498,30 @@ export function detailsSheet(d: D): void { const x = AREA.left + 2 * w + 0.6; const cw = AREA.right - x; let y = AREA.top - 0.1; - y = table( - dd, - [x, y], - "DESIGN CRITERIA", - [ - { name: "ITEM", width: 2.9 }, - { name: "VALUE", width: cw - 2.9 }, - ], - CRITERIA_ROWS, - ); + const criteria: TableOptions = { + style: SCHEDULE, + at: [x, y], + columns: [2.9, cw - 2.9], + title: "DESIGN CRITERIA", + header: ["ITEM", "VALUE"], + rows: CRITERIA_ROWS, + }; + dd.layer(LAYERS.text, {}, () => dd.table(criteria)); + y = tableBottom(criteria); y -= 0.35; y = noteColumn(dd, [x, y], cw, "STRUCTURAL GENERAL NOTES", GENERAL); y -= 0.25; - y = table( - dd, - [x, y], - "ROOF COMPONENT AND CLADDING PRESSURES (ASD)", - [ - { name: "ZONE", width: 0.8, align: "center" }, - { name: "LOCATION", width: 2.9 }, - { name: "GCP (+ / -)", width: 1.1, align: "center" }, - { name: "PSF (+ / -)", width: cw - 4.8, align: "center" }, - ], - ROOF_CC_ROWS, - ); + const center = { 0: "center", 2: "center", 3: "center" } as const; + const pressures: TableOptions = { + style: SCHEDULE, + at: [x, y], + columns: [0.8, 2.9, 1.1, cw - 4.8], + title: "ROOF COMPONENT AND CLADDING PRESSURES (ASD)", + header: aligned(["ZONE", "LOCATION", "GCP (+ / -)", "PSF (+ / -)"], center), + rows: ROOF_CC_ROWS.map((row) => aligned(row, center)), + }; + dd.layer(LAYERS.text, {}, () => dd.table(pressures)); + y = tableBottom(pressures); y -= 0.25; noteColumn(dd, [x, y], cw, "ROOF PRESSURE NOTES", ROOF_CC_NOTES); }); diff --git a/examples/plan-set/sheets/structure-framing.ts b/examples/plan-set/sheets/structure-framing.ts index afd3f12..c3f3c9c 100644 --- a/examples/plan-set/sheets/structure-framing.ts +++ b/examples/plan-set/sheets/structure-framing.ts @@ -26,7 +26,8 @@ import { noteColumn, put, slopeArrow, - table, + aligned, + SCHEDULE, view, viewport, type D, @@ -633,41 +634,34 @@ export function framingSheet(d: D): void { legend(dd, [x, y], AREA.right - x); // The schedules along the bottom. const ty = top - hgt - 1.1; - table( - dd, - [AREA.left, ty], - "UPLIFT CONNECTOR SCHEDULE", - [ - { name: "MARK", width: 0.55, align: "center" }, - { name: "LOCATION", width: 4.2 }, - { name: "MIN. UPLIFT (LB)", width: 1.25, align: "center" }, - { name: "TYPE", width: 1.5 }, - ], - CONNECTORS, - ); - table( - dd, - [AREA.left + 7.9, ty], - "LINTEL SCHEDULE", - [ - { name: "MARK", width: 0.55, align: "center" }, - { name: "OPENING", width: 0.95 }, - { name: "LINTEL", width: 1.9 }, - { name: "AT OPENINGS", width: 2.0 }, - ], - LINTELS, - ); - table( - dd, - [AREA.left + 13.7, ty], - "BEAM AND HEADER SCHEDULE", - [ - { name: "MARK", width: 0.65, align: "center" }, - { name: "MEMBER", width: 3.1 }, - { name: "REINF. / NOTES", width: 2.35 }, - ], - BEAMS, - ); + const connectorAligns = { 0: "center", 2: "center" } as const; + const mark = { 0: "center" } as const; + dd.layer(LAYERS.text, {}, () => { + dd.table({ + style: SCHEDULE, + at: [AREA.left, ty], + columns: [0.55, 4.2, 1.25, 1.5], + title: "UPLIFT CONNECTOR SCHEDULE", + header: aligned(["MARK", "LOCATION", "MIN. UPLIFT (LB)", "TYPE"], connectorAligns), + rows: CONNECTORS.map((row) => aligned(row, connectorAligns)), + }); + dd.table({ + style: SCHEDULE, + at: [AREA.left + 7.9, ty], + columns: [0.55, 0.95, 1.9, 2.0], + title: "LINTEL SCHEDULE", + header: aligned(["MARK", "OPENING", "LINTEL", "AT OPENINGS"], mark), + rows: LINTELS.map((row) => aligned(row, mark)), + }); + dd.table({ + style: SCHEDULE, + at: [AREA.left + 13.7, ty], + columns: [0.65, 3.1, 2.35], + title: "BEAM AND HEADER SCHEDULE", + header: aligned(["MARK", "MEMBER", "REINF. / NOTES"], mark), + rows: BEAMS.map((row) => aligned(row, mark)), + }); + }); const dw = 11.0; const dh = 4.9; const dc: Point = [AREA.left, AREA.bottom + 0.65]; diff --git a/src/blocks.ts b/src/blocks.ts index e9050bd..31b3ef9 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -762,6 +762,8 @@ interface Entered { /** The next item to read: an entity until `entities` is false, then an attribute definition. */ next: number; entities: boolean; + /** The inserts the last item drawn holds, as `holding` gives them, and the next to enter. */ + queued?: { readonly inserts: readonly Insert[]; next: number } | undefined; } /** True for an index of a list that holds an item, which is not an empty slot or past its end. */ @@ -790,6 +792,9 @@ function holds(list: readonly unknown[], index: number): boolean { * @param spend - Asked for 1 before the walk enters a block and before it reads each item of * one. The walk ends when it says no. * @param key - `layerKey`, which the walk finds a block by. + * @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. * @returns False when `spend` ended the walk. */ export function eachDrawn( @@ -800,6 +805,7 @@ export function eachDrawn( xrefs?: ReadonlyMap, spend: (cost: number) => boolean = () => true, key: (name: string) => string = layerKey, + holding?: (entity: Exclude, placement: Placement) => readonly Insert[], ): boolean { if (entity.kind !== "insert") { draw(entity, { @@ -854,17 +860,28 @@ export function eachDrawn( const { inside } = at; const layerOf = (name: string): LayerRef => name === "0" ? at.layer : inside ? { name, of: inside } : { name }; + // One at a time, so two that place one block do not find it open. + if (at.queued !== undefined && at.queued.next < at.queued.inserts.length) { + const insert = at.queued.inserts[at.queued.next++]!; + if (!enter(insert, at.inner, inside, at.matrix, layerOf(insert.layer))) return false; + continue; + } if (at.entities && !holds(at.items, at.next)) [at.entities, at.next] = [false, 0]; if (at.entities) { const item = at.items[at.next++]!; if (!spend(1)) return false; if (item.kind !== "insert") { - draw(item, { + const placement: Placement = { matrix: at.matrix, layer: layerOf(item.layer), insertLayer: at.layer, from: inside, - }); + }; + draw(item, placement); + if (inside !== undefined && holding !== undefined) { + const inserts = holding(item, placement); + at.queued = inserts.length > 0 ? { inserts, next: 0 } : undefined; + } } else if (!enter(item, at.inner, inside, at.matrix, layerOf(item.layer))) return false; continue; } diff --git a/src/drawing.ts b/src/drawing.ts index 5b50bed..f871aa2 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -44,6 +44,13 @@ import { leaderStyleDictionaryHandle, validLeaderStyleHandle, } from "./leaders.ts"; +import { + STANDARD_TABLE_STYLE, + tableMargins, + tableStyleDictionaryHandle, + tableTexts, + validTableStyleHandle, +} from "./tables.ts"; import { fmt, written } from "./format.ts"; import { validIdHandle } from "./handles.ts"; import { layerAuditKey, layerKey, layoutNameKey } from "./layers.ts"; @@ -103,6 +110,14 @@ import { leaderStyleNameProblem, leaderStyleProblem, leaderStyleTwinProblem, + standardTableStyleProblem, + TABLE_IN_BLOCK, + tableColumnsProblem, + tableTextsProblem, + tableProblem, + tableStyleNameProblem, + tableStyleProblem, + tableStyleTwinProblem, leaderTextProblem, placedAttributeProblem, layerColorProblem, @@ -1095,6 +1110,67 @@ export interface Wipeout extends EntityBase { readonly points: readonly Point[]; } +/** + * A cell of a table: its text, or an object with what it holds and what it changes of its row's + * cell style. A text is paragraph text, with a paragraph's codes, which wraps at the column's width + * less the margins and makes its row as tall as it needs. + */ +export type TableCell = string | TableCellContent; + +/** What a cell holds, and what it changes of its row's cell style. */ +export interface TableCellContent { + /** Its text, as a paragraph's value with its codes. `\P` breaks a line. */ + readonly text?: string; + /** A block of the drawing, in place of a text. It takes no attribute values. */ + readonly block?: string; + /** The block's scale. Missing, the block is scaled to fit the cell, less its margins. */ + readonly blockScale?: number; + /** How many columns it spans, from its own to the right. Defaults to 1. */ + readonly columnSpan?: number; + /** How many rows it spans, from its own down. Defaults to 1. */ + readonly rowSpan?: number; + readonly align?: ParagraphAlign; + readonly valign?: ParagraphVerticalAlign; + /** The height of its text's capitals. */ + readonly textHeight?: number; + /** The color index of its text. */ + readonly color?: number; + /** The color index it is filled with, as a swatch. */ + readonly fill?: number; +} + +/** + * A table: a title row, a header row and data rows, in columns, which the leading CAD app holds as + * one table entity a drafter adds a row to, resizes and edits cell by cell. Each row is as tall as + * its tallest cell needs, and no less than the height given for it. R2018 only. + */ +export interface Table extends Placed { + readonly kind: "table"; + /** A table style of the drawing. */ + readonly style: string; + /** Its upper left corner. */ + readonly at: Point; + /** Degrees counterclockwise. Defaults to 0. */ + readonly rotation?: number; + /** The width of each column, from the left. */ + readonly columns: readonly number[]; + /** The title, in one cell across every column. Missing, the table has no title row. */ + readonly title?: TableCell; + /** The least height of the title row. */ + readonly titleHeight?: number; + /** + * The header row, a cell for each column. Missing, the table has no header row. A cell that + * another spans is `null`. + */ + readonly header?: readonly (TableCell | null)[]; + /** The least height of the header row. */ + readonly headerHeight?: number; + /** The data rows, from the top, each with a cell for each column. A cell that another spans is `null`. */ + readonly rows: readonly (readonly (TableCell | null)[])[]; + /** The least height of each data row, or `null` for as tall as its cells need. */ + readonly rowHeights?: readonly (number | null)[]; +} + export type Entity = | Line | Polyline @@ -1116,7 +1192,44 @@ export type Entity = | Leader | Image | Hatch - | Wipeout; + | Wipeout + | Table; + +/** How the cells of one kind of row are drawn. Each size missing is its table style's. */ +export interface TableCellStyle { + /** The text style of its cells. Defaults to its table style's. */ + readonly textStyle?: string; + /** The height of its text's capitals. Defaults to its table style's. */ + readonly textHeight?: number; + readonly align?: ParagraphAlign; + readonly valign?: ParagraphVerticalAlign; + /** The color index of its text. Missing, its table's. */ + readonly color?: number; + /** The color index its cells are filled with. Missing, they are not filled. */ + readonly fill?: number; + /** The lineweight of its cells' borders, in millimetres. Missing, its table's. */ + readonly lineweight?: number; +} + +/** + * A table style: how the tables that name it are drawn. Its title row's cells are centered + * across and up and down, as are its header's, and its data cells' are centered across at the + * top, unless a cell style says otherwise. + */ +export interface TableStyle { + readonly name: string; + /** The text style of its cells. Defaults to `"Standard"`. */ + readonly textStyle?: string; + /** The height of its text's capitals, for each kind of row that gives none of its own. */ + readonly textHeight: number; + /** The room between a cell's sides and its content. Defaults to a third of `textHeight`. */ + readonly horizontalMargin?: number; + /** The room between a cell's top and bottom and its content. Defaults to a third of `textHeight`. */ + readonly verticalMargin?: number; + readonly title?: TableCellStyle; + readonly header?: TableCellStyle; + readonly data?: TableCellStyle; +} /** * A leader style: how the leaders that name it are drawn. Its sizes are the sizes its leaders @@ -1460,6 +1573,8 @@ export interface Drawing { readonly dimensionStyles?: readonly DimensionStyle[]; /** The leader styles that leaders name. */ readonly leaderStyles?: readonly LeaderStyle[]; + /** The table styles that tables name. */ + readonly tableStyles?: readonly TableStyle[]; /** * Whether each image's frame shows and plots: its outline, or its clip's, in its pen. Defaults * to true, as the leading CAD app has it. A sheet with a logo or an aerial wants false. @@ -2700,6 +2815,9 @@ export interface StandardLeaderOptions< } /** What `layout()` sets on a layout. */ +/** The options of `table()`: the table, but for its kind and its layer, which is the current one. */ +export type TableOptions = Omit; + export interface LayoutOptions

{ /** One of `PAPERS`, such as `"ARCH D"`. */ readonly paper: PaperOf

; @@ -2939,6 +3057,7 @@ function located( | "textStyle" | "dimensionStyle" | "leaderStyle" + | "tableStyle" | "block" | "attribute" | "xref" @@ -3048,6 +3167,8 @@ export class DrawingBuilder< /** Keyed by `layerKey`: leader style names are compared as dimension style names are. */ readonly #leaderStyles = new Map(); readonly #leaderStylesAudited = new Map(); + readonly #tableStyles = new Map(); + readonly #tableStylesAudited = new Map(); /** The blocks of the arrowheads the leader styles use, whose handles are taken. */ readonly #leaderArrowheadBlocks = new Set(); /** The views `view()` declared, by `idKey` of their ids. */ @@ -5241,6 +5362,182 @@ export class DrawingBuilder< this.#leaderStylesAudited.set(layerAuditKey(named), named); } + /** + * Defines a table style: the text height of its cells, its margins, and the cell style of its + * title, its header and its data rows. A table names it by `style`. R2018 only. + * + * ```ts + * d.tableStyle({ name: "SCHEDULE", textHeight: 0.1, title: { textHeight: 0.15 } }); + * ``` + */ + tableStyle(style: TableStyle): this { + const definition = style as unknown as TableStyle; + try { + if (this.dxf === "R12") refuse("table-style", R12_ONLY.tables); + this.#defineTableStyle(definition); + } catch (thrown) { + const name: unknown = (definition as { name?: unknown } | null)?.name; + const about = typeof name === "string" ? { tableStyle: name } : {}; + throw located(thrown, DrawingBuilder.prototype.tableStyle, about); + } + return this; + } + + /** Checks a table style and stores it. */ + #defineTableStyle(definition: TableStyle): void { + const name: unknown = (definition as { name?: unknown } | null)?.name; + const fail = (rule: LintRule, problem: string): never => + refuse( + rule, + `Table style ${typeof name === "string" ? JSON.stringify(name) : "with no name"}: ${problem}`, + ); + const problem = tableStyleProblem(definition); + if (problem) fail("table-style", problem); + const named = name as string; + const first = this.#tableStylesAudited.get(layerAuditKey(named)); + if (first !== undefined) fail("duplicate-table-style", tableStyleTwinProblem(named, first)!); + // Each text style it names is the drawing's, under the name the drawing has it by. + const textStyleOf = (given: string | undefined, field: string): string | undefined => { + if (given === undefined || isStandardTextStyle(given)) return undefined; + const found = this.#textStyles.get(layerKey(given))?.name; + if (found === undefined) { + fail( + "undefined-text-style", + `${field}: text style ${JSON.stringify(given)} is not defined. Define it with textStyle() first`, + ); + } + return found; + }; + const textStyle = textStyleOf(definition.textStyle, "textStyle"); + const cells: Partial> = {}; + for (const kind of ["title", "header", "data"] as const) { + const own = definition[kind]; + if (own === undefined) continue; + // A row's own `Standard` stays, since it differs from a style's other text style. + const ownText = + own.textStyle !== undefined && isStandardTextStyle(own.textStyle) + ? STANDARD_TEXT_STYLE + : textStyleOf(own.textStyle, `${kind}.textStyle`); + const { textStyle: _given, ...rest } = own; + cells[kind] = { ...(ownText === undefined ? {} : { textStyle: ownText }), ...rest }; + } + const taken: string[] = []; + try { + this.#claim( + validTableStyleHandle(named), + `the table style ${JSON.stringify(named)}`, + undefined, + taken, + ); + // The first style brings the leading CAD app's own and the dictionary that holds them. + if (this.#tableStyles.size === 0) { + this.#claim( + validTableStyleHandle(STANDARD_TABLE_STYLE), + 'the table style "Standard"', + undefined, + taken, + ); + this.#claim( + tableStyleDictionaryHandle(), + "the dictionary of table styles", + undefined, + taken, + ); + } + } catch (thrown) { + for (const handle of taken) this.#handles.delete(handle); + throw thrown; + } + this.#tableStyles.set(layerKey(named), { + name: named, + ...(textStyle === undefined ? {} : { textStyle }), + textHeight: definition.textHeight, + ...(definition.horizontalMargin === undefined + ? {} + : { horizontalMargin: definition.horizontalMargin }), + ...(definition.verticalMargin === undefined + ? {} + : { verticalMargin: definition.verticalMargin }), + ...cells, + }); + this.#tableStylesAudited.set(layerAuditKey(named), named); + } + + /** + * Draws a table on the current layer, its upper left corner at `at`: a title in one cell across + * its columns, a header row and data rows, each row a list of cells, one for each column, with + * `null` for a cell that another spans. The leading CAD app holds it as one table a drafter adds + * a row to, resizes and edits cell by cell. R2018 only. + * + * ```ts + * d.table({ + * style: "SCHEDULE", + * at: [1, 10], + * columns: [0.6, 1.2, 2.4], + * title: "DOOR SCHEDULE", + * header: ["MARK", "SIZE", "NOTES"], + * rows: [["D1", "3'-0\" x 7'-0\"", "SOLID CORE"]], + * }); + * ``` + */ + table(options: TableOptions): this { + return this.#add(DrawingBuilder.prototype.table, options as object, () => + this.#table(options as unknown), + ); + } + + /** Checks a table and what it names, and returns it. */ + #table(given: unknown): Table { + if (this.dxf === "R12") refuse("table", R12_ONLY.tables); + if (this.#open) refuse("table", TABLE_IN_BLOCK); + const o = (typeof given === "object" && given !== null ? given : {}) as Record; + const named = o.style; + const nameProblem = tableStyleNameProblem(named); + if (nameProblem) refuse("undefined-table-style", nameProblem); + const standard = standardTableStyleProblem(named as string); + if (standard) refuse("undefined-table-style", standard); + const style = this.#tableStyles.get(layerKey(named as string)); + if (style === undefined) { + refuse( + "undefined-table-style", + `Table style ${JSON.stringify(named)} is not defined. Define it with tableStyle() first`, + ); + } + const problem = tableProblem(o, (name) => this.#blocks.has(layerKey(name))); + if (problem) refuse("table", problem); + const narrow = tableColumnsProblem(o.columns as number[], tableMargins(style!)[0]); + if (narrow) refuse("table", narrow); + const fontOf = (name: string | undefined) => + name === undefined || isStandardTextStyle(name) + ? STANDARD_FONT + : this.#textStyles.get(layerKey(name))?.font; + const lettered = tableTextsProblem(tableTexts(o as unknown as Table, style!), fontOf); + if (lettered) refuse("table", lettered); + const blockName = (cell: unknown): unknown => { + if (typeof cell !== "object" || cell === null) return cell; + const content = cell as TableCellContent; + if (content.block === undefined) return { ...content }; + return { ...content, block: this.#blocks.get(layerKey(content.block))!.name }; + }; + const row = (cells: readonly unknown[]) => cells.map(blockName) as (TableCell | null)[]; + return { + kind: "table", + layer: this.#current, + style: style!.name, + at: pt(o.at as Point), + ...(o.rotation === undefined || o.rotation === 0 ? {} : { rotation: o.rotation as number }), + columns: [...(o.columns as number[])], + ...(o.title === undefined ? {} : { title: blockName(o.title) as TableCell }), + ...(o.titleHeight === undefined ? {} : { titleHeight: o.titleHeight as number }), + ...(o.header === undefined ? {} : { header: row(o.header as unknown[]) }), + ...(o.headerHeight === undefined ? {} : { headerHeight: o.headerHeight as number }), + rows: (o.rows as unknown[][]).map(row), + ...(o.rowHeights === undefined + ? {} + : { rowHeights: [...(o.rowHeights as (number | null)[])] }), + }; + } + /** * Draws a leader on the current layer: the note `text`, one line or a list of lines from the * top, joined by a shaft to each point `options.to` names. The shafts meet at `options.at`, @@ -6092,6 +6389,7 @@ export class DrawingBuilder< ? { dimensionStyles: [...this.#dimensionStyles.values()] } : {}), ...(this.#leaderStyles.size > 0 ? { leaderStyles: [...this.#leaderStyles.values()] } : {}), + ...(this.#tableStyles.size > 0 ? { tableStyles: [...this.#tableStyles.values()] } : {}), ...(this.#patterns.size > 0 ? { patterns: [...this.#patterns.values()].map(([pattern]) => pattern) } : {}), diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index fa11f62..43008da 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -48,6 +48,10 @@ import type { Insert, Layout, Leader, + ParagraphAlign, + ParagraphVerticalAlign, + Table, + TableStyle, LeaderStyle, Linetype, LinetypeMark, @@ -61,6 +65,7 @@ import type { } from "./drawing.ts"; import { isFitSpline } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; +import { drawingTables } from "./table-pictures.ts"; import { clamped, fitSpline } from "./curves.ts"; import { nearestColorIndex } from "./svg.ts"; import { @@ -97,6 +102,21 @@ import { writtenImagePath, type ImageDefinition, } from "./images.ts"; +import { + cellStyleOf, + gridCells, + STANDARD_TABLE_STYLE_SIZES, + TABLE_ROW_KINDS, + TABLE_STYLE_DICTIONARY, + tableMargins, + tablePictureHandle, + tableRows, + tableStyleDictionaryHandle, + validTableStyleHandle, + type GridCell, + type TablePicture, + type TablePlace, +} from "./tables.ts"; import { isUnits } from "./units.ts"; import { checksLimit, DrawingError } from "./lint.ts"; import { @@ -217,6 +237,8 @@ export function toDXFR2018( drawing.dimensionStyles, drawing.leaderStyles, checksLimit(drawing), + undefined, + drawing.tableStyles, ); const [left, bottom, right, top] = extentsOf(drawing.entities, boxOf, "model space"); // Each layout is boxed once, after model space, as `lint` boxes them. @@ -232,6 +254,7 @@ export function toDXFR2018( // Keyed as style names are compared, so a leader that names `notes` takes the style `NOTES`. const leaderStylesByKey = new Map(leaderStyles.map((style) => [layerKey(style.name), style])); const leaderArrowheads = leaderArrowheadsWithBlocks(leaderStyles); + const tableStyles = drawing.tableStyles ?? []; // Each file the images show is one definition, and each image has a reactor of its own. const images = [...drawingImages(drawing)]; const definitions = imageDefinitions(images); @@ -274,6 +297,20 @@ export function toDXFR2018( entity: true, }); } + const tableCount = [drawing.entities, ...sheets.map((sheet) => sheet.layout.entities)] + .flat() + .filter((e) => e.kind === "table").length; + // A table and its style are objects of classes too. + if (tableStyles.length > 0) { + writeClass(g, "TABLESTYLE", "AcDbTableStyle", "ObjectDBX Classes", 4095, { + count: tableStyles.length + 1, + entity: false, + }); + writeClass(g, "ACAD_TABLE", "AcDbTable", "ObjectDBX Classes", 1025, { + count: tableCount, + entity: true, + }); + } const wipeouts = wipeoutCount(drawing); if (wipeouts > 0) { writeClass(g, "WIPEOUT", "AcDbWipeout", WIPEOUT_APPLICATION, 2175, { @@ -536,6 +573,20 @@ export function toDXFR2018( }); }); }); + // The block of each table's picture, by the table's space and place, as a dimension's. + const tableBlocks = new Map(); + /** The handles of the tables that name each style, which the style lists as its reactors. */ + const tablesOfStyle = new Map(); + for (const drawn of drawingTables(drawing, boxOf)) { + tableBlocks.set(`${drawn.space}/${drawn.index}`, { + name: drawn.name, + picture: drawn.picture, + place: drawn.place, + style: drawn.style, + layer: drawn.table.layer, + rotation: drawn.table.rotation, + }); + } const blockRecordFields = (g: Group) => { g(280, 1); // explodable g(281, 0); // scale uniformly: no @@ -603,10 +654,36 @@ export function toDXFR2018( handle: handles.record, fields: blockRecordFields, })), + ...[...tableBlocks.values()].map(({ name, place }) => ({ + type: "BLOCK_RECORD", + subclass: "AcDbBlockTableRecord", + name, + handle: tablePictureHandle(place, "record"), + fields: blockRecordFields, + })), ]); g(0, "ENDSEC"); const blocksByName = blocksByKey(blocks); + /** The handle each table was written with. */ + const tableHandles = new Map(); + /** Writes a table entity, which a style the drawing does not have leaves out. */ + const writeTableEntity = ( + table: Table, + handle: string, + owner: string, + paper: boolean, + space: number | undefined, + index: number, + ): void => { + const held = space === undefined ? undefined : tableBlocks.get(`${space}/${index}`); + if (held === undefined) return; + tableHandles.set(held, handle); + writeTableGroups(g, table, held, { handle, owner, paper }, (name) => { + const block = blocksByName.get(layerKey(name)); + return block === undefined ? undefined : blockHandles(block.name).record; + }); + }; /** * Writes the entities of model space, of a block or of a layout, each owned by `owner`. * `paper` marks the entities of a layout as being in paper space. @@ -648,6 +725,10 @@ export function toDXFR2018( }); return; } + if (entity.kind === "table") { + writeTableEntity(entity, own, owner, paper, space, index); + return; + } if (isDimension(entity)) { const picture = space === undefined ? undefined : pictures.get(`${space}/${index}`); writeDimension( @@ -813,6 +894,9 @@ export function toDXFR2018( }); } for (const picture of pictures.values()) writePicture(g, picture); + for (const held of tableBlocks.values()) { + writeTablePicture(g, held, styleOf, (name) => blocksByName.get(layerKey(name))?.name); + } g(0, "ENDSEC"); g(0, "SECTION"); @@ -847,6 +931,11 @@ export function toDXFR2018( } g(3, "ACAD_PLOTSTYLENAME"); g(350, plotStyleDictionary); + const tableDictionary = tableStyleDictionaryHandle(); + if (tableStyles.length > 0) { + g(3, TABLE_STYLE_DICTIONARY); + g(350, tableDictionary); + } if (wipeouts > 0) { g(3, "ACAD_WIPEOUT_VARS"); g(350, wipeoutVariablesHandle()); @@ -891,6 +980,35 @@ export function toDXFR2018( writeLeaderStyle(g, style, leaderDictionary, textStyle, linetypeByBlock, content); } } + if (tableStyles.length > 0) { + // Each table names its style's handle, and the style lists the tables that name it, through + // which the leading CAD app draws each table again when the style changes. + for (const held of tableBlocks.values()) { + const key = layerKey(held.style.name); + const list = tablesOfStyle.get(key) ?? []; + const written = tableHandles.get(held); + if (written !== undefined) list.push(written); + tablesOfStyle.set(key, list); + } + const styles = [STANDARD_TABLE_STYLE_SIZES, ...tableStyles]; + g(0, "DICTIONARY"); + ownedBy(g, tableDictionary, rootDictionary); + g(100, "AcDbDictionary"); + g(281, 1); + for (const style of styles) { + g(3, dxfOnce(style.name)); + g(350, validTableStyleHandle(style.name)); + } + for (const style of styles) { + writeTableStyle( + g, + style, + validTableStyleHandle(style.name), + tableDictionary, + tablesOfStyle.get(layerKey(style.name)) ?? [], + ); + } + } if (images.length > 0) { writeImageObjects(g, definitions, reactors, rootDictionary, drawing); } @@ -1354,7 +1472,7 @@ const TEXT_VALIGN_OF = { top: "top", middle: "middle", bottom: "bottom" } as con */ function writeEntity( g: Group, - e: Exclude, + e: Exclude, handle: string, owner: string, style: TextStyle | undefined, @@ -2806,3 +2924,284 @@ function writeArrowheadStroke( g(42, stroke.bulges[i]!); }); } + +/** Group 170's code of each place in a cell: 1 to 3 along the top, 4 to 6 the middle, 7 to 9 the bottom. */ +function cellAlignment(align: ParagraphAlign, valign: ParagraphVerticalAlign): number { + return paragraphAttachment({ align, valign }); +} + +/** Writes a table style as the leading CAD app saves one: its margins, then a cell style for each kind of row. */ +function writeTableStyle( + g: Group, + style: TableStyle, + handle: string, + owner: string, + tables: readonly string[], +): void { + g(0, "TABLESTYLE"); + g(5, handle); + g(102, "{ACAD_REACTORS"); + g(330, owner); + for (const table of tables) g(330, table); + g(102, "}"); + g(330, owner); + g(100, "AcDbTableStyle"); + g(280, 0); // the version of its data + g(3, dxfOnce(style.name)); + g(70, 0); // its rows run down + g(71, 0); + const [horizontal, vertical] = tableMargins(style); + g(40, horizontal); + g(41, vertical); + g(280, 0); // its title is shown + g(281, 0); // its header is shown + for (const kind of TABLE_ROW_KINDS) { + const cell = cellStyleOf(style, kind); + g(7, dxfOnce(cell.textStyle ?? STANDARD_TEXT_STYLE)); + g(140, cell.textHeight); + g(170, cellAlignment(cell.align, cell.valign)); + g(62, cell.color ?? 0); // by block + g(63, cell.fill ?? 7); + g(283, cell.fill === undefined ? 0 : 1); + g(90, 512); // its data are of no one kind + g(91, 0); + g(1, ""); + const weight = cell.lineweight === undefined ? -2 : lineweightCode(cell.lineweight); + // Each of its six borders: its lineweight, whether it shows and its color. + for (let border = 0; border < 6; border++) { + g(274 + border, weight); + g(284 + border, 1); + g(64 + border, 0); + } + } +} + +/** A table's picture and what the writer needs to write it. */ +interface TableBlockHeld { + /** The block's name, `*T` and a number. */ + readonly name: string; + readonly picture: TablePicture; + readonly place: TablePlace; + readonly style: TableStyle; + readonly layer: string; + /** The table's rotation, which the block holds its picture turned by. */ + readonly rotation: number | undefined; +} + +/** Writes the block of a table's picture: its fills, its lines, then each cell's text and block. */ +function writeTablePicture( + g: Group, + { name, picture, place, layer, rotation }: TableBlockHeld, + styleOf: (name: string | undefined) => TextStyle | undefined, + blockName: (name: string) => string | undefined, +): void { + const record = tablePictureHandle(place, "record"); + writeBlock( + g, + tablePictureHandle(place, "begin"), + tablePictureHandle(place, "end"), + name, + record, + { + paper: false, + anonymous: true, + contents: () => { + const begin = ( + type: string, + part: string, + subclass: string, + o: { readonly lineweight?: number; readonly color?: number | undefined } = {}, + ) => { + g(0, type); + g(5, tablePictureHandle(place, part)); + g(330, record); + g(100, "AcDbEntity"); + g(8, layer); + g(6, "ByBlock"); + g(62, o.color ?? 0); + if (o.lineweight !== undefined) g(370, o.lineweight); + g(100, subclass); + }; + // The block holds the picture turned as the table is, and its insert is not turned. + const [cos, sin] = paragraphDirection(rotation); + const turned = (x: number, y: number): [number, number] => + cos === 1 && sin === 0 ? [x, y] : [x * cos - y * sin, x * sin + y * cos]; + const at = (code: number, x: number, y: number) => point(g, code, ...turned(x, y)); + for (const fill of picture.fills) { + const [x0, y0, x1, y1] = fill.box; + begin("SOLID", `fill-${fill.row}-${fill.column}`, "AcDbTrace", { color: fill.color }); + // Its corners as the leading CAD app holds them: the left side down, then the right. + at(10, x0, y1); + at(11, x0, y0); + at(12, x1, y1); + at(13, x1, y0); + } + picture.lines.forEach((line, i) => { + begin("LINE", `line-${i}`, "AcDbLine", { + lineweight: line.lineweight === undefined ? -2 : lineweightCode(line.lineweight), + }); + at(10, ...line.from); + at(11, ...line.to); + }); + for (const text of picture.texts) { + begin("MTEXT", `text-${text.row}-${text.column}`, "AcDbMText", { color: text.color }); + at(10, ...text.at); + g(40, text.height); + g(41, text.width); + g(46, 0); + g(71, paragraphAttachment(text)); + g(72, 1); + writeMtextValue(g, text.value); + g(7, styleOf(text.textStyle)?.name ?? STANDARD_TEXT_STYLE); + if (cos !== 1 || sin !== 0) { + g(11, fifteenDigits(cos)); + g(21, fifteenDigits(sin)); + g(31, 0); + } + g(73, 1); + g(44, 1); + } + for (const block of picture.blocks) { + const named = blockName(block.block); + if (named === undefined) continue; + begin("INSERT", `block-${block.row}-${block.column}`, "AcDbBlockReference"); + g(2, named); + at(10, ...block.at); + g(41, block.scale); + g(42, block.scale); + g(43, block.scale); + if (rotation !== undefined && rotation !== 0) g(50, writtenAngle(rotation)); + } + }, + }, + ); +} + +/** Writes a table: the insert of its picture's block, then its rows, its columns and each cell. */ +function writeTableGroups( + g: Group, + table: Table, + held: TableBlockHeld, + own: { readonly handle: string; readonly owner: string; readonly paper: boolean }, + blockRecord: (name: string) => string | undefined, +): void { + g(0, "ACAD_TABLE"); + g(5, own.handle); + g(330, own.owner); + g(100, "AcDbEntity"); + if (own.paper) g(67, 1); + g(8, table.layer); + g(100, "AcDbBlockReference"); + g(2, held.name); + point(g, 10, ...table.at); + g(100, "AcDbTable"); + g(280, 0); + g(342, validTableStyleHandle(held.style.name)); + g(343, tablePictureHandle(held.place, "record")); + const [cos, sin] = paragraphDirection(table.rotation); + g(11, cos === 1 ? 1 : fifteenDigits(cos)); + g(21, sin === 0 ? 0 : fifteenDigits(sin)); + g(31, 0); + g(90, 22); + const picture = held.picture; + g(91, picture.rows.length); + g(92, picture.columns.length); + g(93, 0); + g(94, 0); + g(95, 0); + g(96, 0); + // Without a title or a header, the table says so, since its style shows both. + if (table.title === undefined) g(280, 1); + if (table.header === undefined) g(281, 1); + for (const height of picture.rows) g(141, height); + for (const width of picture.columns) g(142, width); + const rows = tableRows(table); + const starts = new Map(); + for (const cell of gridCells(table)) starts.set(`${cell.row}/${cell.column}`, cell); + rows.forEach(({ cells }, r) => { + cells.forEach((_, c) => { + const cell = starts.get(`${r}/${c}`); + const content = cell?.content ?? {}; + const block = content.block === undefined ? undefined : blockRecord(content.block); + g(171, block === undefined ? 1 : 2); + g(172, 0); + g(173, cell === undefined ? 1 : 0); // merged into another + g(174, block !== undefined && content.blockScale === undefined ? 1 : 0); // fit to the cell + g(175, cell?.columns ?? 1); + g(176, cell?.rows ?? 1); + let flags = 0; + const overrides: [number, number | string][] = []; + if (content.align !== undefined || content.valign !== undefined) { + const own = cellStyleOf(held.style, rows[r]!.kind); + flags |= CELL_ALIGNMENT; + overrides.push([ + 170, + cellAlignment(content.align ?? own.align, content.valign ?? own.valign), + ]); + } + if (content.fill !== undefined) { + flags |= CELL_FILL; + // A cell's 283 says it has no fill, where a cell style's says it has one. + overrides.push([63, content.fill], [283, 0]); + } + if (content.color !== undefined) { + flags |= CELL_COLOR; + overrides.push([64, content.color]); + } + if (content.textHeight !== undefined) { + flags |= CELL_TEXT_HEIGHT; + overrides.push([140, content.textHeight]); + } + g(91, flags); + g(178, 0); + g(145, 0); + if (block !== undefined) { + g(340, block); + g(144, content.blockScale ?? 1); + g(179, 0); + } + for (const [code, value] of overrides) g(code, value); + g(92, 0); + g(301, "CELL_VALUE"); + const text = block === undefined ? content.text : undefined; + if (text === undefined || text === "") { + g(93, block === undefined ? 3 : 1); + g(90, block === undefined ? 0 : 4); + g(94, 0); + g(300, ""); + g(302, ""); + } else { + g(93, 4); + g(90, 4); // a string + writeCellText(g, 1, 2, text); + g(94, 0); + g(300, ""); + writeCellText(g, 302, 303, text); + } + g(304, "ACVALUE_END"); + }); + }); +} + +/** The bits of a cell's group 91 that say which of its style's fields it changes. */ +const CELL_ALIGNMENT = 0x1; +/** A fill of its own: its color, 0x4, and whether it has one, 0x2. */ +const CELL_FILL = 0x6; +const CELL_COLOR = 0x8; +const CELL_TEXT_HEIGHT = 0x20; + +/** + * Writes a cell's text as an MTEXT's is written, its carets and tabs escaped: whole in `last` up + * to 250 characters, and in pieces of 250 in `more` before it past that, a caret kept with what it + * escapes. + */ +function writeCellText(g: Group, last: number, more: number, value: string): void { + const text = dxfOnce(value).replaceAll("\t", "^I"); + let at = 0; + while (text.length - at > TEXT_CHUNK) { + const end = text[at + TEXT_CHUNK - 1] === "^" ? at + TEXT_CHUNK - 1 : at + TEXT_CHUNK; + g(more, text.slice(at, end)); + at = end; + } + g(last, text.slice(at)); +} diff --git a/src/extents.ts b/src/extents.ts index d41abf5..2c5000c 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -27,6 +27,8 @@ import type { Entity, Insert, Leader, + Table, + TableStyle, LeaderStyle, Point, Polyline, @@ -37,6 +39,7 @@ import type { import { layerKey, layerKeys } from "./layers.ts"; import { hasArcsOrWidths, mayCurve, polylineBox, PolylineMemo } from "./polylines.ts"; import { leaderPicture, leaderRepeats } from "./leaders.ts"; +import { tableCost, tableBox, tableMeasures, tablePicture } from "./tables.ts"; import { inStyle, measurer } from "./measure.ts"; import { layoutDimensionText, @@ -45,12 +48,19 @@ import { paragraphMeasurer, placer, } from "./paragraphs.ts"; +import { tableProblem } from "./rules.ts"; import { filled } from "./shape.ts"; import { ellipseBox, splineBox } from "./curves.ts"; import { drawnEllipse, SplineMemo } from "./rules.ts"; type Bounds = [number, number, number, number]; +/** A boxer of a drawing's blocks, with the box of each block it has boxed by its key. */ +interface BlockBoxer { + readonly box: Boxer; + readonly known: Map; +} + const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0]; /** @@ -110,6 +120,7 @@ export function extents( dimensionStyles: readonly DimensionStyle[] = [], leaderStyles: readonly LeaderStyle[] = [], most = MAX_WORK, + tableStyles: readonly TableStyle[] = [], ): [number, number, number, number] { const boxOf = boxer( textStyles, @@ -120,6 +131,8 @@ export function extents( dimensionStyles, leaderStyles, most, + most, + tableStyles, ); const box = boxOf(entities); const at = boxOf.capped; @@ -221,6 +234,7 @@ export function boxer( leaderStyles: readonly LeaderStyle[] = [], most = MAX_WORK, walking = most, + tableStyles: readonly TableStyle[] = [], ): Boxer { const key = layerKeys(); const { measure, again: readAgain } = measurer(); @@ -229,21 +243,40 @@ export function boxer( readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; readonly leaderStyles: ReadonlyMap; + readonly tableStyles: ReadonlyMap; + /** The lists it was made from, for boxing a table's blocks as the writers do. */ + readonly lists: { + readonly textStyles: readonly TextStyle[] | undefined; + readonly blocks: readonly Block[] | undefined; + readonly dimensionStyles: readonly DimensionStyle[] | undefined; + readonly leaderStyles: readonly LeaderStyle[] | undefined; + }; /** The blocks a leader's content names. */ readonly blocks: ReadonlyMap; + /** The drawings its xrefs stand for, which a table's cell's block may insert. */ + readonly xrefs: ReadonlyMap | undefined; } const namesOf = ( text: readonly TextStyle[] | undefined, dimensions: readonly DimensionStyle[] | undefined, leaders: readonly LeaderStyle[] | undefined, blocks: readonly Block[] | undefined, + tables: readonly TableStyle[] | undefined, + attached: ReadonlyMap | undefined, ): Names => ({ + xrefs: attached, + lists: { textStyles: text, blocks, dimensionStyles: dimensions, leaderStyles: leaders }, + tableStyles: new Map( + filled(tables) + .filter((style) => typeof (style as { name?: unknown } | null)?.name === "string") + .map((style) => [layerKey(style.name), style]), + ), textStyles: new Map(filled(text).map((t) => [layerKey(t.name), t])), dimensionStyles: new Map(filled(dimensions).map((style) => [layerKey(style.name), style])), leaderStyles: new Map(filled(leaders).map((style) => [layerKey(style.name), style])), blocks: new Map(filled(blocks).map((block) => [layerKey(block.name), block])), }); - const own = namesOf(textStyles, dimensionStyles, leaderStyles, blocks); + const own = namesOf(textStyles, dimensionStyles, leaderStyles, blocks, tableStyles, xrefs); // The names of each referenced drawing, worked out when one of its entities is first met. const referenced = new Map(); const byDrawing = new Map(); @@ -252,9 +285,10 @@ export function boxer( let found = referenced.get(from); if (!found) { found = byDrawing.get(from.drawing); - if (!found) { - const { textStyles, dimensionStyles, leaderStyles, blocks } = from.drawing; - found = namesOf(textStyles, dimensionStyles, leaderStyles, blocks); + // A drawing given with other attachments has names of its own, for its tables' blocks. + if (!found || found.xrefs !== from.xrefs) { + const { textStyles, dimensionStyles, leaderStyles, blocks, tableStyles } = from.drawing; + found = namesOf(textStyles, dimensionStyles, leaderStyles, blocks, tableStyles, from.xrefs); byDrawing.set(from.drawing, found); } referenced.set(from, found); @@ -368,6 +402,13 @@ export function boxer( case "ordinate-dimension": dimension(e, from, add); break; + case "table": { + const box = tableOf(e, from); + if (box === undefined) break; + add(box[0], box[1]); + add(box[2], box[3]); + break; + } case "leader": { const box = leaderBox(e, from); if (box[0] === Infinity) break; @@ -534,6 +575,76 @@ export function boxer( if (mask) for (const corner of paragraphMaskCorners(text, layout, mask)) add(...corner); } }; + /** The box of each table, worked out once for each drawing's names. */ + const tables = new WeakMap>(); + /** A boxer of each drawing's blocks that hides nothing, as the writers box a cell's block. */ + const plainBoxers = new Map(); + /** The same with the drawing's xrefs, for what a cell's block draws through one of them. */ + const attachedBoxers = new Map(); + /** Boxes a block at an insert of it at the origin, once for each name, with one boxer per names. */ + const blockBoxBy = ( + boxers: Map, + from: Names, + attached: ReadonlyMap | undefined, + name: string, + ): Bounds | undefined => { + let held = boxers.get(from); + if (!held) { + const { textStyles, blocks, dimensionStyles, leaderStyles } = from.lists; + held = { + box: boxer( + textStyles, + blocks, + undefined, + undefined, + attached, + dimensionStyles, + leaderStyles, + most, + walking, + ), + known: new Map(), + }; + boxers.set(from, held); + } + const k = key(name); + if (held.known.has(k)) return held.known.get(k); + const found = held.box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); + if (held.box.capped) stop(); + held.known.set(k, found); + return found; + }; + const tableOf = (e: Table, from: Names) => { + let byNames = tables.get(e); + if (!byNames) tables.set(e, (byNames = new Map())); + if (byNames.has(from)) return byNames.get(from); + byNames.set(from, undefined); + // Its cells are paid for before they are read, a unit each and one for each 32 characters. + if (typeof e.style !== "string" || !spend(tableCost(e))) return undefined; + const style = from.tableStyles.get(key(e.style)); + // A table or a style the rules refuse draws nothing, and is not read. + if (style === undefined || tableProblem(e) !== undefined) return undefined; + const styleOf = (name: string | undefined) => + name === undefined ? undefined : from.textStyles.get(key(name)); + const picture = tablePicture( + e, + style, + tableMeasures(styleOf, (name) => blockBoxBy(plainBoxers, from, undefined, name)), + ); + // Its box, worked out once however many places draw it, its cells' blocks in it. A block is + // fitted as the writers fit it, which know no xrefs, and draws what its xrefs hold too. + const attached = from.xrefs; + const box = tableBox( + e, + picture, + styleOf, + attached && attached.size > 0 + ? (name) => blockBoxBy(attachedBoxers, from, attached, name) + : undefined, + ); + byNames.set(from, box); + return box; + }; /** * The box of what a leader draws, worked out once for each drawing: its shafts, its * arrowheads, its landing, and each line of its note as any text is boxed. diff --git a/src/index.ts b/src/index.ts index 02c3bda..7f3cba9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -119,6 +119,12 @@ export { type LeaderOptions, type LeaderSide, type LeaderStyle, + type Table, + type TableCell, + type TableCellContent, + type TableCellStyle, + type TableOptions, + type TableStyle, type LeaderStyleDefinition, type LeaderTargets, type Line, @@ -307,6 +313,7 @@ export { export { attachmentPlace, layoutDimensionText, + layoutCellText, layoutParagraph, measureDimensionText, lineSpacingStyleCode, @@ -316,6 +323,7 @@ export { paragraphDirection, paragraphGutter, paragraphInStyle, + placer, type ParagraphColumns, type ParagraphColumnsHeld, type ParagraphLayout, @@ -482,6 +490,10 @@ export { type ReadPolyline, type ReadSolid, type ReadSpace, + type ReadTable, + type ReadTableCell, + type ReadTableCellStyle, + type ReadTableStyle, type ReadText, type ReadTextPlacement, type ReadTextStyle, @@ -492,3 +504,32 @@ export { type ReadXref, } from "./read/model.ts"; export { toSVG, type SvgOptions } from "./svg.ts"; + +export { + cellStyleOf, + gridCells, + measureTable, + STANDARD_TABLE_STYLE, + STANDARD_TABLE_STYLE_SIZES, + TABLE_ROW_KINDS, + TABLE_STYLE_DICTIONARY, + tableMargins, + tableBox, + tableInserts, + tableMatrix, + tableMeasures, + tableParagraph, + tablePicture, + tablePictureHandle, + tableRows, + tableStyleDictionaryHandle, + validTableStyleHandle, + type CellStyleHeld, + type GridCell, + type TableMeasure, + type TableMeasures, + type TablePicture, + type TablePlace, + type TableRowKind, +} from "./tables.ts"; +export { drawingTables, type DrawnTable } from "./table-pictures.ts"; diff --git a/src/inspect.ts b/src/inspect.ts index 2ea2526..980484c 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -14,6 +14,14 @@ import { import { callOf, type CallSite } from "./callsite.ts"; import { dimensionPicture, pictureTexts, isDimension } from "./dimensions.ts"; import { leaderPicture, leaderRepeats } from "./leaders.ts"; +import { boxer, type Boxer } from "./extents.ts"; +import { + tableCost, + tableMeasures, + tableParagraph, + tablePicture, + type TablePicture, +} from "./tables.ts"; import type { Block, Drawing, @@ -23,6 +31,7 @@ import type { LeaderStyle, Paragraph, Point, + Table, TextStyle, } from "./drawing.ts"; import { written } from "./format.ts"; @@ -35,7 +44,7 @@ import { paragraphMeasurer, } from "./paragraphs.ts"; import { paperInfo } from "./papers.ts"; -import { shown } from "./rules.ts"; +import { shown, tableProblem } from "./rules.ts"; import { filled, Strings } from "./shape.ts"; import { visibility } from "./svg.ts"; @@ -243,6 +252,63 @@ export function inspectWithin( Leader, { style: LeaderStyle; textStyle: TextStyle | undefined; texts: Paragraph[]; cost: number } >(); + /** The box of each block a table's cell holds, by its drawing, boxed once for the call. */ + const blockBoxes = new Map< + Drawing, + { + readonly box: Boxer; + readonly known: Map; + } + >(); + const blockBoxOf = ( + of: Drawing, + name: string, + ): readonly [number, number, number, number] | undefined => { + let held = blockBoxes.get(of); + if (!held) { + held = { + box: boxer( + of.textStyles, + of.blocks, + undefined, + undefined, + undefined, + of.dimensionStyles, + of.leaderStyles, + ), + known: new Map(), + }; + blockBoxes.set(of, held); + } + const k = key(name); + if (held.known.has(k)) return held.known.get(k); + const found = held.box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); + held.known.set(k, found); + return found; + }; + /** The picture of each table, worked out once, with each cell paid for as it is read. */ + const tablePictures = new WeakMap(); + const tableOf = (table: Table, from: Referenced | undefined): TablePicture | undefined => { + if (tablePictures.has(table)) return tablePictures.get(table); + tablePictures.set(table, undefined); + // Its cells are paid for before they are read. A table or a style the rules refuse draws + // nothing, and is not read. + if (typeof table.style !== "string" || !walk(tableCost(table))) return undefined; + const tables = tablesOf(from); + const style = tables.tableStyles.get(key(table.style)); + if (style === undefined || tableProblem(table) !== undefined) return undefined; + const drawingOf = from?.drawing ?? drawing; + const picture = tablePicture( + table, + style, + tableMeasures( + (name) => (name === undefined ? undefined : tables.textStyles.get(key(name))), + (name) => blockBoxOf(drawingOf, name), + ), + ); + tablePictures.set(table, picture); + return picture; + }; /** A leader's note, as the paragraph it is laid out as, where its picture holds it. */ const noteOf = (leader: Leader, style: LeaderStyle, textStyle: TextStyle | undefined) => { const known = notes.get(leader); @@ -284,6 +350,14 @@ export function inspectWithin( for (const text of note.texts) keep(text, index, matrix, from, attribute); return; } + if (drawn.kind === "table") { + // Each cell's text is a paragraph where the table's picture puts it. + const picture = tableOf(drawn, from); + if (picture === undefined) return; + for (const text of picture.texts) + keep(tableParagraph(drawn, text), index, matrix, from, attribute); + return; + } if (isDimension(drawn)) { // A dimension's text is a text where its picture puts it. const style = tablesOf(from).dimensionStyles.get(key(drawn.style)); @@ -391,6 +465,7 @@ export function inspectWithin( ? !blank(e.value) : isDimension(e) || e.kind === "leader" || + e.kind === "table" || (e.kind === "polyline" && e.closed && Array.isArray(e.points) && e.points.length > 2); const where = layout === undefined ? "model space" : `layout ${shown(layout)}`; filled(entities).forEach((entity, index) => { diff --git a/src/lint.ts b/src/lint.ts index 9db0c4b..a7bc00b 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -45,6 +45,8 @@ import type { Layer, Leader, LeaderStyle, + Table, + TableStyle, Linetype, PatternLine, Point, @@ -85,6 +87,17 @@ import { } from "./shape.ts"; import { layerAuditKey, layerKey, layoutNameKey } from "./layers.ts"; import { STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; +import { + STANDARD_TABLE_STYLE, + tableCost, + tableMargins, + tableMeasures, + tablePicture, + tableRepeats, + tableTexts, + tableStyleDictionaryHandle, + validTableStyleHandle, +} from "./tables.ts"; import { parseParagraph, type ParsedParagraph } from "./paragraph-codes.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; import { @@ -128,6 +141,15 @@ import { leaderStyleNameProblem, leaderStyleProblem, leaderStyleTwinProblem, + isStandardTableStyle, + standardTableStyleProblem, + TABLE_IN_BLOCK, + tableColumnsProblem, + tableTextsProblem, + tableProblem, + tableStyleNameProblem, + tableStyleProblem, + tableStyleTwinProblem, leaderBlockContentProblem, leaderTextProblem, layerColorProblem, @@ -256,6 +278,10 @@ export type LintRule = | "duplicate-leader-style" | "undefined-leader-style" | "leader" + | "table-style" + | "duplicate-table-style" + | "undefined-table-style" + | "table" | "paragraph" | "image" | "hatch" @@ -314,6 +340,8 @@ export interface Diagnostic { readonly dimensionStyle?: string; /** The leader style the problem is in, when it is a problem with its definition. */ readonly leaderStyle?: string; + /** The table style the problem is in, when it is a problem with its definition. */ + readonly tableStyle?: string; /** * The block the problem is in: a problem with the block's definition, with one of its * attribute definitions, or with one of its entities. @@ -613,6 +641,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) long1(d.align) + long1(d.valign); const leaderAgain = leaderRepeats(); + const tableAgain = tableRepeats(); /** What is wrong with a dimension's own text, worked out once for a long one. */ const dimensionTexts = new Strings(); const checkDimensionText = (text: unknown): string | undefined => { @@ -747,6 +776,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) | "layouts" | "dimensionStyles" | "leaderStyles" + | "tableStyles" | "patterns", rule: LintRule, ): readonly T[] => { @@ -1427,6 +1457,165 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (!problem && lettered) leaderStyles.set(key, style); }, ); + // Table style names are compared as leader style names are, and only a style with nothing wrong + // with it is drawn with. + const tableStyleNames = new Set(); + const tableStyles = new Map(); + const tableStylesAudited = new Map(); + each( + listed("tableStyles", "table-style"), + "tableStyles", + "table-style", + TYPED.tableStyle, + (style, i) => { + if (malformed(WALKABLE.tableStyle, style, `tableStyles[${i}]`, "table-style")) return; + const error = (rule: LintRule, message: string) => + out.push({ + rule, + severity: "error", + message: `Table style ${shown(style.name)}: ${message}`, + ...(typeof style.name === "string" ? { tableStyle: style.name } : {}), + }); + if (r12) { + error("table-style", R12_ONLY.tables); + return; + } + const problem = tableStyleProblem(style); + if (problem) error("table-style", problem); + const name: unknown = style.name; + if (tableStyleNameProblem(name) || isStandardTableStyle(name as string)) return; + const auditKey = layerAuditKey(style.name); + const first = tableStylesAudited.get(auditKey); + if (first !== undefined) { + error("duplicate-table-style", tableStyleTwinProblem(style.name, first)!); + return; + } + if (tableStylesAudited.size === 0) { + for (const [handle, what] of [ + [validTableStyleHandle(STANDARD_TABLE_STYLE), 'the table style "Standard"'], + [tableStyleDictionaryHandle(), "the dictionary of table styles"], + ] as const) { + const taken = claim(handle, what); + if (taken) error("id-handle", taken); + } + } + tableStylesAudited.set(auditKey, style.name); + const key = layerKey(style.name); + tableStyleNames.add(key); + let lettered = true; + for (const textStyle of [ + style.textStyle, + style.title?.textStyle, + style.header?.textStyle, + style.data?.textStyle, + ] as unknown[]) { + if ( + typeof textStyle !== "string" || + textStyleNameProblem(textStyle) || + isStandardTextStyle(textStyle) + ) { + continue; + } + if (!textStyles.has(layerKey(textStyle))) { + error("undefined-text-style", `Text style ${shown(textStyle)} is not defined`); + lettered = false; + } else if (unreadStyles.has(layerKey(textStyle))) lettered = false; + } + const clash = claim( + validTableStyleHandle(style.name), + `the table style ${shown(style.name)}`, + ); + if (clash) error("id-handle", clash); + if (!problem && lettered) tableStyles.set(key, style); + }, + ); + /** A boxer of the drawing's blocks that hides nothing, as the writers fit a cell's block. */ + let fitBoxer: Boxer | undefined; + const fitBoxes = new Map(); + /** Checks what a table names, and its columns, rows and cells. */ + const lintTable = ( + table: Table, + add: (rule: LintRule, severity: Diagnostic["severity"], problem: string) => void, + inBlock: boolean, + here: () => string, + ): void => { + if (inBlock) add("table", "error", TABLE_IN_BLOCK); + const name: unknown = table.style; + const nameProblem = tableStyleNameProblem(name); + if (nameProblem) add("undefined-table-style", "error", nameProblem); + else if (isStandardTableStyle(name as string)) { + add("undefined-table-style", "error", standardTableStyleProblem(name as string)!); + } else if (!tableStyleNames.has(layerKey(name as string))) { + add("undefined-table-style", "error", `Table style ${shown(name)} is not defined`); + } + const problem = tableProblem(table, (block) => blocks.has(layerKey(block))); + if (problem) add("table", "error", problem); + const style = typeof name === "string" ? tableStyles.get(layerKey(name)) : undefined; + if (!problem && style) { + const narrow = tableColumnsProblem(table.columns, tableMargins(style)[0]); + if (narrow) add("table", "error", narrow); + const fontOf = (name: string | undefined) => + name === undefined || isStandardTextStyle(name) + ? STANDARD_FONT + : stylesByKey.get(layerKey(name))?.font; + const lettered = tableTextsProblem(tableTexts(table, style), fontOf); + if (lettered) add("table", "error", lettered); + if (!narrow && !lettered) lintTableBlocks(table, style, add, here); + } + }; + /** Checks the scale each block a table's cells hold is drawn at, as the writers write it. */ + const lintTableBlocks = ( + table: Table, + style: TableStyle, + add: (rule: LintRule, severity: Diagnostic["severity"], problem: string) => void, + here: () => string, + ): void => { + const holds = table.rows.some((row) => row.some((cell) => isObject(cell) && cell.block)); + if (!holds || !spend(tableCost(table), here)) return; + const styleOf = (name: string | undefined) => + name === undefined ? undefined : stylesByKey.get(layerKey(name)); + let capped = false; + const picture = tablePicture( + table, + style, + tableMeasures(styleOf, (name) => { + const k = layerKey(name); + if (fitBoxes.has(k)) return fitBoxes.get(k); + fitBoxer ??= boxer( + [...stylesByKey.values()], + [...blocks.values()], + undefined, + undefined, + undefined, + [...dimensionStyles.values()], + [...leaderStyles.values()], + most, + most, + ); + const before = fitBoxer.spent; + let found: readonly [number, number, number, number] | undefined; + try { + found = fitBoxer([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); + } catch { + found = undefined; + } + if (fitBoxer.capped || !spend(fitBoxer.spent - before, here)) capped = true; + fitBoxes.set(k, found); + return found; + }), + ); + if (capped) return; + for (const placed of picture.blocks) { + const problem = scaleProblem(placed.scale); + if (problem === undefined) continue; + add( + "table", + "error", + `The block ${shown(placed.block)} in row ${placed.row}, column ${placed.column} of its grid is drawn at a scale of ${placed.scale}. ${problem}`, + ); + return; + } + }; /** The tags of each block a leader holds in place of its note, worked out once. */ const tagsOf = new WeakMap>(); /** Checks what a leader names, its note and its shafts. `sound` is false for one no rule can read. */ @@ -1964,7 +2153,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (isObject(entity) && !boxable) boxable = costsBoxes(entity); // So are a leader that shares its shafts or its note with another and a long string. const shared = isObject(entity) - ? (entity.kind === "leader" ? leaderAgain(entity) : 0) + repeatedIn(entity) + ? (entity.kind === "leader" + ? leaderAgain(entity) + : entity.kind === "table" + ? tableAgain(entity) + : 0) + repeatedIn(entity) : 0; if (shared > 0 && !spend(shared, here)) return; if (metUnsound(WALKABLE.entity, entity) || !isSound(WALKABLE.entity, entity)) { @@ -2122,6 +2315,14 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (problems.length === 0) lintLeader(entity, add, block !== undefined); return; } + if (entity.kind === "table") { + if (r12) { + add("table", "error", R12_ONLY.tables); + return; + } + if (problems.length === 0) lintTable(entity, add, block !== undefined, here); + return; + } if (entity.kind === "image") { if (r12) { add("image", "error", R12_ONLY.images); @@ -2276,6 +2477,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) most - work, // The writer's walks have the whole limit, and so have these, so the two take one path. most, + [...tableStyles.values()], ); } catch { return modelBox; @@ -2690,6 +2892,7 @@ function costsBoxes(e: Readonly>): boolean { kind === "insert" || kind === "spline" || kind === "leader" || + kind === "table" || kind === "linear-dimension" || kind === "aligned-dimension" || kind === "radius-dimension" || diff --git a/src/paragraphs.ts b/src/paragraphs.ts index 2d76ad8..e432f41 100644 --- a/src/paragraphs.ts +++ b/src/paragraphs.ts @@ -30,7 +30,8 @@ import { Strings } from "./shape.ts"; // plus its ink, from the left of its first character's ink to the right of its last one's, come // to no more than the width and `SLACK`. In a word that holds a stack, the characters after its // last stack stand for it, or the stack where it ends the word. A line's first word stays, wider -// than the width or not. +// than the width or not, but in a table's cell, `layoutCellText`: there a word that reaches past +// the width on a line of its own breaks before each character whose ink would end past it. // - At-least spacing gives each line a slot of the factor times A + D + h/3 from its top, and the // next line its top where the slot ends. A is the most its characters' `tops` or its stacks // reach above its baseline, and at least h; D is h/3, or 0 where a stack reaches highest. Its @@ -809,6 +810,14 @@ export function layoutDimensionText(paragraph: ParagraphToMeasure): ParagraphLay return layOut({ ...settingsOf(paragraph), dimension: true }, parseParagraph(paragraph.value)); } +/** + * Lays out the text of a table's cell as `layoutParagraph` lays out a paragraph, but for a word + * wider than the width, which breaks before each character whose ink would pass it. + */ +export function layoutCellText(paragraph: ParagraphToMeasure): ParagraphLayout { + return layOut({ ...settingsOf(paragraph), cell: true }, parseParagraph(paragraph.value)); +} + /** The text of a dimension's picture where it plots, as `measureParagraph` gives a paragraph. */ export function measureDimensionText(paragraph: ParagraphToMeasure): ParagraphMeasure { return measured(paragraph, layoutDimensionText(paragraph)); @@ -834,6 +843,8 @@ interface Settings { * and below where a stack sets its lowest part, and not at a stacked part's ink. */ readonly dimension?: boolean; + /** True for the text of a table's cell, whose words wider than the width break. */ + readonly cell?: boolean; } /** A paragraph's columns, read: how many at most, the height of each, and the gutter. */ @@ -1270,6 +1281,65 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { started: false, tabbed: false, }; + /** Copies the pen into `trial`. */ + const copyPen = (): void => { + trial.x = pen.x; + trial.key = pen.key; + trial.ink = pen.ink; + trial.leaned = pen.leaned; + trial.tab = pen.tab; + trial.gap = pen.gap; + trial.started = pen.started; + trial.tabbed = pen.tabbed; + }; + /** True when the word, placed where the pen stands, reaches past the width. */ + const overflowsAlone = (): boolean => { + copyPen(); + return overflows(place(word, trial) + 2 * trial.leaned, trial); + }; + const one: Parts = { items: [], count: 1 }; + /** + * Places a word wider than the width in a cell's text a character at a time: a character whose + * ink, from the left of the box, would end past the width starts a line, as long as the line + * holds a character of the word. + */ + const breakWord = (): void => { + let held = false; + const fit = (): void => { + if (held && line.at !== undefined) { + copyPen(); + place(one, trial); + // Where its ink ends, from the left of the box. + if (line.at + trial.ink > limit + SLACK * height) { + endLine(); + restart(false); + } + } + place(one, pen, line); + held = true; + }; + for (let p = 0; p < word.count; p++) { + const part = word.items[p]!; + if (part.kind === "stack") { + one.items[0] = part; + fit(); + continue; + } + for (let k = part.from; k < part.to;) { + const code = part.source.charCodeAt(k); + const next = + code >= 0xd800 && + code <= 0xdbff && + k + 1 < part.to && + part.source.charCodeAt(k + 1) >= 0xdc00 + ? k + 2 + : k + 1; + one.items[0] = { ...part, from: k, to: next }; + fit(); + k = next; + } + } + }; const endWord = (): void => { if (word.count === 0) return; trial.x = pen.x; @@ -1286,7 +1356,8 @@ function layOut(settings: Settings, parsed: ParsedParagraph): ParagraphLayout { endLine(); restart(false); } else place(spaces, pen, line); - place(word, pen, line); + if (settings.cell && limit < Infinity && overflowsAlone()) breakWord(); + else place(word, pen, line); words++; word.count = 0; spaces.count = 0; diff --git a/src/read/check.ts b/src/read/check.ts index 0dcf32b..ad4e294 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -399,6 +399,47 @@ const ENTITY: Readonly> = { }, }, wipeout: { ...BASE, kind: { oneOf: ["wipeout"] }, points: { list: "point" } }, + table: { + ...BASE, + kind: { oneOf: ["table"] }, + "style?": "string", + at: "point", + direction: "point", + rows: { list: "number" }, + columns: { list: "number" }, + title: "boolean", + header: "boolean", + cells: { + list: { + fields: { + row: "count", + column: "count", + rowSpan: "count", + columnSpan: "count", + "text?": "string", + "block?": "string", + "blockScale?": "number", + "alignment?": "number", + "textHeight?": "number", + "color?": "number", + "fill?": "number", + }, + }, + }, + "block?": "string", + "blockHandle?": "string", + }, +}; + +const TABLE_CELL_STYLE: Type = { + fields: { + textStyle: "string", + textHeight: "number", + alignment: "number", + color: "number", + "fill?": "number", + lineweight: "number", + }, }; const SPACE: Fields = { @@ -508,6 +549,19 @@ const DRAWING_READ: Fields = { }, }, }, + tableStyles: { + list: { + fields: { + "handle?": "string", + name: "string", + horizontalMargin: "number", + verticalMargin: "number", + title: TABLE_CELL_STYLE, + header: TABLE_CELL_STYLE, + data: TABLE_CELL_STYLE, + }, + }, + }, blocks: { list: { fields: { diff --git a/src/read/dxf.ts b/src/read/dxf.ts index d174724..33f68d9 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -25,6 +25,7 @@ import { type PendingStart, } from "./entities.ts"; import { GroupReader, textTwice, unescaped } from "./groups.ts"; +import { TableGroups, tableStyleOf, type TableStyleHeld } from "./table.ts"; import { add, facing, @@ -69,6 +70,8 @@ import { type ReadLinetypeMark, type ReadMultileader, type ReadOptions, + type ReadTable, + type ReadTableStyle, type ReadTextStyle, type ReadView, type ReadViewport, @@ -183,6 +186,7 @@ const CENSUS: ReadonlySet = new Set([5, 6, 8, 60, 62, 67, 102, 330, 370, const VISIBILITY: ReadonlySet = new Set([60]); /** The kinds a block's definition reads whole, and a space's with `geometry`. */ const BLOCK_READS = new Set([ + "ACAD_TABLE", "ARC", "ATTDEF", "ATTRIB", @@ -267,7 +271,8 @@ const HOUSEKEEPING = new Set([ "RASTERVARIABLES", "SCALE", "SUN", - "TABLESTYLE", + "TABLECONTENT", + "TABLEGEOMETRY", "VISUALSTYLE", "WIPEOUTVARIABLES", "XRECORD", @@ -451,6 +456,15 @@ interface PendingLeader extends LeaderNames { readonly target?: Target; } +/** A table whose style is named by handle, until the file is read. */ +interface PendingTable { + readonly entity: ReadTable; + readonly target: Target; + readonly style: string | undefined; + readonly noTitle: boolean | undefined; + readonly noHeader: boolean | undefined; +} + /** A polyline whose vertices follow it, up to its `SEQEND`. */ interface PolylineOwner { readonly kind: "polyline"; @@ -511,6 +525,15 @@ class DxfReader { #leaderStyleDictionary: string | undefined; /** Each leader style's name, by its handle. */ readonly leaderStyles = new Map(); + /** The dictionary of table styles, which the root dictionary names, and its entries in its order. */ + #tableStyleDictionary: string | undefined; + readonly #tableStyleEntries: (readonly [name: string, handle: string])[] = []; + /** Each table style read, by its handle in capitals. */ + readonly #tableStyleObjects = new Map(); + /** The groups of the table read now, from its `AcDbTable` on, and whether they have begun. */ + #table: TableGroups | undefined; + #inTable = false; + readonly #tables: PendingTable[] = []; /** The view of the first `*Active` record of the viewport table. */ #activeView: Omit | undefined; readonly unread = { @@ -597,6 +620,8 @@ class DxfReader { group(code: number, value: string): void { if (code === 0) { this.#end(); + this.#table = undefined; + this.#inTable = false; if (value === "SECTION") this.#section = "?"; else if (value === "ENDSEC") this.#section = ""; else if (value === "EOF") this.#section = ""; @@ -619,6 +644,16 @@ class DxfReader { return; } const r = this.#rec; + // A table's own groups are read as they arrive, and its record keeps those before them. + if (r?.type === "ACAD_TABLE") { + if (this.#inTable) return this.#table?.group(code, value); + if (code === 100 && value.trim() === "AcDbTable") { + this.#inTable = true; + const room = this.#tableRoom(); + if (room !== undefined) this.#table = new TableGroups(room, this.#limits.geometryItems); + return; + } + } const keep = this.#keep; if (!r || keep === NOTHING || DROPPED.has(code) || (keep !== ALL && !keep.has(code))) return; if (r.codes.length >= MAX_GROUPS) { @@ -650,7 +685,8 @@ class DxfReader { type === "LAYOUT" || type === "IMAGEDEF" || type === "DICTIONARYVAR" || - type === "SORTENTSTABLE" + type === "SORTENTSTABLE" || + type === "TABLESTYLE" ? ALL : NOTHING; case "BLOCKS": @@ -861,7 +897,7 @@ class DxfReader { }); // An xref's block holds nothing of its own in the host. this.#inDimensionPicture = true; - } else if (!this.#geometry && /^\*D\d*$/i.test(blockName)) { + } else if (!this.#geometry && /^\*[DT]\d*$/i.test(blockName)) { this.#inDimensionPicture = true; } else { this.#block = { @@ -928,6 +964,19 @@ class DxfReader { return space; } + /** + * How many items the table whose groups arrive now may hold: what its block or the spaces may + * still keep, or undefined where the read keeps no table. The space of a table of the section + * `ENTITIES` is known at its end, and every space shares one budget. + */ + #tableRoom(): number | undefined { + if (this.#section === "ENTITIES") + return this.#geometry ? this.#limits.geometryItems - this.#geometryItems : undefined; + if (this.#section !== "BLOCKS" || this.#inDimensionPicture) return undefined; + const target = this.#target(); + return target === undefined ? undefined : this.#room(target); + } + /** Where the entity read now is kept: its block, or its space when the read keeps geometry. */ #target(): Target | undefined { return this.#block ?? (this.#geometry ? this.#space : undefined); @@ -1075,6 +1124,8 @@ class DxfReader { block.attributeDefinitions.push(definition); return; } + case "ACAD_TABLE": + return this.#tableEntity(r, layer, handle, face, target); case "VIEWPORT": { if (!space) { if (block) add(block.other, "VIEWPORT"); @@ -1108,6 +1159,45 @@ class DxfReader { else if ("malformed" in reading) add(this.unread.malformed, reading.malformed); } + /** A table, whose style and rows of title and header are named once the file is read. */ + #tableEntity( + r: Rec, + layer: string, + handle: string | undefined, + face: Facing, + target: Target | undefined, + ): void { + const groups = this.#table; + this.#table = undefined; + if (!target) return; + if (hidden(r)) return add(target.other, "invisible"); + if (face !== 1) + return add(target.other, face === 0 ? "ACAD_TABLE in 3D" : "ACAD_TABLE seen from below"); + if (brokenNumber(r) || groups === undefined) { + const why = groups === undefined ? "with no AcDbTable" : "with a number that is not finite"; + return add(this.unread.malformed, `ACAD_TABLE ${why}`); + } + const read = groups.end( + (record) => this.blockRecords.get(record) ?? this.blockRecords.get(record.toUpperCase()), + ); + if ("other" in read) return add(target.other, read.other); + if ("malformed" in read) return add(this.unread.malformed, read.malformed); + const { styleHandle, blockHandle, noTitle, noHeader, ...parts } = read.table; + const block = name(r, 2); + const entity: ReadTable = { + ...baseOf(r, layer, handle), + kind: "table", + at: point(r, 10), + ...parts, + title: false, + header: false, + ...(block !== undefined && block !== "" && { block }), + ...(blockHandle !== undefined && { blockHandle }), + }; + if (this.#kept(target, entity)) + this.#tables.push({ entity, target, style: styleHandle, noTitle, noHeader }); + } + /** What a space's census lists of a text, an `MTEXT` or a dimension, and the fields' MTEXTs. */ #census(r: Rec, layer: string, handle: string | undefined, face: Facing): void { const space = this.#space; @@ -1317,10 +1407,15 @@ class DxfReader { const value = r.values[i + 1]!; // An entry keys a map by the handle it holds, which is 1 to 16 hexadecimal digits. if (!/^[0-9A-Fa-f]{1,16}$/.test(value)) continue; - if (key === "ACAD_FIELD" || key === "TEXT") { + // The dictionary of table styles names each by its name, whatever the name is. + if (handle === this.#tableStyleDictionary) { + if (key.length <= LONGEST_NAME && this.#tableStyleEntries.length < this.#limits.census) + this.#tableStyleEntries.push([unescaped(key), value]); + } else if (key === "ACAD_FIELD" || key === "TEXT") { entries ??= {}; entries[key] = value; } else if (key === "ACAD_MLEADERSTYLE") this.#leaderStyleDictionary ??= value; + else if (key === "ACAD_TABLESTYLE") this.#tableStyleDictionary ??= value; else if (key === "ACAD_IMAGE_DICT") this.#imageDictionary ??= value; else if (key === "AcDbVariableDictionary") this.#variableDictionary ??= value; else if (handle === this.#variableDictionary && key === "WIPEOUTFRAME") @@ -1376,6 +1471,13 @@ class DxfReader { } return; } + case "TABLESTYLE": { + const handle = handleAt(r, 5); + if (handle === undefined || this.#tableStyleObjects.size >= this.#limits.census) return; + const key = handle.toUpperCase(); + if (!this.#tableStyleObjects.has(key)) this.#tableStyleObjects.set(key, tableStyleOf(r)); + return; + } case "IMAGEDEF": { const handle = handleAt(r, 5); if (handle === undefined || this.#imageDefinitions.size >= this.#limits.census) return; @@ -1479,6 +1581,7 @@ class DxfReader { ); this.#startsOfTexts(); this.#leaderStyles(styleNames); + const tableStyles = this.#tableStyles(); this.#blockHandles(); // A file before the R2000 format (AC1015) has one paper space and no LAYOUT: the leading CAD @@ -1661,6 +1764,7 @@ class DxfReader { sha256, bytes, images, + tableStyles, ...(groups.version !== undefined && { version: groups.version }), ...(groups.codepage !== undefined && { codepage: groups.codepage }), encoding: groups.encoding, @@ -1797,6 +1901,47 @@ class DxfReader { for (const target of targets) target.entities = target.entities.filter((e) => !left.has(e)); } + /** + * The table styles the dictionary of them names, in its order, and the style of each table and + * whether its first rows are a title and a header, from its style and its own groups. A style's + * name is charged to the budget its table was kept in, and a table it does not fit is counted as + * past the limit and left out. + */ + #tableStyles(): ReadTableStyle[] { + const styles: ReadTableStyle[] = []; + const named = new Map(); + for (const [styleName, handle] of this.#tableStyleEntries) { + const key = handle.toUpperCase(); + const held = this.#tableStyleObjects.get(key); + if (held === undefined || named.has(key)) continue; + named.set(key, { name: styleName, held }); + styles.push({ handle, name: styleName, ...held.style }); + } + const left = new Set(); + const targets = new Set(); + for (const { entity, target, style, noTitle, noHeader } of this.#tables) { + const found = style === undefined ? undefined : named.get(style.toUpperCase()); + const cost = nameCost(found?.name); + if (cost > this.#room(target)) { + add(target.other, "past the limit"); + left.add(entity); + targets.add(target); + continue; + } + if (target.block) this.#blockItems += cost; + else this.#geometryItems += cost; + const rows = entity.rows.length; + const title = !(noTitle ?? found?.held.noTitle ?? false) && rows > 0; + const header = !(noHeader ?? found?.held.noHeader ?? false) && rows > (title ? 1 : 0); + const mutable = entity as { style?: string; title: boolean; header: boolean }; + if (found !== undefined) mutable.style = found.name; + mutable.title = title; + mutable.header = header; + } + for (const target of targets) target.entities = target.entities.filter((e) => !left.has(e)); + return styles; + } + /** The tag of each attribute definition the blocks read hold, by its handle in capitals. */ #definitionTags(): Map { const tags = new Map(); @@ -1824,7 +1969,8 @@ class DxfReader { entity.kind !== "radial-dimension" && entity.kind !== "angular-dimension" && entity.kind !== "arc-length-dimension" && - entity.kind !== "ordinate-dimension" + entity.kind !== "ordinate-dimension" && + !(entity.kind === "table" && entity.blockHandle === undefined) ) continue; const block = entity.block; diff --git a/src/read/entities.ts b/src/read/entities.ts index 4d13e46..41f9b91 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -1397,5 +1397,14 @@ export function costOf(e: ReadEntity): number { } case "wipeout": return own + e.points.length; + case "table": + return ( + own + + chars(e.style) + + chars(e.block) + + e.rows.length + + e.columns.length + + e.cells.reduce((sum, cell) => sum + 1 + chars(cell.text) + chars(cell.block), 0) + ); } } diff --git a/src/read/model.ts b/src/read/model.ts index 6dd701e..b7b0681 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -37,9 +37,11 @@ export interface DrawingRead { readonly linetypes: readonly ReadLinetype[]; readonly textStyles: readonly ReadTextStyle[]; readonly dimensionStyles: readonly ReadDimensionStyle[]; + /** The table styles the file's dictionary of table styles names. */ + readonly tableStyles: readonly ReadTableStyle[]; /** - * Each block that is not a space or an xref. The pictures of dimensions, the blocks `*D` and a - * number, are kept by a read with `geometry` alone. + * Each block that is not a space or an xref. The pictures of dimensions and tables, the blocks + * `*D` or `*T` and a number, are kept by a read with `geometry` alone. */ readonly blocks: readonly ReadBlock[]; readonly xrefs: readonly ReadXref[]; @@ -181,6 +183,31 @@ export interface ReadTextStyle { readonly shapes: boolean; } +/** A cell style of a table style, as its file holds it. */ +export interface ReadTableCellStyle { + readonly textStyle: string; + readonly textHeight: number; + /** Where its content is: 1 to 3 along the top, left to right, 4 to 6 the middle, 7 to 9 the bottom. */ + readonly alignment: number; + /** The color index of its text, 0 for ByBlock. */ + readonly color: number; + /** The color index its cells are filled with, when they are. */ + readonly fill?: number; + /** Its borders' lineweight in hundredths of a millimeter, or -2 for ByBlock. */ + readonly lineweight: number; +} + +/** A table style. */ +export interface ReadTableStyle { + readonly handle?: string | undefined; + readonly name: string; + readonly horizontalMargin: number; + readonly verticalMargin: number; + readonly title: ReadTableCellStyle; + readonly header: ReadTableCellStyle; + readonly data: ReadTableCellStyle; +} + export interface ReadDimensionStyle { readonly handle?: string | undefined; readonly name: string; @@ -688,6 +715,56 @@ export interface ReadLeader extends ReadEntityBase { readonly note?: string; } +/** A cell of a table, as its file holds it: what it holds and what it changes of its cell style. */ +export interface ReadTableCell { + /** Where it starts, from 0 at the top left. */ + readonly row: number; + readonly column: number; + /** How many rows and columns it spans: 1 and 1, or more for a cell merged with others. */ + readonly rowSpan: number; + readonly columnSpan: number; + /** Its text, with a paragraph's codes, or undefined for none. */ + readonly text?: string; + /** The block it holds, by its name. */ + readonly block?: string; + /** The block's scale, or undefined where it is scaled to fit the cell. */ + readonly blockScale?: number; + /** Its own alignment, 1 to 9 as a cell style's, where it has one. */ + readonly alignment?: number; + readonly textHeight?: number; + /** The color index of its text, where it has one of its own. */ + readonly color?: number; + /** The color index it is filled with, where it has one of its own. */ + readonly fill?: number; +} + +/** + * A table: its rows and columns, each cell that starts a span or stands alone, and the block that + * holds its picture, which the leading CAD app shows and plots. + */ +export interface ReadTable extends ReadEntityBase { + readonly kind: "table"; + /** Its table style, when the file's dictionary of table styles names it. */ + readonly style?: string; + /** Its upper left corner. */ + readonly at: Point; + /** The way its rows run, one unit long. */ + readonly direction: Point; + /** The height of each row, from the top. */ + readonly rows: readonly number[]; + /** The width of each column, from the left. */ + readonly columns: readonly number[]; + /** True where its first row is a title, and its next a header, as its style and its own say. */ + readonly title: boolean; + readonly header: boolean; + /** Each cell that starts a span or stands alone, in reading order. */ + readonly cells: readonly ReadTableCell[]; + /** The block of its picture, `*T` and a number, when it has one. */ + readonly block?: string; + /** The handle of that block's record. */ + readonly blockHandle?: string; +} + /** A filled outline of three or four corners, as a dimension draws an arrowhead. */ export interface ReadSolid extends ReadEntityBase { readonly kind: "solid"; @@ -887,7 +964,8 @@ export type ReadEntity = | ReadSolid | ReadImage | ReadHatch - | ReadWipeout; + | ReadWipeout + | ReadTable; export interface ReadBlock { /** The handle of the block's record, which an insert's block record points to. */ diff --git a/src/read/table.ts b/src/read/table.ts new file mode 100644 index 0000000..f59b34b --- /dev/null +++ b/src/read/table.ts @@ -0,0 +1,416 @@ +// A DXF's table and table style: the groups of an `ACAD_TABLE` after its subclass `AcDbTable`, +// read as they arrive, and a `TABLESTYLE` object. A table is read from the groups every save +// holds of it, its rows, columns and cells, and not from the objects of its dictionary. +import type { Point } from "../drawing.ts"; +import { TABLE_CELLS, TABLE_COLUMNS } from "../rules.ts"; +import { textOnce, unescaped } from "./groups.ts"; +import type { ReadTableCell, ReadTableCellStyle, ReadTableStyle } from "./model.ts"; +import { inSubclass, type Rec } from "./records.ts"; + +const HANDLE = /^[0-9A-Fa-f]{1,16}$/; + +/** What a table's groups read as, but for what its style and its head say. */ +export interface TableParts { + readonly styleHandle: string | undefined; + readonly blockHandle: string | undefined; + readonly direction: Point; + readonly rows: readonly number[]; + readonly columns: readonly number[]; + /** Whether the table itself hides its title and its header, where it says. */ + readonly noTitle: boolean | undefined; + readonly noHeader: boolean | undefined; + readonly cells: readonly ReadTableCell[]; +} + +export type TableReading = + | { readonly table: TableParts } + | { readonly other: string } + | { readonly malformed: string }; + +/** A cell while its groups arrive. */ +interface CellDraft { + merged: boolean; + /** Group 91: which of its style's fields it changes. */ + flags: number; + block: boolean; + fit: boolean; + columnSpan: number; + rowSpan: number; + blockRecord?: string; + blockScale?: number; + alignment?: number; + textHeight?: number; + color?: number; + fill?: number; + noFill: boolean; + /** Its text, from groups 2 and 1, and the string its value shows, from 303 and 302. */ + text: string; + shown: string; +} + +/** Group codes of doubles. */ +const isDouble = (code: number): boolean => + (code >= 10 && code <= 59) || (code >= 110 && code <= 149); + +/** + * The groups of one table after `100 AcDbTable`, read as they arrive: its head, the height of + * each row and the width of each column, then each cell, its own groups and its value up to + * `ACVALUE_END`. It holds nothing past its limits: a table of more than `TABLE_COLUMNS` columns, + * `TABLE_CELLS` cells or `rows` rows, or whose items pass `room`, is counted, never listed. + */ +export class TableGroups { + readonly #room: number; + readonly #rowLimit: number; + #stage: "head" | "cell" | "value" = "head"; + /** How many 280 groups its head has had: the first is the version of its data. */ + #versions = 0; + #styleHandle: string | undefined; + #blockHandle: string | undefined; + #direction: [number, number] = [1, 0]; + #rowCount: number | undefined; + #columnCount: number | undefined; + #noTitle: boolean | undefined; + #noHeader: boolean | undefined; + #rows: number[] = []; + #columns: number[] = []; + #cells: CellDraft[] = []; + #cell: CellDraft | undefined; + /** What it holds so far, counted as `costOf` counts a table, with every character it holds. */ + #items = 1; + #characters = 0; + /** Why it is not read, once that is known: then it holds nothing more. */ + #refused: TableReading | undefined; + #broken = false; + #mismatched = false; + + constructor(room: number, rowLimit: number) { + this.#room = room; + this.#rowLimit = rowLimit; + } + + group(code: number, value: string): void { + if (this.#refused) return; + if (isDouble(code) && value.trim() !== "" && !Number.isFinite(Number(value))) { + this.#broken = true; + return; + } + if (code === 171) return this.#startCell(value); + if (this.#stage === "head") return this.#head(code, value); + const cell = this.#cell!; + if (this.#stage === "value") { + if (code === 1 || code === 2) this.#text(cell, "text", value); + // The string its value shows, which a cell whose value holds no text gives. + else if ((code === 302 || code === 303) && cell.text === "") this.#text(cell, "shown", value); + else if (code === 304) this.#stage = "cell"; + return; + } + const n = Number(value); + switch (code) { + case 91: + if (Number.isSafeInteger(n)) cell.flags = n; + return; + case 173: + cell.merged = n !== 0; + return; + case 174: + cell.fit = n !== 0; + return; + case 175: + cell.columnSpan = Number.isSafeInteger(n) && n > 0 ? n : 1; + return; + case 176: + cell.rowSpan = Number.isSafeInteger(n) && n > 0 ? n : 1; + return; + case 340: + if (HANDLE.test(value.trim())) cell.blockRecord = value.trim(); + return; + case 144: + cell.blockScale = n; + return; + case 170: + if (Number.isFinite(n)) cell.alignment = n; + return; + case 140: + cell.textHeight = n; + return; + case 64: + if (Number.isFinite(n)) cell.color = n; + return; + case 63: + if (Number.isFinite(n)) cell.fill = n; + return; + // In a cell, 283 says it has no fill, where in a cell style it says it has one. + case 283: + cell.noFill = n === 1; + return; + // A file of the format before R2007 holds a cell's text among its own groups. + case 1: + case 2: + this.#text(cell, "text", value); + return; + case 301: + if (value.trim() === "CELL_VALUE") this.#stage = "value"; + return; + } + } + + #head(code: number, value: string): void { + const n = Number(value); + switch (code) { + case 280: + if (this.#versions++ > 0) this.#noTitle = n === 1; + return; + case 281: + this.#noHeader = n === 1; + return; + case 342: + if (HANDLE.test(value.trim())) this.#styleHandle = value.trim(); + return; + case 343: + if (HANDLE.test(value.trim())) this.#blockHandle = value.trim(); + return; + case 11: + this.#direction[0] = n; + return; + case 21: + this.#direction[1] = n; + return; + case 91: + case 92: { + if (!Number.isSafeInteger(n) || n < 0) { + this.#refused = { malformed: "ACAD_TABLE whose rows or columns are no whole number" }; + return; + } + if (code === 91) this.#rowCount = n; + else this.#columnCount = n; + this.#limit(); + return; + } + case 141: + this.#size(this.#rows, this.#rowCount ?? this.#rowLimit, value); + return; + case 142: + this.#size(this.#columns, this.#columnCount ?? TABLE_COLUMNS, value); + return; + } + } + + /** Refuses a table past the core's limits, or of more rows than a read keeps items. */ + #limit(): void { + const [rows, columns] = [this.#rowCount ?? 0, this.#columnCount ?? 0]; + if (columns > TABLE_COLUMNS) + this.#refused = { other: `ACAD_TABLE of more than ${TABLE_COLUMNS} columns` }; + else if (rows * columns > TABLE_CELLS) + this.#refused = { other: `ACAD_TABLE of more than ${TABLE_CELLS} cells` }; + else if (rows > this.#rowLimit) + this.#refused = { other: `ACAD_TABLE of more than ${this.#rowLimit} rows` }; + else if (1 + rows + columns > this.#room) this.#refused = { other: "past the limit" }; + } + + #size(list: number[], most: number, value: string): void { + if (list.length >= most) { + this.#mismatched = true; + return; + } + list.push(Number(value)); + this.#spend(1, 0); + } + + #startCell(value: string): void { + const most = Math.min( + TABLE_CELLS, + this.#rowCount === undefined || this.#columnCount === undefined + ? TABLE_CELLS + : this.#rowCount * this.#columnCount, + ); + this.#stage = "cell"; + if (this.#cells.length >= most) { + // Its groups are read into a cell that is not kept. + this.#mismatched = true; + this.#cell = draft(value); + return; + } + this.#cell = draft(value); + this.#cells.push(this.#cell); + this.#spend(1, 0); + } + + #text(cell: CellDraft, field: "text" | "shown", value: string): void { + cell[field] += value; + this.#spend(0, value.length); + } + + #spend(items: number, characters: number): void { + this.#items += items; + this.#characters += characters; + if (this.#items + Math.floor(this.#characters / 32) > this.#room) { + this.#refused = { other: "past the limit" }; + this.#cells = []; + this.#rows = []; + this.#columns = []; + } + } + + /** What the table reads as, with each cell's block named from its record's handle. */ + end(blockName: (record: string) => string | undefined): TableReading { + if (this.#refused) return this.#refused; + if (this.#broken) return { malformed: "ACAD_TABLE with a number that is not finite" }; + const rows = this.#rowCount ?? this.#rows.length; + const columns = this.#columnCount ?? this.#columns.length; + if ( + this.#mismatched || + this.#rows.length !== rows || + this.#columns.length !== columns || + this.#cells.length !== rows * columns + ) { + return { malformed: "ACAD_TABLE whose rows, columns or cells are not as many as it says" }; + } + const cells: ReadTableCell[] = []; + this.#cells.forEach((c, i) => { + if (c.merged) return; + const text = c.text !== "" ? c.text : c.shown; + const block = c.block && c.blockRecord !== undefined ? blockName(c.blockRecord) : undefined; + cells.push({ + row: Math.floor(i / columns), + column: i % columns, + rowSpan: c.rowSpan, + columnSpan: c.columnSpan, + ...(!c.block && text !== "" && { text: textOnce(text) }), + ...(block !== undefined && { block }), + ...(block !== undefined && + !c.fit && { blockScale: Number.isFinite(c.blockScale) ? c.blockScale! : 1 }), + ...((c.flags & ALIGNMENT_OWN) !== 0 && + c.alignment !== undefined && { alignment: c.alignment }), + ...((c.flags & HEIGHT_OWN) !== 0 && + Number.isFinite(c.textHeight) && { textHeight: c.textHeight! }), + ...((c.flags & COLOR_OWN) !== 0 && c.color !== undefined && { color: c.color }), + ...((c.flags & FILL_OWN) !== 0 && c.fill !== undefined && !c.noFill && { fill: c.fill }), + }); + }); + const [dx, dy] = this.#direction; + const length = Math.hypot(dx, dy); + const direction: Point = + !Number.isFinite(length) || length === 0 + ? [1, 0] + : Math.abs(length - 1) > 1e-9 + ? [dx / length, dy / length] + : [dx, dy]; + return { + table: { + styleHandle: this.#styleHandle, + blockHandle: this.#blockHandle, + direction, + rows: this.#rows, + columns: this.#columns, + noTitle: this.#noTitle, + noHeader: this.#noHeader, + cells, + }, + }; + } +} + +/** The bits of a cell's group 91 that say it changes its style's alignment, fill color, text color and text height. */ +const ALIGNMENT_OWN = 0x1; +const FILL_OWN = 0x4; +const COLOR_OWN = 0x8; +const HEIGHT_OWN = 0x20; + +function draft(type: string): CellDraft { + return { + merged: false, + flags: 0, + block: Number(type) === 2, + fit: false, + columnSpan: 1, + rowSpan: 1, + noFill: false, + text: "", + shown: "", + }; +} + +/** The kinds of row in the order a table style holds their cell styles. */ +const KINDS = ["data", "title", "header"] as const; + +/** Where each kind of row puts its content where its cell style does not say: the top center, or the middle. */ +const ALIGNMENT = { data: 2, title: 5, header: 5 } as const; + +/** The leading CAD app's own sizes, which a style that states none has. */ +const TEXT_HEIGHT = { data: 0.18, title: 0.25, header: 0.18 } as const; +const MARGIN = 0.06; + +/** A table style as a `TABLESTYLE` holds it, with whether it hides its title and its header. */ +export interface TableStyleHeld { + readonly style: Omit; + readonly noTitle: boolean; + readonly noHeader: boolean; +} + +/** The codes of a cell style's own fields, any of which starts the next cell style once it has it. */ +const CELL_CODES = new Set([7, 140, 170, 62, 63, 283, 274]); + +/** + * A `TABLESTYLE`: its margins, whether it hides its title and its header, then a cell style for + * each kind of row, in the order data, title, header. A cell style starts at its text style, + * group 7, or at a field the one before already holds. A field a style leaves out is the leading + * CAD app's own. + */ +export function tableStyleOf(r: Rec): TableStyleHeld { + const own = inSubclass(r, "AcDbTableStyle"); + let horizontal = MARGIN; + let vertical = MARGIN; + let noTitle = false; + let noHeader = false; + let versions = 0; + const cells: Map[] = []; + let cell: Map | undefined; + for (let i = 0; i < own.codes.length; i++) { + const code = own.codes[i]!; + const value = own.values[i]!; + if (CELL_CODES.has(code)) { + if (cell === undefined || code === 7 || cell.has(code)) { + if (cells.length === KINDS.length) break; + cell = new Map(); + cells.push(cell); + } + cell.set(code, value); + continue; + } + if (cell !== undefined) continue; + const n = Number(value); + if (code === 40 && Number.isFinite(n)) horizontal = n; + else if (code === 41 && Number.isFinite(n)) vertical = n; + else if (code === 280 && versions++ > 0) noTitle = n === 1; + else if (code === 281) noHeader = n === 1; + } + const styleOf = (kind: (typeof KINDS)[number], at: number): ReadTableCellStyle => { + const groups = cells[at]; + const number = (code: number, otherwise: number): number => { + const value = groups?.get(code); + const n = Number(value); + return value !== undefined && value.trim() !== "" && Number.isFinite(n) ? n : otherwise; + }; + const textStyle = groups?.get(7); + const filled = number(283, 0) === 1; + return { + textStyle: textStyle === undefined || textStyle === "" ? "Standard" : unescaped(textStyle), + textHeight: number(140, TEXT_HEIGHT[kind]), + alignment: number(170, ALIGNMENT[kind]), + color: number(62, 0), + ...(filled && { fill: number(63, 7) }), + lineweight: number(274, -2), + }; + }; + return { + style: { + horizontalMargin: horizontal, + verticalMargin: vertical, + data: styleOf("data", 0), + title: styleOf("title", 1), + header: styleOf("header", 2), + }, + noTitle, + noHeader, + }; +} diff --git a/src/rules.ts b/src/rules.ts index aecbf06..c2d8ec6 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -130,6 +130,14 @@ const LEADER_STYLE_NAMES = { length: "Leader style names cannot be longer than 255 characters, as dimension style names cannot", } as const; +const TABLE_STYLE_NAMES = { + empty: "Table style names cannot be empty", + chars: 'Table style names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', + rejected: + "Table style names cannot contain a character the leading CAD app rejects or replaces in names, such as a zero-width space or the ohm sign U+2126. docs/layer-names.md in the tsdraft repository lists them", + edge: "Table style names cannot start or end with a space", + length: "Table style names cannot be longer than 255 characters, as dimension style names cannot", +} as const; const HATCH_PATTERN_NAMES = { empty: "Hatch pattern names cannot be empty", chars: 'Hatch pattern names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks', @@ -145,7 +153,8 @@ type NameMessages = | typeof BLOCK_NAMES | typeof DIMENSION_STYLE_NAMES | typeof LEADER_STYLE_NAMES - | typeof HATCH_PATTERN_NAMES; + | typeof HATCH_PATTERN_NAMES + | typeof TABLE_STYLE_NAMES; const NAME_R12_CHARS = 'R12 layer names can only use letters, digits, $, - and _. Use DXF version "R2018" for other characters'; const NAME_R12_LENGTH = @@ -183,6 +192,7 @@ const R12_PARAGRAPHS = 'tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph'; const LINE_SPACING = "A paragraph's line spacing is a factor from 0.25 to 4"; const R12_IMAGES = 'tsdraft writes no images to R12 drawings. Use DXF version "R2018" for an image'; +const R12_TABLES = 'tsdraft writes no tables to R12 drawings. Use DXF version "R2018" for a table'; const R12_HATCHES = 'tsdraft writes no hatches or wipeouts to R12 drawings. Use DXF version "R2018" for a fill'; const R12_CURVES = @@ -1930,6 +1940,7 @@ export const R12_ONLY = { paragraphs: R12_PARAGRAPHS, images: R12_IMAGES, hatches: R12_HATCHES, + tables: R12_TABLES, curves: R12_CURVES, } as const; @@ -4978,3 +4989,373 @@ export function leaderOwnProblem(given: object, scale: number): string | undefin } return leaderScaledProblem(leader, scale); } + +/** The most columns a table may have, and the most cells: rows times columns. */ +export const TABLE_COLUMNS = 1000; +export const TABLE_CELLS = 100_000; + +const STANDARD_TABLE_STYLE_DEFINED = + "The table style \"Standard\" is the leading CAD app's own, which tsdraft writes beside a drawing's table styles, and cannot be defined. That app keeps the first style of a name and skips a second"; +const STANDARD_TABLE_STYLE_USED = + 'tsdraft draws no table in the table style "Standard", which is the leading CAD app\'s own. Define a style with tableStyle() and name it'; +/** What is wrong with a table inside a block. */ +export const TABLE_IN_BLOCK = + "A table cannot be drawn in a block. Draw it in model space or on a layout, where the leading CAD app edits it"; +const CELL_COLOR = "a color is a color index, an integer from 1 to 255"; + +/** Returns what is wrong with a table style's name, or undefined. */ +export function tableStyleNameProblem(name: unknown): string | undefined { + if (typeof name !== "string") return "A table style's name must be a string"; + return nameProblem(name, TABLE_STYLE_NAMES); +} + +/** True for `Standard`, the leading CAD app's own table style, in any case. */ +export function isStandardTableStyle(name: string): boolean { + return layerKey(name) === layerKey("Standard"); +} + +/** Returns what is wrong with a table that names `Standard`, or undefined. */ +export function standardTableStyleProblem(name: string): string | undefined { + return isStandardTableStyle(name) ? STANDARD_TABLE_STYLE_USED : undefined; +} + +/** Returns what is wrong with an optional size: a finite number greater than 0 as written. */ +function optionalSizeProblem(value: unknown, field: string): string | undefined { + if (value === undefined) return undefined; + if (typeof value !== "number" || !Number.isFinite(value)) + return `${field} must be a finite number`; + const problem = sizeProblem(value); + return problem ? `${field}: ${problem}` : undefined; +} + +/** Returns what is wrong with a color index of a cell or a cell style, or undefined. */ +function cellColorProblem(value: unknown, field: string): string | undefined { + if (value === undefined) return undefined; + return Number.isInteger(value) && (value as number) >= 1 && (value as number) <= 255 + ? undefined + : `${field}: ${CELL_COLOR}`; +} + +/** Returns what is wrong with an `align` and a `valign`, or undefined. */ +function cellPlaceProblem(o: Record, at: string): string | undefined { + if (o.align !== undefined && !(PARAGRAPH_ALIGNS as readonly unknown[]).includes(o.align)) { + return `${at}align must be "left", "center" or "right"`; + } + if ( + o.valign !== undefined && + !(PARAGRAPH_VERTICAL_ALIGNS as readonly unknown[]).includes(o.valign) + ) { + return `${at}valign must be "top", "middle" or "bottom"`; + } + return undefined; +} + +/** The fields of a cell style, and of a cell given as an object. */ +const CELL_STYLE_FIELDS = new Set([ + "textStyle", + "textHeight", + "align", + "valign", + "color", + "fill", + "lineweight", +]); +const CELL_FIELDS = new Set([ + "text", + "block", + "blockScale", + "columnSpan", + "rowSpan", + "align", + "valign", + "textHeight", + "color", + "fill", +]); + +/** Returns what is wrong with a field an object does not have, or undefined. */ +function unknownFieldProblem( + o: object, + known: ReadonlySet, + at: string, +): string | undefined { + for (const field of Object.keys(o)) { + if (!known.has(field)) return `${at} has no field ${shown(field)}`; + if ((o as Record)[field] === undefined) { + return `${at}.${field} is undefined: leave a field out rather than set it to undefined`; + } + } + return undefined; +} + +/** Returns what is wrong with a cell style of a table style, or undefined. */ +function cellStyleProblem(value: unknown, kind: string): string | undefined { + if (value === undefined) return undefined; + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return `${kind} must be an object, the cell style of its rows`; + } + const o = value as Record; + const unknown = unknownFieldProblem(o, CELL_STYLE_FIELDS, kind); + if (unknown) return unknown; + const at = `${kind}.`; + if (o.textStyle !== undefined) { + if (typeof o.textStyle !== "string") return `${at}textStyle: a text style is named by a string`; + const problem = textStyleNameProblem(o.textStyle); + if (problem) return `${at}textStyle: ${problem}`; + } + return ( + optionalSizeProblem(o.textHeight, `${at}textHeight`) ?? + cellPlaceProblem(o, at) ?? + cellColorProblem(o.color, `${at}color`) ?? + cellColorProblem(o.fill, `${at}fill`) ?? + (o.lineweight === undefined || + (typeof o.lineweight === "number" && (LINEWEIGHTS as readonly number[]).includes(o.lineweight)) + ? undefined + : `${at}lineweight must be one of LINEWEIGHTS, in millimetres`) + ); +} + +/** Returns what is wrong with a table style, or undefined. */ +export function tableStyleProblem(style: unknown): string | undefined { + if (typeof style !== "object" || style === null || Array.isArray(style)) { + return "A table style must be an object with a name and a text height"; + } + const s = style as Record; + const nameError = tableStyleNameProblem(s.name); + if (nameError) return nameError; + if (isStandardTableStyle(s.name as string)) return STANDARD_TABLE_STYLE_DEFINED; + if (s.textStyle !== undefined) { + if (typeof s.textStyle !== "string") return "textStyle: a text style is named by a string"; + const problem = textStyleNameProblem(s.textStyle); + if (problem) return `textStyle: ${problem}`; + } + if (typeof s.textHeight !== "number" || !Number.isFinite(s.textHeight)) { + return "textHeight must be a finite number"; + } + const height = sizeProblem(s.textHeight); + if (height) return `textHeight: ${height}`; + for (const field of ["horizontalMargin", "verticalMargin"] as const) { + const value = s[field]; + if (value === undefined) continue; + if (typeof value !== "number" || !Number.isFinite(value) || !(value >= 0)) { + return `${field} must be a finite number, 0 or more`; + } + const problem = magnitudeProblem(value); + if (problem) return `${field}: ${problem}`; + } + for (const kind of ["title", "header", "data"] as const) { + const problem = cellStyleProblem(s[kind], kind); + if (problem) return problem; + } + return undefined; +} + +/** + * Returns what is wrong with a table style twin of the drawing's, as `leaderStyleTwinProblem` + * says of leader styles. + */ +export function tableStyleTwinProblem(name: string, other: string): string | undefined { + if (layerAuditKey(name) !== layerAuditKey(other)) return undefined; + if (layerKey(name) === layerKey(other)) { + return "The drawing already has a table style of this name. CAD ignores case in table style names and keeps the first"; + } + return `The drawing already has a table style of this name, as ${JSON.stringify(other)}. tsdraft holds table style names to the rules of dimension style names, which the leading CAD app's AUDIT takes for one name`; +} + +/** Returns what is wrong with one cell, given as a string, an object or `null`, or undefined. */ +function cellProblem( + cell: unknown, + at: string, + hasBlock: (name: string) => boolean | undefined, +): string | undefined { + if (typeof cell === "string") + return ( + paragraphValueProblem(cell, undefined) && `${at}: ${paragraphValueProblem(cell, undefined)}` + ); + if (typeof cell !== "object" || cell === null || Array.isArray(cell)) { + return `${at} must be a string, an object or null`; + } + const o = cell as Record; + const unknown = unknownFieldProblem(o, CELL_FIELDS, at); + if (unknown) return unknown; + if (o.text !== undefined) { + if (typeof o.text !== "string") return `${at}.text must be a string`; + const problem = paragraphValueProblem(o.text, undefined); + if (problem) return `${at}.text: ${problem}`; + } + if (o.block !== undefined) { + if (typeof o.block !== "string") return `${at}.block: a block is named by a string`; + if (o.text !== undefined) return `${at} holds a text or a block, not both`; + const problem = blockNameProblem(o.block); + if (problem) return `${at}.block: ${problem}`; + if (hasBlock(o.block) === false) + return `${at}.block: the block ${JSON.stringify(o.block)} is not defined`; + } + if (o.blockScale !== undefined) { + if (o.block === undefined) return `${at}.blockScale is for a cell that holds a block`; + const problem = optionalSizeProblem(o.blockScale, `${at}.blockScale`); + if (problem) return problem; + } + for (const field of ["columnSpan", "rowSpan"] as const) { + const value = o[field]; + if (value !== undefined && !(Number.isInteger(value) && (value as number) >= 1)) { + return `${at}.${field} must be a whole number, 1 or more`; + } + } + return ( + cellPlaceProblem(o, `${at}.`) ?? + optionalSizeProblem(o.textHeight, `${at}.textHeight`) ?? + cellColorProblem(o.color, `${at}.color`) ?? + cellColorProblem(o.fill, `${at}.fill`) + ); +} + +/** + * Returns what is wrong with a table's columns, rows, cells and heights, or undefined. `hasBlock` + * says whether the drawing has a block, or undefined where that is not known. + */ +export function tableProblem( + table: unknown, + hasBlock: (name: string) => boolean | undefined = () => undefined, +): string | undefined { + if (typeof table !== "object" || table === null) return "A table must be an object"; + const t = table as Record; + const at = t.at; + if ( + !Array.isArray(at) || + at.length !== 2 || + !at.every((n) => typeof n === "number" && Number.isFinite(n)) + ) { + return "at must be a point, [x, y], the table's upper left corner"; + } + if ( + t.rotation !== undefined && + (typeof t.rotation !== "number" || !Number.isFinite(t.rotation)) + ) { + return "rotation must be a finite number of degrees"; + } + const columns = t.columns; + if (!Array.isArray(columns) || columns.length === 0) + return "columns must list the width of each column, one or more"; + if (columns.length > TABLE_COLUMNS) return `A table has at most ${TABLE_COLUMNS} columns`; + for (let c = 0; c < columns.length; c++) { + const width = columns[c]; + if (typeof width !== "number" || !Number.isFinite(width)) + return `columns[${c}] must be a finite number`; + const problem = sizeProblem(width); + if (problem) return `columns[${c}]: ${problem}`; + } + const count = columns.length; + const rows = t.rows; + if (!Array.isArray(rows)) return "rows must be a list of rows, each a list of cells"; + const all = (t.title === undefined ? 0 : 1) + (t.header === undefined ? 0 : 1) + rows.length; + if (all === 0) return "A table needs a row: a title, a header or a data row"; + if (all * count > TABLE_CELLS) + return `A table has at most ${TABLE_CELLS} cells, its rows times its columns`; + for (const field of ["titleHeight", "headerHeight"] as const) { + const problem = optionalSizeProblem(t[field], field); + if (problem) return problem; + } + if (t.titleHeight !== undefined && t.title === undefined) + return "titleHeight is for a table with a title"; + if (t.headerHeight !== undefined && t.header === undefined) + return "headerHeight is for a table with a header"; + if (t.rowHeights !== undefined) { + const heights = t.rowHeights; + if (!Array.isArray(heights) || heights.length !== rows.length) { + return "rowHeights must give a height or null for each data row"; + } + for (let r = 0; r < heights.length; r++) { + const height: unknown = heights[r]; + if (height === null) continue; + if (height === undefined) return `rowHeights[${r}] must be a height or null`; + const problem = optionalSizeProblem(height, `rowHeights[${r}]`); + if (problem) return problem; + } + } + if (t.title !== undefined) { + if (t.title === null) return "title must be a string or an object"; + const problem = cellProblem(t.title, "title", hasBlock); + if (problem) return problem; + const o = t.title as Record; + if (typeof o === "object" && (o.columnSpan !== undefined || o.rowSpan !== undefined)) { + return "title spans every column and one row of its own, so it takes no columnSpan or rowSpan"; + } + } + // The rows below the title, header first: each cell in its place, and what each span covers. + const lists: { readonly name: string; readonly cells: unknown; readonly header: boolean }[] = []; + if (t.header !== undefined) lists.push({ name: "header", cells: t.header, header: true }); + for (let r = 0; r < rows.length; r++) { + lists.push({ name: `rows[${r}]`, cells: rows[r], header: false }); + } + const covered: Uint8Array = new Uint8Array(lists.length * count); + for (let r = 0; r < lists.length; r++) { + const { name, cells, header } = lists[r]!; + if (!Array.isArray(cells) || cells.length !== count) { + return `${name} must hold a cell for each of the ${count} columns, null for one another spans`; + } + for (let c = 0; c < count; c++) { + const cell = cells[c]; + const here = `${name}[${c}]`; + if (cell === null) { + if (covered[r * count + c] !== 1) + return `${here} is null, but no cell above or to its left spans it`; + continue; + } + if (covered[r * count + c] === 1) + return `${here} is spanned by a cell above or to its left, so it must be null`; + const problem = cellProblem(cell, here, hasBlock); + if (problem) return problem; + const o = typeof cell === "object" ? (cell as Record) : {}; + const across = (o.columnSpan as number | undefined) ?? 1; + const down = (o.rowSpan as number | undefined) ?? 1; + if (c + across > count) return `${here} spans past the table's last column`; + if (r + down > lists.length) return `${here} spans past the table's last row`; + if (header && down > 1) return `${here} spans from the header into the data rows`; + for (let rr = r; rr < r + down; rr++) { + for (let cc = c; cc < c + across; cc++) { + if (rr === r && cc === c) continue; + if (covered[rr * count + cc] === 1) return `${here} spans a cell another already spans`; + covered[rr * count + cc] = 1; + } + } + } + } + return undefined; +} + +/** + * Returns what is wrong with a table's columns in its style, or undefined: a column must be wider + * than its two horizontal margins, which a cell's text is narrower than its column by. + */ +export function tableColumnsProblem( + columns: readonly number[], + margin: number, +): string | undefined { + for (let c = 0; c < columns.length; c++) { + if (!(written(columns[c]! - 2 * margin) > 0)) { + return `columns[${c}] is ${shown(columns[c])} wide, no wider than its two margins of ${shown(margin)}, which leave its text no width`; + } + } + return undefined; +} + +/** + * Returns what is wrong with a table's texts in the fonts of their rows, or undefined: the rules + * a paragraph's value is held to in its font. `fontOf` gives the font of a text style, or of + * `Standard` for undefined. + */ +export function tableTextsProblem( + cells: readonly { + readonly text: string; + readonly textStyle: string | undefined; + readonly at: string; + }[], + fontOf: (textStyle: string | undefined) => string | undefined, +): string | undefined { + for (const { text, textStyle, at } of cells) { + const problem = paragraphValueProblem(text, fontOf(textStyle)); + if (problem) return `${at}: ${problem}`; + } + return undefined; +} diff --git a/src/shape.ts b/src/shape.ts index aec7d09..8f314c4 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -23,6 +23,8 @@ import type { Layout, Leader, LeaderStyle, + Table, + TableStyle, Line, LinearDimension, RadiusDimension, @@ -319,6 +321,7 @@ export interface Shapes { readonly textStyle: Check; readonly dimensionStyle: Check; readonly leaderStyle: Check; + readonly tableStyle: Check; readonly block: Check; readonly attribute: Check; readonly xref: Check; @@ -682,6 +685,19 @@ function shapes(all: boolean, typed = all): Shapes { { ...shared, pattern: LEFT, gradient: LEFT }, ), wipeout: fields({ kind, layer: string, points: list(point) }, shared), + // A rule of `lint` reports the columns, the cells and the heights, whatever their type. + table: fields( + { kind, layer: string, style: ruled(string), at: point, columns: LEFT, rows: LEFT }, + { + id: ruled(string), + rotation: number, + title: LEFT, + titleHeight: ruled(number), + header: LEFT, + headerHeight: ruled(number), + rowHeights: LEFT, + }, + ), } satisfies Record; const entity: Check = (value, at, problems, extra) => { @@ -839,6 +855,20 @@ function shapes(all: boolean, typed = all): Shapes { }, ), ); + // A rule of `lint` reports each cell style, whatever its type. + const tableStyle = record( + fields( + { name: ruled(string), textHeight: ruled(number) }, + { + textStyle: ruled(string), + horizontalMargin: ruled(number), + verticalMargin: ruled(number), + title: LEFT, + header: LEFT, + data: LEFT, + }, + ), + ); const attribute = record( fields( { @@ -907,6 +937,7 @@ function shapes(all: boolean, typed = all): Shapes { layouts: ruled(table(layout)), dimensionStyles: ruled(table(dimensionStyle)), leaderStyles: ruled(table(leaderStyle)), + tableStyles: ruled(table(tableStyle)), imageFrame: ruled(boolean), wipeoutFrame: ruled(boolean), patterns: ruled(table(pattern)), @@ -922,6 +953,7 @@ function shapes(all: boolean, typed = all): Shapes { textStyle, dimensionStyle, leaderStyle, + tableStyle, block, attribute, xref: record(xref), diff --git a/src/svg.ts b/src/svg.ts index ef18cf2..f189c33 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -22,6 +22,8 @@ import { type Insert, type Layer, type Leader, + type Table, + type TableStyle, type LeaderStyle, type Line, type Linetype, @@ -103,9 +105,19 @@ import { fifteenDigits, fmt, written } from "./format.ts"; import { layerKey, layerKeys } from "./layers.ts"; import { findLayout, validViewportView } from "./layouts.ts"; import { leaderBlock, leaderPicture, type LeaderPicture } from "./leaders.ts"; +import { + tableCost, + tableInserts, + tableMatrix, + tableMeasures, + tableParagraph, + tablePicture, + type TablePicture, +} from "./tables.ts"; import { builtInLinetype, LINEWEIGHTS, lineweightCode } from "./linetypes.ts"; import { drawnValue, inStyle, layoutText } from "./measure.ts"; import { + layoutCellText, layoutDimensionText, paragraphInStyle, paragraphMeasurer, @@ -120,6 +132,7 @@ import { MARK_ORIENTS, shown as quoted, SplineMemo, + tableProblem, turning, viewportProblem, type DrawnEllipse, @@ -729,6 +742,8 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): drawing.dimensionStyles, drawing.leaderStyles, most, + most, + drawing.tableStyles, )); const boxOf = (entities: readonly Entity[], at: (e: Entity) => string) => { const boxes = boxesOf(); @@ -755,6 +770,71 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): pictures.set(e, { style, textStyle, picture }); return picture; }; + /** The picture of each table, worked out once for the picture. */ + /** + * The box of each block a table's cell holds, by its drawing: of every entity of the block, + * hidden or not, as the writers box it, so a cell's block takes the scale the file holds. + */ + const blockBoxes = new Map< + Drawing, + { + readonly box: Boxer; + readonly known: Map; + } + >(); + const plainBoxOf = (of: Drawing, name: string) => { + let held = blockBoxes.get(of); + if (!held) { + held = { + box: boxer( + of.textStyles, + of.blocks, + undefined, + undefined, + undefined, + of.dimensionStyles, + of.leaderStyles, + most, + most, + of.tableStyles, + ), + known: new Map(), + }; + blockBoxes.set(of, held); + } + const k = key(name); + if (!held.known.has(k)) { + const found = held.box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }]); + if (held.box.capped) refuse(drawingAt?.() ?? "a table", true); + held.known.set(k, found); + } + return held.known.get(k); + }; + /** The picture of each table, worked out once for each drawing it is drawn from. */ + const tablePictures = new WeakMap>(); + const tablePictureOf = (e: Table, from?: Referenced): TablePicture | undefined => { + let byFrom = tablePictures.get(e); + if (!byFrom) tablePictures.set(e, (byFrom = new Map())); + if (byFrom.has(from)) return byFrom.get(from); + byFrom.set(from, undefined); + // A table or a style the rules refuse draws nothing. Its cells are paid for before they are + // read, as the picture's other work is. + if (typeof e.style !== "string") return undefined; + if (!spend(tableCost(e))) refuse(drawingAt?.() ?? "a table"); + const tables = tablesOf(from); + const style = tables.tableStyles.get(key(e.style)); + if (style === undefined || tableProblem(e) !== undefined) return undefined; + const picture = tablePicture( + e, + style, + tableMeasures( + (name) => (name === undefined ? undefined : tables.textStyles.get(key(name))), + (name) => plainBoxOf(from?.drawing ?? drawing, name), + ), + ); + byFrom.set(from, picture); + return picture; + }; /** The layout of each paragraph, a long value laid out once for the picture. */ const paragraphs = paragraphMeasurer(); /** @@ -957,6 +1037,22 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const layOut = () => paragraphs.layout(paragraphInStyle(picture!.note, textStyle)); return leaderToSvg(e, picture, layOut, mark, drawnPen, look, matrix, room, sides); } + if (e.kind === "table") { + const tables = tablesOf(from); + const styleOf = (name: string | undefined) => + name === undefined ? undefined : tables.textStyles.get(key(name)); + return tableToSvg( + e, + tablePictureOf(e, from), + styleOf, + mark, + drawnPen, + look, + matrix, + room, + sides, + ); + } if (e.kind === "image") { // One whose fields cannot be drawn, which `lint` refuses, draws nothing. return imageDrawable(e, clipsChecked) @@ -1137,6 +1233,15 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): e.kind === "insert" ? !frozen({ name: e.layer }) : !hidden({ name: e.layer }), ) .flatMap(([i, e]): [number, Entity][] => { + // A table draws the block of each of its cells as an insert of it, after itself. + if (e.kind === "table") { + const picture = tablePictureOf(e); + // Each insert a placement makes is paid for before it is made. + if (picture !== undefined && !spend(picture.blocks.length)) + refuse(drawingAt?.() ?? "a table"); + const inserts = picture === undefined ? [] : tableInserts(e, picture); + return [[i, e], ...inserts.map((insert): [number, Entity] => [i, insert])]; + } // A leader whose content is a block draws the block as an insert of it, after itself. const content = e.kind === "leader" ? contentOf(e) : undefined; return content === undefined @@ -1224,6 +1329,15 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): xrefs, (cost) => length <= longest && spend(cost), key, + // A referenced drawing's table draws the block of each of its cells, as one of this + // drawing's does, each insert paid for before it is made. + (held, at) => { + if (held.kind !== "table" || hidden(at.layer) || frozenHere?.(at.layer)) return []; + const picture = tablePictureOf(held, at.from); + if (picture === undefined || picture.blocks.length === 0) return []; + if (!spend(picture.blocks.length)) refuse(where()); + return tableInserts(held, picture); + }, ); if (!walked || length > longest) refuse(where()); const xref = blocks.has(key(e.block)) ? undefined : xrefPaths.get(key(e.block)); @@ -1560,6 +1674,7 @@ interface Tables { readonly textStyles: ReadonlyMap; readonly dimensionStyles: ReadonlyMap; readonly leaderStyles: ReadonlyMap; + readonly tableStyles: ReadonlyMap; /** The hatch patterns, by name as a linetype's is found: the first of a name. */ readonly hatchPatterns: ReadonlyMap; } @@ -1577,6 +1692,12 @@ function tablesFor(drawing: Drawing): Tables { textStyles: new Map(filled(drawing.textStyles).map((t) => [layerKey(t.name), t])), dimensionStyles: new Map(filled(drawing.dimensionStyles).map((t) => [layerKey(t.name), t])), leaderStyles: new Map(filled(drawing.leaderStyles).map((t) => [layerKey(t.name), t])), + // A style that is no object with a name, which `lint` refuses, is one the drawing lacks. + tableStyles: new Map( + filled(drawing.tableStyles) + .filter((t) => typeof (t as { name?: unknown } | null)?.name === "string") + .map((t) => [layerKey(t.name), t]), + ), hatchPatterns, }; } @@ -1636,11 +1757,11 @@ function viewOf(view: SvgOptions["view"]): [number, number, number, number] | un type Drawn = Exclude; /** An entity that is one shape, with a linetype and a lineweight it may have of its own. */ -type Shape = Exclude; +type Shape = Exclude; /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ function styled(e: Drawn): Pick { - return isDimension(e) || e.kind === "leader" ? {} : e; + return isDimension(e) || e.kind === "leader" || e.kind === "table" ? {} : e; } /** @@ -1735,6 +1856,84 @@ function leaderToSvg( * the picture, longer than the room, which `write` then refuses, and lays nothing out when its * value alone passes it. */ +/** + * A table as a group: the fill of each cell that has one, its lines, each in its own lineweight + * or the table's, and the text of each cell, laid out as the leading CAD app lays out a cell's. + * The blocks its cells hold are drawn after it, as inserts. + */ +function tableToSvg( + e: Table, + picture: TablePicture | undefined, + styleOf: (name: string | undefined) => TextStyle | undefined, + mark: string, + pen: Pen, + look: Look, + matrix: Matrix | undefined, + room: number, + sides: Known, +): string { + if (picture === undefined) return ``; + const placed = matrix ? compose(matrix, tableMatrix(e)) : tableMatrix(e); + const own = tableMatrix(e); + const at = (p: Point): Point => mapPoint(placed, p); + const inSpace = (p: Point): Point => mapPoint(own, p); + const parts: string[] = []; + let left = room; + const add = (part: (left: number) => string): void => { + if (left < 0) return; + const drawn = part(left); + parts.push(drawn); + left -= drawn.length; + }; + for (const fill of picture.fills) { + const [x0, y0, x1, y1] = fill.box; + const corners = ( + [ + [x0, y0], + [x1, y0], + [x1, y1], + [x0, y1], + ] as const + ).map(at); + add( + () => + ``, + ); + } + for (const line of picture.lines) { + const weighed = + line.lineweight === undefined ? pen : { ...pen, lineweight: lineweightCode(line.lineweight) }; + add((left) => + entityToSvg( + { kind: "line", layer: e.layer, from: inSpace(line.from), to: inSpace(line.to) }, + `data-part="line"`, + weighed, + look, + undefined, + matrix, + left, + sides, + ), + ); + } + for (const text of picture.texts) { + const paragraph = tableParagraph(e, text); + const lettered = text.color === undefined ? pen : { ...pen, color: look.color(text.color) }; + add((left) => + paragraphToSvg( + paragraph, + () => layoutCellText(paragraphInStyle(paragraph, styleOf(text.textStyle))), + `data-part="text"`, + lettered, + look, + matrix, + left, + ), + ); + } + return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; +} + function paragraphToSvg( e: Paragraph, layOut: () => ParagraphLayout, diff --git a/src/table-pictures.ts b/src/table-pictures.ts new file mode 100644 index 0000000..92c7c1c --- /dev/null +++ b/src/table-pictures.ts @@ -0,0 +1,79 @@ +// The tables of a drawing as both writers write them: each with its style, the key of its handles +// and its picture, and the name of the block that holds the picture. +import { blocksByKey } from "./blocks.ts"; +import type { Drawing, Table, TableStyle, TextStyle } from "./drawing.ts"; +import { boxer, type Boxer } from "./extents.ts"; +import { layerKey } from "./layers.ts"; +import { checksLimit } from "./lint.ts"; +import { tableMeasures, tablePicture, type TablePicture, type TablePlace } from "./tables.ts"; + +/** A table of a drawing, with what the writers need to write it. */ +export interface DrawnTable { + readonly table: Table; + /** 0 for model space, or 1 and on for each layout in the drawing's order. */ + readonly space: number; + /** Its index among the entities of its space. */ + readonly index: number; + /** The block of its picture: `*T` and its number among the drawing's tables, from 1. */ + readonly name: string; + readonly place: TablePlace; + readonly style: TableStyle; + readonly picture: TablePicture; +} + +/** + * The tables of model space, then of each layout, that name a style of the drawing, with their + * pictures. `boxOf` boxes a cell's block; missing, one is made for the drawing. + */ +export function drawingTables(drawing: Drawing, boxOf?: Boxer): DrawnTable[] { + const styles = new Map((drawing.tableStyles ?? []).map((style) => [layerKey(style.name), style])); + if (styles.size === 0) return []; + const textStyles = new Map( + (drawing.textStyles ?? []).map((style) => [layerKey(style.name), style]), + ); + const styleOf = (name: string | undefined): TextStyle | undefined => + name === undefined ? undefined : textStyles.get(layerKey(name)); + const blocks = blocksByKey(drawing.blocks); + const box = + boxOf ?? + boxer( + drawing.textStyles, + drawing.blocks, + undefined, + undefined, + undefined, + drawing.dimensionStyles, + drawing.leaderStyles, + checksLimit(drawing), + ); + const measures = tableMeasures(styleOf, (name) => { + const found = blocks.get(layerKey(name)); + return found === undefined + ? undefined + : box([{ kind: "insert", layer: "0", block: found.name, at: [0, 0] }]); + }); + const layouts = drawing.layouts ?? []; + const out: DrawnTable[] = []; + [drawing.entities, ...layouts.map((layout) => layout.entities)].forEach((entities, space) => { + entities.forEach((entity, index) => { + if (entity.kind !== "table") return; + const style = styles.get(layerKey(entity.style)); + if (style === undefined) return; + const layout = space === 0 ? undefined : layouts[space - 1]!.name; + out.push({ + table: entity, + space, + index, + name: `*T${out.length + 1}`, + place: { + index, + ...(entity.id === undefined ? {} : { id: entity.id }), + ...(layout === undefined ? {} : { layout }), + }, + style, + picture: tablePicture(entity, style, measures), + }); + }); + }); + return out; +} diff --git a/src/tables.ts b/src/tables.ts new file mode 100644 index 0000000..da6fb5f --- /dev/null +++ b/src/tables.ts @@ -0,0 +1,794 @@ +// What a table needs worked out: the keys of the handles of a table style, of the dictionary that +// holds the styles and of a table's picture, the cell style of each kind of row, and where each +// cell of a table is once its spans are taken. +import type { Matrix } from "./blocks.ts"; +import type { + Insert, + Paragraph, + Point, + ParagraphAlign, + ParagraphVerticalAlign, + Table, + TableCell, + TableCellContent, + TableCellStyle, + TableStyle, +} from "./drawing.ts"; +import type { Block, TableOptions, TextStyle } from "./drawing.ts"; +import { boxer } from "./extents.ts"; +import { layerKey } from "./layers.ts"; +import { TABLE_CELLS, tableProblem, tableStyleProblem } from "./rules.ts"; +import { filled, Strings } from "./shape.ts"; +import { keyHandle } from "./handles.ts"; +import { layoutCellText, paragraphDirection, paragraphInStyle, placer } from "./paragraphs.ts"; + +/** The leading CAD app's own table style, which the writers add with a drawing's first. */ +export const STANDARD_TABLE_STYLE = "Standard"; + +/** The sizes of the leading CAD app's own table style, which the writers add with a drawing's first. */ +export const STANDARD_TABLE_STYLE_SIZES: TableStyle = { + name: STANDARD_TABLE_STYLE, + textHeight: 0.18, + horizontalMargin: 0.06, + verticalMargin: 0.06, + title: { textHeight: 0.25 }, +}; + +/** The name of the dictionary of table styles, as the leading CAD app names it. */ +export const TABLE_STYLE_DICTIONARY = "ACAD_TABLESTYLE"; + +/** The kinds of row, in the order a table style holds their cell styles in a file. */ +export const TABLE_ROW_KINDS = ["data", "title", "header"] as const; +export type TableRowKind = (typeof TABLE_ROW_KINDS)[number]; + +/** A name with A to Z in lower case, as the keys of the handles hold it. */ +function lower(name: string): string { + return name.replace(/[A-Z]/g, (letter) => letter.toLowerCase()); +} + +/** The handle of a table style whose name the rules have passed. */ +export function validTableStyleHandle(name: string): string { + return keyHandle(`table-style:${lower(name)}`); +} + +/** The handle of the dictionary of table styles. */ +export function tableStyleDictionaryHandle(): string { + return keyHandle("dictionary:acad_tablestyle"); +} + +/** Where a table is: its id, or its index among the entities of model space or of a layout. */ +export interface TablePlace { + readonly id?: string; + readonly layout?: string; + readonly index: number; +} + +/** + * The key of a part of a table's picture: the table's id with A to Z in lower case, or `@`, its + * layout's name in lower case, `/` and its index for one without an id. An id holds neither `@` + * nor `/`, and a layout's name holds no `/`. + */ +export function tablePictureKey(place: TablePlace, part: string): string { + const who = + place.id !== undefined + ? lower(place.id) + : `@${place.layout === undefined ? "" : lower(place.layout)}/${place.index}`; + return `table-picture:${who}/${part}`; +} + +/** The handle of a part of a table's picture: `record`, `begin`, `end`, or a part it draws. */ +export function tablePictureHandle(place: TablePlace, part: string): string { + return keyHandle(tablePictureKey(place, part)); +} + +/** A cell style with every field it can default filled in from its table style. */ +export interface CellStyleHeld { + readonly textStyle: string | undefined; + readonly textHeight: number; + readonly align: ParagraphAlign; + readonly valign: ParagraphVerticalAlign; + readonly color: number | undefined; + readonly fill: number | undefined; + readonly lineweight: number | undefined; +} + +/** Where each kind of row puts its content, unless its cell style says otherwise. */ +const PLACE: Record = { + title: ["center", "middle"], + header: ["center", "middle"], + data: ["center", "top"], +}; + +/** The cell style of one kind of row of a table style. */ +export function cellStyleOf(style: TableStyle, kind: TableRowKind): CellStyleHeld { + const own: TableCellStyle = style[kind] ?? {}; + return { + textStyle: own.textStyle ?? style.textStyle, + textHeight: own.textHeight ?? style.textHeight, + align: own.align ?? PLACE[kind][0], + valign: own.valign ?? PLACE[kind][1], + color: own.color, + fill: own.fill, + lineweight: own.lineweight, + }; +} + +/** A table style's margins: across, then up and down. */ +export function tableMargins(style: TableStyle): readonly [number, number] { + return [ + style.horizontalMargin ?? style.textHeight / 3, + style.verticalMargin ?? style.textHeight / 3, + ]; +} + +/** A cell as the grid holds it: where it starts, how far it reaches and what it holds. */ +export interface GridCell { + readonly row: number; + readonly column: number; + readonly rows: number; + readonly columns: number; + readonly kind: TableRowKind; + readonly content: TableCellContent; +} + +/** The content of a cell given as a string or an object. */ +export function cellContent(cell: TableCell): TableCellContent { + return typeof cell === "string" ? { text: cell } : cell; +} + +/** + * The rows of a table as a file holds them, from the top: the title, the header, then the data + * rows, each with its kind and the least height given for it. + */ +export function tableRows(table: Table): { + readonly kind: TableRowKind; + readonly cells: readonly (TableCell | null)[]; + readonly height: number | undefined; +}[] { + const out: { + kind: TableRowKind; + cells: readonly (TableCell | null)[]; + height: number | undefined; + }[] = []; + const count = table.columns.length; + if (table.title !== undefined) { + const cells: (TableCell | null)[] = [ + typeof table.title === "string" + ? { text: table.title, columnSpan: count } + : { ...table.title, columnSpan: count }, + ]; + for (let c = 1; c < count; c++) cells.push(null); + out.push({ kind: "title", cells, height: table.titleHeight }); + } + if (table.header !== undefined) { + out.push({ kind: "header", cells: table.header, height: table.headerHeight }); + } + table.rows.forEach((cells, r) => { + const height = table.rowHeights?.[r]; + out.push({ kind: "data", cells, height: height === null ? undefined : height }); + }); + return out; +} + +/** + * Each cell that starts a span, or stands alone, in reading order. The rules have checked that + * every row holds a cell for each column, that a span stays inside the table and inside the + * header or the data, and that the cells a span covers are `null`. + */ +export function gridCells(table: Table): GridCell[] { + const out: GridCell[] = []; + tableRows(table).forEach(({ kind, cells }, row) => { + cells.forEach((cell, column) => { + if (cell === null) return; + const content = cellContent(cell); + out.push({ + row, + column, + rows: content.rowSpan ?? 1, + columns: content.columnSpan ?? 1, + kind, + content, + }); + }); + }); + return out; +} + +/** A line of a table's picture: a side of a cell, in the table's own coordinates. */ +export interface TableLine { + readonly from: Point; + readonly to: Point; + /** Its lineweight in millimetres, or undefined for its table's. */ + readonly lineweight: number | undefined; +} + +/** A cell's text where the picture holds it: a paragraph held at `at` by `align` and `valign`. */ +export interface TableText { + readonly row: number; + readonly column: number; + readonly at: Point; + readonly value: string; + readonly height: number; + readonly width: number; + readonly align: ParagraphAlign; + readonly valign: ParagraphVerticalAlign; + readonly textStyle: string | undefined; + readonly color: number | undefined; +} + +/** A block in a cell, where the picture inserts it. */ +export interface TableBlock { + readonly row: number; + readonly column: number; + readonly block: string; + readonly at: Point; + readonly scale: number; + /** What the block draws, in its own coordinates before its scale, or undefined for nothing. */ + readonly box?: readonly [number, number, number, number]; +} + +/** A cell's fill: its box, `[left, bottom, right, top]`, and its color index. */ +export interface TableFill { + readonly row: number; + readonly column: number; + readonly box: readonly [number, number, number, number]; + readonly color: number; +} + +/** + * What the leading CAD app draws for a table, in the table's own coordinates: X to the right and Y + * up from its upper left corner, so every row is below 0. `rows` and `columns` are the height of + * each row and the width of each column as the file holds them. + */ +export interface TablePicture { + readonly rows: readonly number[]; + readonly columns: readonly number[]; + readonly fills: readonly TableFill[]; + readonly lines: readonly TableLine[]; + readonly texts: readonly TableText[]; + readonly blocks: readonly TableBlock[]; +} + +/** What `tablePicture` needs to measure a cell's text and to place a block. */ +export interface TableMeasures { + /** The height a text takes: its paragraph's box, from its first line's top to its last line's bottom. */ + readonly textHeight: (text: TableText) => number; + /** A block's box in its own coordinates, `[left, bottom, right, top]`, or undefined for none. */ + readonly blockBox: (name: string) => readonly [number, number, number, number] | undefined; +} + +/** The picture of a table the rules refuse. */ +const NOTHING: TablePicture = { + rows: [], + columns: [], + fills: [], + lines: [], + texts: [], + blocks: [], +}; + +/** How tall a row is for each line of text at least, in text heights. */ +const ROW_LINE = 4 / 3; + +/** + * The picture of a table: the height of each row, its fills, its lines, and where each cell's + * text and block go. A table or a style that `tableProblem` or `tableStyleProblem` refuses has + * an empty picture. + */ +export function tablePicture( + table: Table, + style: TableStyle, + measures: TableMeasures, +): TablePicture { + // A table or a style the rules refuse draws nothing, so no walk reads what it cannot bound. + if (tableProblem(table) !== undefined || tableStyleProblem(style) !== undefined) return NOTHING; + const [hm, vm] = tableMargins(style); + const rows = tableRows(table); + const cells = gridCells(table); + const columns = table.columns; + const styles = { + title: cellStyleOf(style, "title"), + header: cellStyleOf(style, "header"), + data: cellStyleOf(style, "data"), + }; + // Where each column starts, added up once from the left, in the order a sum from 0 takes. + const lefts = [0]; + for (let c = 0; c < columns.length; c++) lefts.push(lefts[c]! + columns[c]!); + const left = (column: number): number => lefts[column]!; + const widthOf = (cell: GridCell): number => { + let w = 0; + for (let c = cell.column; c < cell.column + cell.columns; c++) w += columns[c]!; + return w; + }; + const textOf = (cell: GridCell): TableText | undefined => { + const own = styles[cell.kind]; + const value = cell.content.text; + if (value === undefined || value === "" || cell.content.block !== undefined) return undefined; + return { + row: cell.row, + column: cell.column, + at: [0, 0], + value, + height: cell.content.textHeight ?? own.textHeight, + width: widthOf(cell) - 2 * hm, + align: cell.content.align ?? own.align, + valign: cell.content.valign ?? own.valign, + textStyle: own.textStyle, + color: cell.content.color ?? own.color, + }; + }; + /** A block's box in its own coordinates and the scale it is drawn at in a cell of this size. */ + const blockFit = ( + cell: GridCell, + room: readonly [number, number], + ): + | { + readonly box: readonly [number, number, number, number]; + readonly drawn: readonly [number, number, number, number] | undefined; + readonly scale: number; + } + | undefined => { + const name = cell.content.block; + if (name === undefined) return undefined; + const drawn = measures.blockBox(name); + const box = drawn ?? [0, 0, 0, 0]; + const size = [box[2] - box[0], box[3] - box[1]] as const; + // Fitted by each side that has a size, so a line fits along its length; a point keeps 1. + const fits = [0, 1].filter((i) => size[i]! > 0).map((i) => room[i]! / size[i]!); + const scale = cell.content.blockScale ?? (fits.length > 0 ? Math.min(...fits) : 1); + return { box, drawn, scale }; + }; + /** The height a cell's content needs: its text's, or its block's at its scale. */ + const contentHeight = (cell: GridCell, roomAcross: number): number | undefined => { + if (cell.content.block !== undefined) { + if (cell.content.blockScale === undefined) return undefined; + const fit = blockFit(cell, [roomAcross, 0]); + return fit === undefined ? undefined : (fit.box[3] - fit.box[1]) * fit.scale; + } + const text = textOf(cell); + // A text takes at least a line of its own height. + return text === undefined + ? undefined + : Math.max(measures.textHeight(text), ROW_LINE * text.height); + }; + /** Where a cell's block goes: its box placed in the cell, less the margins, as its text would be. */ + const blockOf = ( + cell: GridCell, + box: readonly [number, number, number, number], + ): TableBlock | undefined => { + const room: readonly [number, number] = [box[2] - box[0] - 2 * hm, box[3] - box[1] - 2 * vm]; + const fit = blockFit(cell, room); + if (fit === undefined) return undefined; + const own = styles[cell.kind]; + const align = cell.content.align ?? own.align; + const valign = cell.content.valign ?? own.valign; + const [b0, b1, b2, b3] = fit.box.map((v) => v * fit.scale) as unknown as [ + number, + number, + number, + number, + ]; + const x = + align === "left" + ? box[0] + hm - b0 + : align === "right" + ? box[2] - hm - b2 + : (box[0] + box[2]) / 2 - (b0 + b2) / 2; + const y = + valign === "top" + ? box[3] - vm - b3 + : valign === "bottom" + ? box[1] + vm - b1 + : (box[1] + box[3]) / 2 - (b1 + b3) / 2; + return { + row: cell.row, + column: cell.column, + block: cell.content.block!, + at: [x, y], + scale: fit.scale, + ...(fit.drawn === undefined ? {} : { box: fit.drawn }), + }; + }; + // Each row at least as tall as a line of its text, then as its own cells need. + const heights = rows.map(({ kind, height }) => { + const least = ROW_LINE * styles[kind].textHeight + 2 * vm; + return Math.max(height ?? 0, least); + }); + for (const cell of cells) { + if (cell.rows !== 1) continue; + const content = contentHeight(cell, widthOf(cell) - 2 * hm); + if (content === undefined) continue; + const need = content + 2 * vm; + if (need > heights[cell.row]!) heights[cell.row] = need; + } + // A cell over several rows grows the last of them. + for (const cell of cells) { + if (cell.rows === 1) continue; + const content = contentHeight(cell, widthOf(cell) - 2 * hm); + if (content === undefined) continue; + const need = content + 2 * vm; + let have = 0; + for (let r = cell.row; r < cell.row + cell.rows; r++) have += heights[r]!; + if (need > have) heights[cell.row + cell.rows - 1]! += need - have; + } + // Where each row starts, added up once from the top. + const tops = [0]; + for (let r = 0; r < heights.length; r++) tops.push(tops[r]! - heights[r]!); + const top = (row: number): number => tops[row]!; + const boxOf = (cell: GridCell): readonly [number, number, number, number] => { + const x0 = left(cell.column); + const y1 = top(cell.row); + let h = 0; + for (let r = cell.row; r < cell.row + cell.rows; r++) h += heights[r]!; + return [x0, y1 - h, x0 + widthOf(cell), y1]; + }; + const fills: TableFill[] = []; + const texts: TableText[] = []; + const blocks: TableBlock[] = []; + for (const cell of cells) { + const box = boxOf(cell); + const fill = cell.content.fill ?? styles[cell.kind].fill; + if (fill !== undefined) fills.push({ row: cell.row, column: cell.column, box, color: fill }); + const text = textOf(cell); + if (text !== undefined) { + const x = + text.align === "left" + ? box[0] + hm + : text.align === "right" + ? box[2] - hm + : (box[0] + box[2]) / 2; + const y = + text.valign === "top" + ? box[3] - vm + : text.valign === "bottom" + ? box[1] + vm + : (box[1] + box[3]) / 2; + texts.push({ ...text, at: [x, y] }); + } + const placed = blockOf(cell, box); + if (placed !== undefined) blocks.push(placed); + } + // Which cell holds each place of the grid, by its index in `cells`. + const owner = new Int32Array(rows.length * columns.length).fill(-1); + cells.forEach((cell, i) => { + for (let r = cell.row; r < cell.row + cell.rows; r++) { + for (let c = cell.column; c < cell.column + cell.columns; c++) + owner[r * columns.length + c] = i; + } + }); + const ownerAt = (row: number, column: number): number => owner[row * columns.length + column]!; + const weightOf = (row: number): number | undefined => styles[rows[row]!.kind].lineweight; + const lines: TableLine[] = []; + /** + * Joins the pieces of one line of the grid: each piece that is drawn, with its lineweight, runs + * on from the one before while the two share a lineweight, as the leading CAD app joins them. + */ + const join = ( + count: number, + drawn: (i: number) => boolean, + weight: (i: number) => number | undefined, + at: (i: number) => number, + make: (from: number, to: number, lineweight: number | undefined) => TableLine, + ): void => { + let start: number | undefined; + let held: number | undefined; + for (let i = 0; i <= count; i++) { + const open = i < count && drawn(i); + const w = open ? weight(i) : undefined; + if (start !== undefined && (!open || w !== held)) { + lines.push(make(start, at(i), held)); + start = undefined; + } + if (open && start === undefined) { + start = at(i); + held = w; + } + } + }; + for (let r = 0; r <= rows.length; r++) { + const y = top(r); + // A row's top is drawn where the cell above it is not the cell below it. + join( + columns.length, + (c) => r === 0 || r === rows.length || ownerAt(r - 1, c) !== ownerAt(r, c), + () => weightOf(Math.min(r, rows.length - 1)), + left, + (from, to, lineweight) => ({ from: [from, y], to: [to, y], lineweight }), + ); + } + for (let c = 0; c <= columns.length; c++) { + const x = left(c); + join( + rows.length, + (r) => c === 0 || c === columns.length || ownerAt(r, c - 1) !== ownerAt(r, c), + weightOf, + top, + (from, to, lineweight) => ({ from: [x, from], to: [x, to], lineweight }), + ); + } + return { rows: heights, columns, fills, lines, texts, blocks }; +} + +/** + * The measures of a drawing's tables: each text laid out as a paragraph in its style, from the top + * of its first line's capitals to its last baseline, and each block's box from `blockBox`. + */ +export function tableMeasures( + styleOf: (name: string | undefined) => TextStyle | undefined, + blockBox: TableMeasures["blockBox"], +): TableMeasures { + return { + textHeight: (text) => { + const layout = layoutCellText( + paragraphInStyle( + { value: text.value, height: text.height, width: text.width }, + styleOf(text.textStyle), + ), + ); + return layout.frame[3] - layout.frame[1]; + }, + blockBox, + }; +} + +/** Where a table's picture puts a point of its own coordinates: turned by its rotation, at `at`. */ +export function tableMatrix(table: Table): Matrix { + const [cos, sin] = paragraphDirection(table.rotation); + return [cos, sin, -sin, cos, table.at[0], table.at[1]]; +} + +/** + * The box of what a table draws, in the drawing's coordinates, or undefined for nothing: its + * grid, each cell's text's ink, and the box of each cell's block at its scale and place. A + * block's box is the whole of what it draws, as its fit takes it, so a layer turned off inside it + * still counts. `styleOf` gives a text style by its name. `blockBox`, given, boxes what a block + * draws where that is more than it was fitted by, such as what it draws through an xref. + */ +export function tableBox( + table: Table, + picture: TablePicture, + styleOf: (name: string | undefined) => TextStyle | undefined, + blockBox?: (name: string) => readonly [number, number, number, number] | undefined, +): [number, number, number, number] | undefined { + const box: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]; + const [a, b, c, d, x0, y0] = tableMatrix(table); + const add = (x: number, y: number): void => { + const px = a * x + c * y + x0; + const py = b * x + d * y + y0; + box[0] = Math.min(box[0], px); + box[1] = Math.min(box[1], py); + box[2] = Math.max(box[2], px); + box[3] = Math.max(box[3], py); + }; + let width = 0; + for (const w of picture.columns) width += w; + let height = 0; + for (const h of picture.rows) height += h; + if (picture.columns.length > 0) { + add(0, 0); + add(width, 0); + add(width, -height); + add(0, -height); + } + for (const text of picture.texts) { + const paragraph = tableParagraph(table, text); + const layout = layoutCellText(paragraphInStyle(paragraph, styleOf(text.textStyle))); + if (!layout.ink) continue; + const place = placer(paragraph); + const [i0, j0, i1, j1] = layout.ink; + // Already in the drawing's coordinates, so each goes in as it is. + for (const [x, y] of [place(i0, j0), place(i1, j0), place(i1, j1), place(i0, j1)]) { + box[0] = Math.min(box[0], x); + box[1] = Math.min(box[1], y); + box[2] = Math.max(box[2], x); + box[3] = Math.max(box[3], y); + } + } + for (const block of picture.blocks) { + const drawn = blockBox ? blockBox(block.block) : block.box; + if (drawn === undefined) continue; + const [x, y] = block.at; + const s = block.scale; + const [b0, b1, b2, b3] = drawn; + add(x + s * b0, y + s * b1); + add(x + s * b2, y + s * b1); + add(x + s * b2, y + s * b3); + add(x + s * b0, y + s * b3); + } + return box[0] === Infinity ? undefined : box; +} + +/** A cell's text as a paragraph, where the picture places it in the table's space. */ +export function tableParagraph(table: Table, text: TableText): Paragraph { + const [a, b, c, d, e, f] = tableMatrix(table); + const [x, y] = text.at; + return { + kind: "paragraph", + layer: table.layer, + at: [a * x + c * y + e, b * x + d * y + f], + height: text.height, + value: text.value, + rotation: table.rotation ?? 0, + width: text.width, + ...(text.textStyle === undefined ? {} : { style: text.textStyle }), + align: text.align, + valign: text.valign, + }; +} + +/** The insert of each block a table's cells hold, where the picture places it, on the table's layer. */ +export function tableInserts(table: Table, picture: TablePicture): Insert[] { + const [a, b, c, d, e, f] = tableMatrix(table); + return picture.blocks.map((block) => { + const [x, y] = block.at; + return { + kind: "insert", + layer: table.layer, + block: block.block, + at: [a * x + c * y + e, b * x + d * y + f], + scale: [block.scale, block.scale], + ...(table.rotation === undefined || table.rotation === 0 ? {} : { rotation: table.rotation }), + }; + }); +} + +/** A table's size, as `measureTable` gives it. */ +export interface TableMeasure { + /** How wide it is: its columns' widths added up. */ + readonly width: number; + /** How tall it is: its rows' heights added up, each as tall as its cells need. */ + readonly height: number; + /** The height of each row, from the top: the title's, the header's, then each data row's. */ + readonly rows: readonly number[]; + readonly columns: readonly number[]; +} + +/** + * How large a table is drawn in its style, with each row as tall as its cells need, as the leading + * CAD app lays it out: for placing what goes below or beside it. `textStyles` and `blocks` are + * the drawing's, which its style and its cells name. + * + * ```ts + * const { height } = measureTable(schedule, SCHEDULE_STYLE, textStyles); + * ``` + */ +export function measureTable( + table: TableOptions, + style: TableStyle, + textStyles: readonly TextStyle[] = [], + blocks: readonly Block[] = [], +): TableMeasure { + const named = (name: string | undefined) => + name === undefined ? undefined : textStyles.find((t) => layerKey(t.name) === layerKey(name)); + // One boxer for the call, which keeps the box of each block it reads. + const box = boxer(textStyles, blocks); + const known = new Map(); + const picture = tablePicture( + { ...table, kind: "table", layer: "0" }, + style, + tableMeasures(named, (name) => { + const k = layerKey(name); + if (!known.has(k)) + known.set(k, box([{ kind: "insert", layer: "0", block: name, at: [0, 0] }])); + return known.get(k); + }), + ); + return { + width: picture.columns.reduce((sum, w) => sum + w, 0), + height: picture.rows.reduce((sum, h) => sum + h, 0), + rows: picture.rows, + columns: picture.columns, + }; +} + +/** The shortest text of a cell that `tableRepeats` tells apart by its value. */ +const LONG = 256; + +/** + * For the tables of one call, what reading a table again costs when it shares its rows, a row, a + * cell or a text of `LONG` characters or more with a table read before, as a drawing made in code + * may: a unit for each row and each cell, and one for each 32 characters of a text. 0 for a table + * that shares none, whose lists the drawing holds. A table of more cells than the rules allow + * costs nothing here, since nothing reads its cells. + */ +export function tableRepeats(): (table: unknown) => number { + const lists = new WeakMap(); + const cells = new WeakSet(); + const texts = new Strings(); + const text = (value: unknown): [number, boolean] => { + if (typeof value !== "string") return [1, false]; + const long = value.length >= LONG; + const again = long && (texts.get(value) !== undefined || texts.clashes(value)); + if (long) texts.set(value, true); + return [1 + Math.floor(value.length / 32), again]; + }; + const cell = (value: unknown): [number, boolean] => { + if (typeof value === "string") return text(value); + if (typeof value !== "object" || value === null) return [1, false]; + const again = cells.has(value); + cells.add(value); + const [cost, shared] = text((value as { text?: unknown }).text); + return [cost, again || shared]; + }; + const read = (list: unknown, item: (value: unknown) => [number, boolean]): [number, boolean] => { + if (!Array.isArray(list)) return [0, false]; + const known = lists.get(list); + if (known) return [known.cost, true]; + let cost = 0; + let shares = false; + for (const value of filled(list)) { + const [more, again] = item(value); + cost += more; + shares ||= again; + } + lists.set(list, { cost, shares }); + return [cost, shares]; + }; + const row = (value: unknown): [number, boolean] => { + const [cost, shares] = read(value, cell); + return [1 + cost, shares]; + }; + return (table) => { + if (typeof table !== "object" || table === null) return 0; + const t = table as { rows?: unknown; header?: unknown; columns?: unknown; title?: unknown }; + const width = Array.isArray(t.columns) ? t.columns.length : 0; + const height = + (Array.isArray(t.rows) ? t.rows.length : 0) + + (t.header === undefined ? 0 : 1) + + (t.title === undefined ? 0 : 1); + if (width === 0 || width * height > TABLE_CELLS) return 0; + const [ofRows, sharedRows] = read(t.rows, row); + const [ofHeader, sharedHeader] = row(t.header); + const [ofTitle, sharedTitle] = cell(t.title); + return sharedRows || sharedHeader || sharedTitle ? ofRows + ofHeader + ofTitle : 0; + }; +} + +/** + * What reading a table's cells costs, before any of them is read: a unit for each cell and one for + * each 32 characters of its text. 0 for a table whose cells the rules refuse to read: one of more + * than `TABLE_CELLS` cells, or with no list of columns or rows. + */ +export function tableCost(table: unknown): number { + if (typeof table !== "object" || table === null) return 0; + const t = table as { columns?: unknown; rows?: unknown; header?: unknown; title?: unknown }; + if (!Array.isArray(t.columns) || !Array.isArray(t.rows)) return 0; + const width = t.columns.length; + const height = t.rows.length + (t.header === undefined ? 0 : 1) + (t.title === undefined ? 0 : 1); + // No column, or more cells than the rules allow: no row is read. + if (width === 0 || width * height > TABLE_CELLS) return 0; + const of = (cell: unknown): number => { + const text = typeof cell === "string" ? cell : (cell as { text?: unknown } | null)?.text; + return 1 + (typeof text === "string" ? Math.floor(text.length / 32) : 0); + }; + const row = (list: unknown): number => { + if (!Array.isArray(list)) return 0; + let cost = 0; + for (let c = 0; c < list.length && c < width; c++) cost += of(list[c]); + return cost; + }; + let cost = of(t.title) + row(t.header); + for (let r = 0; r < t.rows.length; r++) cost += row(t.rows[r]); + return cost; +} + +/** Each cell's text with the text style of its row and where it is, for `tableTextsProblem`. */ +export function tableTexts( + table: Table, + style: TableStyle, +): { readonly text: string; readonly textStyle: string | undefined; readonly at: string }[] { + const out: { text: string; textStyle: string | undefined; at: string }[] = []; + const first = (table.title === undefined ? 0 : 1) + (table.header === undefined ? 0 : 1); + for (const cell of gridCells(table)) { + const text = cell.content.text; + if (text === undefined || text === "") continue; + const at = + cell.kind === "title" + ? "title" + : cell.kind === "header" + ? `header[${cell.column}]` + : `rows[${cell.row - first}][${cell.column}]`; + out.push({ text, textStyle: cellStyleOf(style, cell.kind).textStyle, at }); + } + return out; +} diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 2344090..b5b61d6 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -2674,6 +2674,30 @@ test("a long paragraph value many places share is laid out once in each of its s assert.match(paid!.message, /stopped short at entity #1 of model space/); }); +test("lint pays for tables that share their rows or a long text, and stops where the writer would", () => { + const row = Array.from({ length: 1000 }, () => "CELL"); + const rows = Array.from({ length: 10 }, () => row); + const long = "WORD ".repeat(20_000); + for (const shared of [ + { columns: Array(1000).fill(0.5), rows }, + { columns: [1], rows: [[long]] }, + ]) { + const drawing = { + ...createDrawing({ units: "in" }).build(), + tableStyles: [{ name: "S", textHeight: 0.1 }], + entities: Array.from({ length: 2000 }, (_, i) => ({ + kind: "table", + layer: "0", + style: "S", + at: [i, 0], + ...shared, + })), + } as Drawing; + const found = within(3000, () => lint(drawing)); + assert.ok(found.some((d) => d.rule === "check-capped")); + } +}); + test("gradients that many hatches share, and a gradient of many fields, are checked and drawn in a bounded time", () => { const loops = [ { diff --git a/test/read-agreement.ts b/test/read-agreement.ts index e7efa7c..0808fea 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -28,14 +28,25 @@ import { idHandle } from "../src/handles.ts"; import { findLeaderStyle, leaderPicture } from "../src/leaders.ts"; import { fromImagePixels, imageClip, imageVectors, writtenImagePath } from "../src/images.ts"; import { layerKey } from "../src/layers.ts"; +import { boxer } from "../src/extents.ts"; import { entityLinetype, lineweightCode } from "../src/linetypes.ts"; import { paragraphAttachment, paragraphDirection, paragraphTurn } from "../src/paragraphs.ts"; import { textOnce, textTwice } from "../src/read/groups.ts"; +import { + cellStyleOf, + gridCells, + tableMargins, + tableMeasures, + tablePicture, + TABLE_ROW_KINDS, + tableRows, +} from "../src/tables.ts"; import type { DrawingRead, ReadAttribute, ReadAttributeParagraph, ReadEntity, + ReadTableCellStyle, ReadTextPlacement, } from "../src/read/model.ts"; @@ -98,6 +109,28 @@ export function readProblems( const dimensionStyles = new Map( (drawing.dimensionStyles ?? []).map((s) => [layerKey(s.name), s]), ); + const tableStyles = new Map((drawing.tableStyles ?? []).map((s) => [layerKey(s.name), s])); + let measures: ReturnType | undefined; + /** The measures the writer lays a table out by: each block's box, and each text's. */ + const tableMeasuresOf = (): ReturnType => { + if (measures) return measures; + const boxOf = boxer( + drawing.textStyles, + drawing.blocks, + undefined, + undefined, + undefined, + drawing.dimensionStyles, + drawing.leaderStyles, + ); + measures = tableMeasures(styleOf, (name) => { + const block = blocks.get(layerKey(name)); + return block === undefined + ? undefined + : boxOf([{ kind: "insert", layer: "0", block: block.name, at: [0, 0] }]); + }); + return measures; + }; /** A text's place: where its file puts it, and what it is justified to. */ const placement = ( @@ -287,7 +320,12 @@ export function readProblems( } if (got.color !== undefined || got.trueColor !== undefined) say(`${label}: has a color of its own`); - if (want.kind !== "insert" && want.kind !== "leader" && !isDimension(want)) { + if ( + want.kind !== "insert" && + want.kind !== "leader" && + want.kind !== "table" && + !isDimension(want) + ) { const linetype = entityLinetype(want); if (linetype === undefined ? got.linetype !== undefined : !sameName(got.linetype, linetype)) { say(`${label}: linetype ${got.linetype}, expected ${linetype}`); @@ -727,6 +765,97 @@ export function readProblems( } return; } + case "table": { + if (!kind("table") || got.kind !== "table") return; + const style = tableStyles.get(layerKey(want.style)); + if (!sameName(got.style, want.style)) say(`${label}: style ${got.style}`); + if (!style) return; + if (!nearPoint(got.at, point(want.at))) say(`${label}: at ${got.at}`); + // Its direction is written with 15 digits. + const [cos, sin] = paragraphDirection(want.rotation); + if (Math.abs(got.direction[0] - cos) > 1e-12 || Math.abs(got.direction[1] - sin) > 1e-12) + say(`${label}: runs along ${got.direction}`); + if (got.title !== (want.title !== undefined)) say(`${label}: title ${got.title}`); + if (got.header !== (want.header !== undefined)) say(`${label}: header ${got.header}`); + // The leading CAD app lays the table out again, within the rounding of 6 decimals. + const picture = tablePicture(want, style, tableMeasuresOf()); + for (const [what, a, b] of [ + ["rows", got.rows, picture.rows], + ["columns", got.columns, picture.columns], + ] as const) { + if (a.length !== b.length || a.some((n, i) => !near(n, written(b[i]!), by === "cad"))) + say(`${label}: ${what} ${a.join(", ")}, expected ${b.map(written).join(", ")}`); + } + const rows = tableRows(want); + const cells = gridCells(want); + if (got.cells.length !== cells.length) { + say(`${label}: ${got.cells.length} cells, expected ${cells.length}`); + } + cells.forEach((cell, i) => { + const read = got.cells[i]; + const at = `${label} cell ${cell.row}/${cell.column}`; + if (!read) return say(`${at}: missing`); + const { content } = cell; + if ( + read.row !== cell.row || + read.column !== cell.column || + read.rowSpan !== cell.rows || + read.columnSpan !== cell.columns + ) + say(`${at}: at ${read.row}/${read.column} over ${read.rowSpan} by ${read.columnSpan}`); + const block = + content.block === undefined ? undefined : blocks.get(layerKey(content.block)); + const text = block === undefined && content.text !== "" ? content.text : undefined; + if (read.text !== (text === undefined ? undefined : once(text))) + say(`${at}: reads ${JSON.stringify(read.text)}`); + if (block ? !sameName(read.block, block.name) : read.block !== undefined) + say(`${at}: holds the block ${read.block}`); + const scale = block === undefined ? undefined : content.blockScale; + if ( + (read.blockScale === undefined) !== (scale === undefined) || + (scale !== undefined && !near(read.blockScale!, written(scale))) + ) + say(`${at}: block scale ${read.blockScale}`); + const own = cellStyleOf(style, rows[cell.row]!.kind); + const alignment = + content.align === undefined && content.valign === undefined + ? undefined + : paragraphAttachment({ + align: content.align ?? own.align, + valign: content.valign ?? own.valign, + }); + for (const [what, a, b] of [ + ["alignment", read.alignment, alignment], + [ + "text height", + read.textHeight, + content.textHeight === undefined ? undefined : written(content.textHeight), + ], + ["color", read.color, content.color], + ["fill", read.fill, content.fill], + ] as const) { + if ((a === undefined) !== (b === undefined) || (a !== undefined && !near(a, b!))) + say(`${at}: ${what} ${a}, expected ${b}`); + } + }); + if (got.block === undefined || !got.blockHandle) { + say(`${label}: names no block of its picture`); + return; + } + if (by === "tsdraft" && !/^\*T\d+$/.test(got.block)) say(`${label}: drawn by ${got.block}`); + const drawn = read.blocks.find((b) => b.handle === got.blockHandle); + if (!drawn || !sameName(drawn.name, got.block)) say(`${label}: its block is not read`); + else if (by === "tsdraft") { + const count = + picture.fills.length + + picture.lines.length + + picture.texts.length + + picture.blocks.filter((b) => blocks.has(layerKey(b.block))).length; + if (drawn.entities.length !== count) + say(`${label}: its block draws ${drawn.entities.length}, expected ${count}`); + } + return; + } case "image": { if (!kind("image") || got.kind !== "image") return; if (got.path !== writtenImagePath(want.path)) @@ -862,6 +991,41 @@ export function readProblems( } else start(read, mine?.attributeDefinitions[i], read.default ?? "", label); }); } + /** A cell style as the read holds it, against the style's of that kind of row. */ + const cellStyle = ( + got: ReadTableCellStyle, + want: ReturnType, + label: string, + ): void => { + if (!sameName(got.textStyle, want.textStyle ?? "Standard")) + say(`${label}: text style ${got.textStyle}`); + const weight = want.lineweight === undefined ? -2 : lineweightCode(want.lineweight); + for (const [what, a, b] of [ + ["text height", got.textHeight, written(want.textHeight)], + ["alignment", got.alignment, paragraphAttachment(want)], + ["color", got.color, want.color ?? 0], + ["lineweight", got.lineweight, weight], + ] as const) { + if (!near(a, b)) say(`${label}: ${what} ${a}, expected ${b}`); + } + if (got.fill !== want.fill) say(`${label}: fill ${got.fill}, expected ${want.fill}`); + }; + for (const style of drawing.tableStyles ?? []) { + const label = `table style ${style.name}`; + const got = read.tableStyles.find((s) => sameName(s.name, style.name)); + if (!got) { + say(`${label}: missing`); + continue; + } + const [horizontal, vertical] = tableMargins(style); + if ( + !near(got.horizontalMargin, written(horizontal)) || + !near(got.verticalMargin, written(vertical)) + ) + say(`${label}: margins ${got.horizontalMargin} and ${got.verticalMargin}`); + for (const kind of TABLE_ROW_KINDS) + cellStyle(got[kind], cellStyleOf(style, kind), `${label} ${kind}`); + } if (Object.keys(read.unread.malformed).length > 0) { say(`malformed: ${JSON.stringify(read.unread.malformed)}`); } diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index fcae915..c41b07c 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -84,6 +84,25 @@ export function seedFiles(): Uint8Array[] { }); images.insert("LOGO", [0, 10]); }); + // Tables of two styles, with spans, blocks, fills and a cell's own sizes. + const tables = createDrawing({ units: "in" }); + tables.block("TAG", {}, () => tables.circle([0, 0], 0.2)); + tables.tableStyle({ name: "PLAIN", textHeight: 0.18, header: { fill: 8, lineweight: 0.35 } }); + tables.table({ + style: "PLAIN", + at: [0, 10], + rotation: 30, + columns: [0.6, 1.1], + title: "SCHEDULE", + header: ["MARK", { block: "TAG" }], + rows: [ + [ + { text: "D1", rowSpan: 2, align: "left" }, + { block: "TAG", blockScale: 0.5 }, + ], + [null, { text: "A LONG NOTE\\PTWO", fill: 3, color: 1, textHeight: 0.1 }], + ], + }); // Ellipses and splines of each kind, in model space and in a block. const curves = createDrawing({ units: "ft" }); curves.block("CURVE", {}, () => curves.layer("0", {}, () => curves.ellipse([0, 0], [2, 1], 0.5))); @@ -134,6 +153,7 @@ export function seedFiles(): Uint8Array[] { toDXF(kitchen), toDXF(d.build(), { version: "R12" }), toDXF(images.build()), + toDXF(tables.build()), toDXF(curves.build()), ].map((t) => encoder.encode(t)), leaderFile(), diff --git a/test/read.test.ts b/test/read.test.ts index 331a6fc..f6f507f 100644 --- a/test/read.test.ts +++ b/test/read.test.ts @@ -857,6 +857,118 @@ test("readDXF with geometry gives back every entity of both examples", async () assert.deepEqual(read.opensAt, { layout: "C-101", center: [18, 12], height: 26.4, width: 42.24 }); }); +test("readDXF with geometry reads each table as its Table, with its style and its picture", async () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "ARIALS", font: "Arial" }); + d.block("TAG", {}, () => d.circle([0, 0], 0.2)); + d.tableStyle({ name: "PLAIN", textHeight: 0.18, title: { textHeight: 0.25 } }); + d.tableStyle({ + name: "SCHED", + textStyle: "ARIALS", + textHeight: 0.1, + horizontalMargin: 0.05, + header: { fill: 8, lineweight: 0.35, color: 5 }, + data: { align: "left", valign: "middle" }, + }); + d.table({ + style: "PLAIN", + at: [1, 10], + columns: [0.6, 1.1, 1.6], + title: "DOOR SCHEDULE", + header: ["MARK", { text: "SIZE", columnSpan: 2 }, null], + rows: [ + [{ text: "D1", rowSpan: 2 }, { block: "TAG" }, { block: "TAG", blockScale: 0.5 }], + [ + null, + { text: "{\\C1;RED}", fill: 3, color: 2 }, + { text: "", textHeight: 0.3, align: "right" }, + ], + ], + rowHeights: [0.5, null], + }); + d.table({ style: "SCHED", at: [6, 10], rotation: 30, columns: [1, 1], rows: [["A", "B"]] }); + d.layout("SHEET", { paper: "ANSI B" }, () => { + d.table({ style: "SCHED", at: [1, 8], columns: [2], title: "LONE", header: ["H"], rows: [] }); + }); + const drawing = d.build(); + const read = await readDXF(toDXF(drawing), { geometry: true }); + assert.deepEqual(checkDrawingRead(plain(read)), []); + assert.deepEqual(readProblems(drawing, read, "tsdraft"), []); + assert.deepEqual( + read.tableStyles.map((s) => s.name), + ["Standard", "PLAIN", "SCHED"], + ); + // Without geometry no table is kept, and neither is its picture. + const plainRead = await readDXF(toDXF(drawing)); + assert.equal(plainRead.blocks.filter((b) => b.name.startsWith("*T")).length, 0); + assert.equal(plainRead.tableStyles.length, 3); +}); + +test("readDXF counts a table past the core's limits or a read's, and never lists it", async () => { + type Pairs = (readonly [number, string | number])[]; + const cell = (text: string): Pairs => [ + [171, 1], + [175, 1], + [176, 1], + [91, 0], + [301, "CELL_VALUE"], + [1, text], + [304, "ACVALUE_END"], + ]; + const table = (rows: number, columns: number, cells: Pairs = [], heights = rows): Pairs => [ + [0, "ACAD_TABLE"], + [8, "0"], + [100, "AcDbBlockReference"], + [2, "*T1"], + [100, "AcDbTable"], + [280, 0], + [91, rows], + [92, columns], + ...Array.from({ length: heights }, (): [number, number] => [141, 0.3]), + ...Array.from({ length: Math.min(columns, 2000) }, (): [number, number] => [142, 1]), + ...cells, + ]; + const read = await readDXFWithin( + dxf([ + ...section( + "ENTITIES", + table(1, 1001), + table(400, 400, [], 0), + table(2000, 0), + table(2, 1, cell("ONE")), + table(1, 1, cell("X".repeat(32 * 1100))), + table(1, 1, cell("A")), + ), + [0, "EOF"], + ]), + { geometry: true }, + { ...READ_LIMITS, geometryItems: 1000 }, + ); + assert.deepEqual(plain(read.model.other), { + "ACAD_TABLE of more than 1000 columns": 1, + "ACAD_TABLE of more than 100000 cells": 1, + "ACAD_TABLE of more than 1000 rows": 1, + "past the limit": 1, + }); + assert.deepEqual(plain(read.unread.malformed), { + "ACAD_TABLE whose rows, columns or cells are not as many as it says": 1, + }); + assert.deepEqual(plain(read.model.entities), [ + { + layer: "0", + kind: "table", + at: [0, 0], + direction: [1, 0], + rows: [0.3], + columns: [1], + title: true, + header: false, + cells: [{ row: 0, column: 0, rowSpan: 1, columnSpan: 1, text: "A" }], + block: "*T1", + }, + ]); +}); + test("readDXF gives back a text that holds the leading CAD app's escapes as toDXF wrote it", async () => { const d = createDrawing({ units: "in" }); d.leaderStyle({ name: "NOTE", textHeight: 0.125, arrowSize: 0.125, landing: 0.125, gap: 0.0625 }); diff --git a/test/shape.test.ts b/test/shape.test.ts index 43bd620..056b855 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -22,6 +22,8 @@ import { type Layer, type Layout, type LeaderStyle, + type TableCellStyle, + type TableStyle, type Hatch, type HatchPattern, type Linetype, @@ -306,6 +308,27 @@ const kinds: { textBelow: "MIN.", id: "h-a", }, + table: { + kind: "table", + layer: "0", + style: "SCHEDULE", + at: [100, 20], + rotation: 0, + columns: [1, 2], + title: "DOORS", + titleHeight: 0.4, + header: [ + { text: "MARK", align: "left", valign: "bottom", textHeight: 0.1, color: 1, fill: 2 }, + "SIZE", + ], + headerHeight: 0.3, + rows: [ + [{ block: "TREE", blockScale: 0.5, columnSpan: 2, rowSpan: 2 }, null], + [null, null], + ], + rowHeights: [0.5, null], + id: "tb", + }, "ordinate-dimension": { kind: "ordinate-dimension", layer: "0", @@ -424,6 +447,9 @@ const full: Required & { Required>, ]; readonly leaderStyles: readonly [Required]; + readonly tableStyles: readonly [ + Required & { readonly data: Required }, + ]; readonly layers: readonly [Layer, Required]; readonly blocks: readonly [ Block, @@ -569,6 +595,26 @@ const full: Required & { scale: 10, }, ], + tableStyles: [ + { + name: "SCHEDULE", + textStyle: "NOTES", + textHeight: 0.1, + horizontalMargin: 0.03, + verticalMargin: 0.02, + title: { textHeight: 0.15 }, + header: { fill: 8 }, + data: { + textStyle: "NOTES", + textHeight: 0.08, + align: "left", + valign: "middle", + color: 3, + fill: 9, + lineweight: 0.25, + }, + }, + ], layers: [ { name: "0", color: 7 }, { @@ -854,7 +900,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #21: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #22: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ diff --git a/test/tables.test.ts b/test/tables.test.ts new file mode 100644 index 0000000..b890ba1 --- /dev/null +++ b/test/tables.test.ts @@ -0,0 +1,233 @@ +// Tables (docs/tables.md): the rules the reviews of the first tables proved, each with the +// smallest drawing that shows it. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { Script } from "node:vm"; +import { + createDrawing, + inspectText, + lint, + readDXF, + toDXF, + toSVG, + type Drawing, +} from "../src/index.ts"; +import { referencedByKey } from "../src/blocks.ts"; +import { extents } from "../src/extents.ts"; +import { tableCost, tableRepeats } from "../src/tables.ts"; +import { timeLimit } from "./time-limit.ts"; + +const running = new Script("running()"); +/** What `fn` gives, stopped after `ms`, so a run that never ends fails. */ +const within = (ms: number, fn: () => T): T => { + Object.assign(globalThis, { running: fn }); + return running.runInThisContext({ timeout: timeLimit(ms) }) as T; +}; +const boxOf = (d: Drawing, xrefs?: Parameters[1]) => + extents( + d.entities, + d.textStyles, + d.blocks, + undefined, + undefined, + xrefs && referencedByKey(d, xrefs), + undefined, + undefined, + undefined, + d.tableStyles, + ); + +/** A drawing whose one table holds the block `TAG`, a circle of radius 10, at a scale of 1. */ +function tagged(): Drawing { + const d = createDrawing({ units: "in" }); + d.block("TAG", {}, () => d.circle([0, 0], 10)); + d.tableStyle({ name: "S", textHeight: 1 }); + d.table({ style: "S", at: [0, 0], columns: [4], rows: [[{ block: "TAG", blockScale: 1 }]] }); + return d.build(); +} + +test("a referenced drawing's table draws and boxes the block in each of its cells", () => { + const source = tagged(); + const host = createDrawing({ units: "in" }); + host.xref("BASE", "base.dwg"); + host.insert("BASE", [100, 0]); + const drawn = host.build(); + const circles = (svg: string) => svg.match(/<(circle|ellipse)\b/g)?.length ?? 0; + assert.equal(circles(toSVG(source)), 1); + assert.equal(circles(toSVG(drawn, { xrefs: { BASE: source } })), 1); + const own = boxOf(source); + const placed = boxOf(drawn, { BASE: source }); + assert.deepEqual( + placed.map((v, i) => v - (i % 2 === 0 ? 100 : 0)), + own, + ); + assert.ok(own[0] < 0 && own[2] > 4, "the block reaches past its column"); +}); + +test("a referenced drawing's table draws one block in two cells twice", () => { + const d = createDrawing({ units: "in" }); + d.block("TAG", {}, () => d.circle([0, 0], 1)); + d.tableStyle({ name: "S", textHeight: 1 }); + d.table({ + style: "S", + at: [0, 0], + columns: [4, 4], + rows: [[{ block: "TAG" }, { block: "TAG" }]], + }); + const host = createDrawing({ units: "in" }); + host.xref("BASE", "base.dwg"); + host.insert("BASE", [100, 0]); + const svg = toSVG(host.build(), { xrefs: { BASE: d.build() } }); + assert.equal(svg.match(/<(circle|ellipse)\b/g)?.length ?? 0, 2); +}); + +test("a table's box holds what a cell's block draws through an xref", () => { + const far = createDrawing({ units: "in" }); + far.circle([1000, 0], 2); + const d = createDrawing({ units: "in" }); + d.xref("FAR", "far.dwg", { attach: true }); + d.block("TAG", {}, () => d.insert("FAR", [0, 0])); + d.tableStyle({ name: "S", textHeight: 1 }); + d.table({ style: "S", at: [0, 0], columns: [4], rows: [[{ block: "TAG", blockScale: 1 }]] }); + const schedule = d.build(); + const given = { FAR: far.build() }; + // The block draws nothing of its own, so it sits at its cell's top center, as the writers put it. + assert.ok(Math.abs(boxOf(schedule, given)[2] - 1004) < 1e-6); + // Referenced at x 100, the view held on the far circle draws it. + const host = createDrawing({ units: "in" }); + host.xref("BASE", "base.dwg"); + host.insert("BASE", [100, 0]); + const svg = toSVG(host.build(), { + xrefs: { BASE: { drawing: schedule, xrefs: given } }, + view: [1095, -10, 1110, 10], + }); + assert.equal(svg.match(/<(circle|ellipse)\b/g)?.length ?? 0, 1); +}); + +test("the extents box a table's blocks once, however many places draw the table", () => { + const d = createDrawing({ units: "in" }); + d.block("TAG", {}, () => d.circle([0, 0], 1)); + d.tableStyle({ name: "S", textHeight: 1 }); + d.table({ + style: "S", + at: [0, 0], + columns: Array(1000).fill(4), + rows: Array.from({ length: 50 }, () => Array(1000).fill({ block: "TAG" })), + }); + const one = d.build(); + const many = { ...one, entities: Array(3000).fill(one.entities[0]) }; + assert.deepEqual( + within(2000, () => boxOf(many)), + boxOf(one), + ); +}); + +test("lint refuses a cell's block that its fit would write at a scale of 0", () => { + const d = createDrawing({ units: "in" }); + d.block("ROAD", {}, () => d.line([0, 0], [1e8, 0])); + d.tableStyle({ name: "S", textHeight: 1 }); + d.table({ style: "S", at: [0, 0], columns: [4], rows: [[{ block: "ROAD" }]] }); + const found = lint(d.build()).filter((x) => x.rule === "table"); + assert.equal(found.length, 1); + assert.match(found[0]!.message, /ROAD.*scale cannot be 0/); +}); + +test("a table of no columns costs nothing to read, however many rows it has", () => { + const table = { + kind: "table", + layer: "0", + style: "S", + at: [0, 0], + columns: [], + rows: Array(2_000_000).fill([]), + } as never; + within(1000, () => { + assert.equal(tableCost(table), 0); + assert.equal(tableRepeats()(table), 0); + }); +}); + +test("a table's text keeps a caret, and a style may be named TEXT", async () => { + const d = createDrawing({ units: "in" }); + d.tableStyle({ name: "TEXT", textHeight: 1 }); + d.table({ style: "TEXT", at: [0, 0], columns: [8], rows: [["REV^A"]] }); + const read = await readDXF(toDXF(d.build()), { geometry: true }); + const table = (read.model.entities ?? []).find((e) => e.kind === "table"); + assert.equal(table?.kind === "table" && table.style, "TEXT"); + assert.equal(table?.kind === "table" && table.cells[0]?.text, "REV^A"); + assert.ok(read.tableStyles.some((s) => s.name === "TEXT")); +}); + +test("a row that names the Standard text style keeps it", async () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "Body", font: "Arial" }); + d.tableStyle({ + name: "Schedule", + textHeight: 1, + textStyle: "Body", + header: { textStyle: "Standard" }, + }); + d.table({ style: "Schedule", at: [0, 0], columns: [4], header: ["H"], rows: [["A"]] }); + const read = await readDXF(toDXF(d.build()), { geometry: true }); + assert.equal(read.tableStyles.find((s) => s.name === "Schedule")?.header.textStyle, "Standard"); +}); + +test("a fitted block fits by each side it has a size along, from its base", () => { + // A line fits along its length. + const line = createDrawing({ units: "in" }); + line.block("L", {}, () => line.line([0, 0], [100, 0])); + line.tableStyle({ name: "S", textHeight: 1 }); + line.table({ style: "S", at: [0, 0], columns: [4], rows: [[{ block: "L" }]] }); + const fitted = boxOf(line.build()); + assert.ok(fitted[0] >= -1e-9 && fitted[2] <= 4 + 1e-9, JSON.stringify(fitted)); + // A block whose base is away from what it draws is placed by what it draws. + const based = createDrawing({ units: "in" }); + based.block("B", { base: [10, 0] }, () => + based.polyline( + [ + [10, 0], + [11, 0], + [11, 1], + ], + false, + ), + ); + based.tableStyle({ name: "S", textHeight: 1 }); + based.table({ style: "S", at: [0, 0], columns: [4], rows: [[{ block: "B", blockScale: 1 }]] }); + assert.ok(boxOf(based.build())[0] >= -1e-9); +}); + +test("a fitted block fits by all it draws, a layer that does not plot included", () => { + const d = createDrawing({ units: "in" }); + d.layer("CON", { color: 1, plot: false }); + d.block("B", {}, () => { + d.line([0, 0], [1, 1]); + d.layer("CON", {}, () => d.line([0, 0], [100, 100])); + }); + d.tableStyle({ name: "S", textHeight: 1 }); + d.table({ style: "S", at: [0, 0], columns: [4], rows: [[{ block: "B" }]] }); + // The unit line is drawn at the scale that fits the 100-unit one, which does not plot. + const svg = toSVG(d.build()); + const drawn = svg.slice(svg.indexOf('data-block="B"')).match(/x1="([-0-9.]+)".*?x2="([-0-9.]+)"/); + assert.ok(drawn); + assert.ok(Number(drawn[2]) - Number(drawn[1]) < 0.1, drawn[0]); +}); + +test("the builder holds a cell's text to its row's font", () => { + const d = createDrawing({ units: "in" }); + d.textStyle({ name: "SHX", font: "romans.shx" }); + d.tableStyle({ name: "S", textHeight: 1, textStyle: "SHX" }); + assert.throws(() => d.table({ style: "S", at: [0, 0], columns: [4], rows: [["%%c"]] })); +}); + +test("a table whose style the drawing lacks draws nothing and throws nothing", () => { + const drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [{ kind: "table", layer: "0", at: [0, 0], columns: [1], rows: [["A"]] }], + } as never; + assert.doesNotThrow(() => toSVG(drawing)); + assert.doesNotThrow(() => inspectText(drawing)); +}); From 298d0847fb53af35672e3384cbad4f2e88f606b4 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 07:20:26 -0500 Subject: [PATCH 23/35] Linetypes with shapes: a fence's circles along it, drawn from the firm's shape file Linetypes with shapes, in R2018 drawings: a fence with its circles along it, and batt insulation. - `parseShapes(bytes)` reads a firm's compiled shape file (`.shx`) into each shape's outlines, its lines and arcs, with the shapes it draws inside it drawn in place. It refuses a font's file of another kind, a shape that draws itself, and one that ends before its codes do, and it is bounded by `SHAPE_FILE_LENGTH`, `SHAPE_POINTS` and `SHAPE_STEPS`. - `toSVG`, `toPDF` and `lint` take the files' bytes as `shapes`, found by name as CAD programs find them: without regard to case, and with or without `.shx` (`shapeFileKey`). The plot draws each shape where a linetype's text goes, turned and scaled alike, in the line's pen. A shape of a negative scale is turned half a turn. - A shape whose file is not given, does not read, or lacks the shape leaves its gap, and `lint` warns `linetype-shape` only of such a shape. - `parseLinetypes(text, { shapes })` numbers a shape the linetype file gives by its name. - The `tsdraft` command reads each shape file from the drawing file's folder, and `tsdraft dev` draws again when one is copied there. - A pattern that ends with a dash is now fitted to its own first dash, with that last dash running on into it, and a pattern of dashes alone draws its marks along a solid line, as CAD programs plot both. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 4 +- CHANGELOG.md | 15 +- GUIDE.md | 4 + README.md | 7 +- cli/src/worker.ts | 95 ++++++++- docs/rules.md | 12 +- src/drawing.ts | 9 +- src/dxf-r2018.ts | 17 +- src/index.ts | 11 ++ src/linetypes.ts | 72 ++++++- src/lint.ts | 42 +++- src/pdf.ts | 10 +- src/rules.ts | 14 +- src/shapes.ts | 456 ++++++++++++++++++++++++++++++++++++++++++++ src/svg.ts | 223 +++++++++++++++++----- test/shapes.test.ts | 268 ++++++++++++++++++++++++++ 16 files changed, 1162 insertions(+), 97 deletions(-) create mode 100644 src/shapes.ts create mode 100644 test/shapes.test.ts diff --git a/AGENTS.md b/AGENTS.md index e1b0f65..e367768 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,7 +231,9 @@ stretch, and `letterAt` sets each text in the frame of the side it lands on, the line's direction in its own coordinates deciding `upright`; on an arc that frame is the straight piece the leading CAD app cuts the arc into, `arcFrame`, 1/1200 inch from it on the paper, which - `Look.chord` holds. A polyline's `linetypeGeneration` cuts its sides as one course, `courseOf`, + `Look.chord` holds. `shapeAt` draws a shape the same way, from the outlines `parseShapes` reads + of its file, found by `shapeFinder`, which `lint` shares. A pattern that ends with a dash runs + it into its first, `Dashes.trail`, and is fitted to its own first dash, `Dashes.lead`. A polyline's `linetypeGeneration` cuts its sides as one course, `courseOf`, from its second point when it is closed. `toSVG` draws a layout with `elements`, the walk it draws model space with, under a `Look` that says how wide and what color a pen is. - A rule the leading CAD app enforces lives in `src/rules.ts` twice: as a type, so a wrong diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f029bd..277f2f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +- Linetypes with shapes: a fence with its circles along it, and batt insulation. `parseShapes` + reads a firm's compiled shape file (`.shx`) into each shape's outlines, and `toSVG`, `toPDF` + and `lint` take the files' bytes as `shapes`, found by name as CAD programs find them, without + regard to case and with or without `.shx`. The plot draws each shape where it draws a text, + turned and scaled alike, in the line's pen, and a shape of a negative scale turned half a turn; + `lint` warns `linetype-shape` only of a shape it cannot draw from the files given. + `parseLinetypes(text, { shapes })` numbers a shape given by its name. The `tsdraft` command + reads each shape file from the drawing file's folder. A pattern that ends with a dash is now + fitted to its own first dash, which runs on from that last one, and a pattern of dashes alone + draws its marks along a solid line, as CAD programs plot them. + - Tables, in R2018 drawings. `d.tableStyle(style)` defines a table style: the text style and height of its cells, its margins, and the cell style of its title, header and data rows, each with its own text style, height, alignment, text color, fill and border lineweight. @@ -21,6 +32,7 @@ that cannot be written, a row of the wrong length, a span past the table or over another cell, a `null` that nothing spans, a block its fit would scale to 0, a table in a block and more than 100,000 cells. `tableBox` gives the box of what a table draws, its cells' blocks included. + - Linetypes with text, in R2018 drawings: a pipe with its letters along it. A linetype's `marks` draw a text, such as `W`, at the end of a length of its pattern, by `after`, in one of the drawing's text styles, turned with the line, from the X axis, or `upright` so it reads from the @@ -30,8 +42,7 @@ writers write them, `readDXF` and `readDWG` read them back, and `toSVG` and `toPDF` draw the letters where CAD programs plot them: with each whole pattern, along the side they land on, at the size of the paper in a viewport or an insert. A linetype's shapes are written and read as - their numbers in a shape file, and the plot leaves a gap for each, with the warning - `linetype-shape` where one is drawn. + their numbers in a shape file. - Ellipses and splines, in R2018 drawings. `d.ellipse(center, majorAxis, ratio)` draws an ellipse, or an arc of one with `startParameter` and `endParameter`. `d.spline(fitPoints)` draws diff --git a/GUIDE.md b/GUIDE.md index ef27851..925efca 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -545,6 +545,10 @@ d.layout("C-101", { paper: "ARCH D" }, (sheet) => { firm's linetype file, a linetype's `marks` draw its letters at each repeat of its pattern, and a polyline drawn with `linetypeGeneration: true` runs the pattern on past its vertices, so short runs between bends still get their letters. The letters' text style must be one of the drawing's. +- A fence's circles or batt insulation's loops are shapes of the firm's shape file. Copy the file + beside the drawing: the command reads it there, and `toSVG`, `toPDF` and `lint` take its bytes + as `shapes`. Without it the plot leaves a gap where each shape goes, and `lint` warns + `linetype-shape`. - The sheet plots in black with `monochrome.ctb`. Pass `plotStyle: "acad.ctb"` to plot each layer in its color, or `"Grayscale.ctb"` in grays. `PLOT_STYLE_TABLES` lists them. - Define blocks outside `layout`, and insert them inside it. An `id` is unique across model diff --git a/README.md b/README.md index 62de3cc..06509b2 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,9 @@ Linetypes and lineweights are set on a layer, and an entity draws ByLayer unless it is given its own. `DASHED`, `HIDDEN`, `CENTER`, `PHANTOM`, `DASHDOT` and `DOT` are the leading CAD app's own definitions; `d.linetype({ name, pattern })` defines another, with dashes as positive lengths, gaps as negative ones and dots as 0. Its `marks` draw texts -along the line, such as a water main's letters, and `parseLinetypes` reads a firm's linetype file. A -polyline's `linetypeGeneration` runs the pattern on past its vertices. A +along the line, such as a water main's letters, and shapes of a firm's shape file, such as a +fence's circles, which `parseShapes` reads and the plot takes as `shapes`. `parseLinetypes` reads +a firm's linetype file. A polyline's `linetypeGeneration` runs the pattern on past its vertices. A lineweight is in millimetres. A text is in the style `Standard` unless it names another. `d.textStyle({ name, @@ -319,7 +320,7 @@ layers or twist the view, and layers that are off, frozen, locked or not plotted [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. It does not yet have overlines in paragraph text, ellipses, splines or points, tables, color or transparency set on one -entity, the shapes of a linetype in its plot, PDF underlays, or the other kinds of dimension. +entity, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit and write again. [Reading drawing files](docs/reading.md) has what it reads. diff --git a/cli/src/worker.ts b/cli/src/worker.ts index d6e5d2f..9341bbd 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -9,7 +9,7 @@ // module loaded ahead only when every file loaded ahead, every link on the way to one and // every package.json above one is on disk as it was read. Otherwise the process answers // `stale` and the parent builds in one that loaded nothing. -import { existsSync, readFileSync, realpathSync } from "node:fs"; +import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import { createRequire, isBuiltin, registerHooks } from "node:module"; import { dirname, isAbsolute, join, sep } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -147,7 +147,11 @@ type GivenXrefs = Readonly>; interface Library { readonly lint: ( drawing: Drawing, - options?: { standard?: unknown; xrefs?: GivenXrefs }, + options?: { + standard?: unknown; + xrefs?: GivenXrefs; + shapes?: Readonly>; + }, ) => Diagnostic[]; /** A copy of tsdraft from before standards has none, and its `lint` takes no standard. */ readonly defineStandard?: unknown; @@ -160,8 +164,11 @@ interface Library { layout?: string; view?: readonly [number, number, number, number]; images?: Readonly>; + shapes?: Readonly>; }, ) => string; + /** The key a shape file is found by. A copy of tsdraft from before shapes has none. */ + readonly shapeFileKey?: (file: string) => string; /** A raster file's pixels. A copy of tsdraft from before images has none. */ readonly rasterSize?: (bytes: Uint8Array) => [number, number] | undefined; /** What is wrong with the text as it plots. A copy of tsdraft from before it has none. */ @@ -570,7 +577,13 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise } { + const key = library.shapeFileKey; + if (typeof key !== "function") return {}; + const names: string[] = []; + for (const linetype of Array.isArray(drawing.linetypes) ? drawing.linetypes : []) { + const marks: unknown = (linetype as { marks?: unknown } | undefined)?.marks; + for (const m of Array.isArray(marks) ? marks : []) { + const named = (m as { file?: unknown } | undefined)?.file; + if (typeof m === "object" && m !== null && "shape" in m && typeof named === "string") + names.push(named); + } + } + if (names.length === 0) return {}; + const folder = dirname(file); + // The folder's shape files, each by its key, folded once. + const found = new Map(); + try { + for (const entry of readdirSync(folder)) + if (/\.shx$/i.test(entry) && !found.has(key(entry))) found.set(key(entry), entry); + } catch { + // A folder that cannot be read has no shape files. + } + // A record of no prototype, so a file named `__proto__` is a name like any other. + const shapes: Record = Object.create(null); + // Each spelling a mark gives has an entry, and each file is read once. + const bytesOf = new Map(); + const given = new Set(); + let total = 0; + for (const name of names) { + if (given.has(key(name))) continue; + given.add(key(name)); + const base = name.replaceAll("\\", "/").split("/").at(-1) ?? ""; + const k = key(base); + if (base === "") continue; + if (!bytesOf.has(k)) { + const entry = found.get(k); + const at = join(folder, entry ?? (/\.shx$/i.test(base) ? base : `${base}.shx`)); + track(at, fileVersion(at)); + let bytes: Uint8Array | undefined; + if (entry !== undefined) { + try { + const size = statSync(at).size; + if (size <= SHAPE_FILE_BYTES && total + size <= SHAPE_BYTES) { + total += size; + bytes = new Uint8Array(readFileSync(at)); + } + } catch { + // A file that cannot be read is left out. + } + } + bytesOf.set(k, bytes); + } + const bytes = bytesOf.get(k); + if (bytes !== undefined) shapes[name] = bytes; + } + return { shapes }; +} + /** The most bytes the files of a drawing's images are read to, all told. */ const RASTER_BYTES = 1 << 30; diff --git a/docs/rules.md b/docs/rules.md index 145293a..8eaf822 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -110,8 +110,9 @@ it would take `1e+100` for `1e+10` and report nothing. - A linetype's `marks` are each at the end of a length of its pattern, by `after`, in order, at most one at a length. A text is a string of at least one character in one of the drawing's text styles, `Standard` unless it names one, and its height is greater than 0 as written. A shape is a - whole number from 1 to 65535 in a named shape file, and its scale is greater than 0: a shape by - its name, as a linetype file gives it, is refused, since a drawing holds a shape by its number. + whole number from 1 to 65535 in a named shape file, and its scale is not 0 as written: one of a + negative scale is drawn turned half a turn. A shape by its name, as a linetype file gives it, is + refused, since a drawing holds a shape by its number: `parseLinetypes` given the file numbers it. `orient` is `relative`, `absolute` or `upright`. A linetype's texts may take 256 characters together, counting one more for each, since a DWG holds them in 512 bytes. R2018 only, as is a polyline's `linetypeGeneration`. @@ -312,9 +313,10 @@ it would take `1e+100` for `1e+10` and report nothing. - A viewport that reaches past its layout's paper. The leading CAD app plots a layout as far as its paper goes. - A viewport that shows none of the drawing: nothing in model space lies in the box it shows. -- `linetype-shape`: a linetype that a layer or an entity draws in, with shapes of a shape file. - CAD programs draw a shape from its file, which the drawing names and does not hold, and - tsdraft's plot leaves a gap where each goes. +- `linetype-shape`: a linetype that a layer or an entity draws in, with a shape the plot cannot + draw from the `shapes` given: its file is not given, does not read, or has no such shape. CAD + programs draw a shape from its file, which the drawing names and does not hold, and tsdraft's + plot leaves a gap where such a shape goes. - `check-capped`: where `lint` stopped the checks it makes again for what a drawing repeats: each attribute an insert places and each handle it takes past its first 64, a tag of 256 characters or more each time an insert's values are searched for it, what each diff --git a/src/drawing.ts b/src/drawing.ts index f871aa2..400dd3f 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -418,15 +418,18 @@ export interface LinetypeText extends MarkBase { } /** - * A shape of a shape file a linetype draws, by its number in the file. tsdraft's plot leaves a - * gap where it goes. + * A shape of a shape file a linetype draws, by its number in the file. tsdraft's plot draws it + * from the file given as `shapes`, which `parseShapes` reads, and leaves a gap without it. */ export interface LinetypeShape extends MarkBase { /** Its number in its shape file. A name, as a linetype file gives it, is not written. */ readonly shape: number | string; /** The shape file, as the drawing names it, such as `"shapes.shx"`. */ readonly file: string; - /** Its size, as a multiple of the shape's own, scaled as the pattern's lengths are. */ + /** + * Its size, as a multiple of the shape's own, scaled as the pattern's lengths are. A negative + * scale turns it half a turn. + */ readonly scale: number; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 43008da..6f5b322 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -174,6 +174,7 @@ import { } from "./leaders.ts"; import { entityLinetype, layerLinetype, lineweightCode, patternLength } from "./linetypes.ts"; import { idKey, isStandardTextStyle, shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; +import { shapeFileKey } from "./shapes.ts"; /** `$INSUNITS` codes from the DXF Reference. */ const INSUNITS: Record = { in: 1, ft: 2, mm: 4, cm: 5, m: 6 }; @@ -359,13 +360,12 @@ export function toDXFR2018( const textStyles = drawing.textStyles ?? []; // A linetype's mark holds its text style, or its shape file's, by its handle. The shape files // are styles of their own after the text styles, one for each file, in the order first named. - const shapeFiles = [ - ...new Map( - linetypes.flatMap((t) => - (t.marks ?? []).flatMap((m) => ("shape" in m ? [[m.file.toLowerCase(), m.file]] : [])), - ) as [string, string][], - ).values(), - ]; + const shapeKeys = new Map(); + for (const t of linetypes) + for (const m of t.marks ?? []) + if ("shape" in m && !shapeKeys.has(shapeFileKey(m.file))) + shapeKeys.set(shapeFileKey(m.file), m.file); + const shapeFiles = [...shapeKeys.values()]; let styleHandles: { standard: string; list: string[]; shapes: string[] } | undefined; const allocateStyles = () => ({ standard: handle(), @@ -376,8 +376,7 @@ export function toDXFR2018( if (linetypes.some((t) => (t.marks?.length ?? 0) > 0)) styleHandles = allocateStyles(); const markStyle = (m: LinetypeMark): string => { const handles = styleHandles!; - if ("shape" in m) - return handles.shapes[shapeFiles.findIndex((f) => f.toLowerCase() === m.file.toLowerCase())]!; + if ("shape" in m) return handles.shapes[[...shapeKeys.keys()].indexOf(shapeFileKey(m.file))]!; const name = m.style ?? STANDARD_TEXT_STYLE; if (isStandardTextStyle(name)) return handles.standard; const key = layerKey(name); diff --git a/src/index.ts b/src/index.ts index 7f3cba9..40f827b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -410,6 +410,17 @@ export { SPLINE_ITEMS, XREF_DEPTH, } from "./rules.ts"; +export { + parseShapes, + shapeFileKey, + SHAPE_FILE_LENGTH, + SHAPE_POINTS, + SHAPE_STEPS, + type ShapeDefinition, + type ShapeFile, + type ShapeFiles, + type ShapeOutline, +} from "./shapes.ts"; export { BUILT_IN_STANDARD, defineStandard, type BuiltInStandard } from "./standard/define.ts"; export type { Box, diff --git a/src/linetypes.ts b/src/linetypes.ts index fa88b8e..b5ea17c 100644 --- a/src/linetypes.ts +++ b/src/linetypes.ts @@ -2,6 +2,13 @@ // writers name and number them. import type { Layer, Lineweight, Linetype, LinetypeMark, MarkOrient } from "./drawing.ts"; import { layerKey } from "./layers.ts"; +import { + givenShapeFiles, + shapeFileKey, + shapeReader, + type ShapeFile, + type ShapeFiles, +} from "./shapes.ts"; /** Every lineweight the leading CAD app offers, in millimetres, from thinnest to widest. */ export const LINEWEIGHTS: readonly Lineweight[] = [ @@ -97,16 +104,25 @@ export const LINETYPE_FILE_LENGTH = 1_000_000; * when positive, a gap when negative and a dot when 0. A text in brackets, `["W",STYLE,S=0.1, * R=0,X=-0.05,Y=-0.05]`, or a shape, `[NAME,file.shx,S=0.1]`, is drawn at the end of the length * before it, turned by `R=` from the line, `A=` from the X axis or `U=` upright. A `;` starts a - * comment. A shape is given by its name in its file, which the drawing does not hold: a drawing - * takes a shape by its number. + * comment. A shape is given by its name in its file, and a drawing takes it by its number: with + * its file in `options.shapes`, by the file's name as `shapeFileKey` finds it, a shape is given + * its number, found by its name without regard to ASCII case, the first of the name in the file. + * A shape whose file is not given keeps its name, which the builder refuses. * - * @throws RangeError for a line it cannot read, naming its number, and for text past - * `LINETYPE_FILE_LENGTH` characters. + * @throws RangeError for a line it cannot read, naming its number, for a shape its given file + * lacks or a given file that does not read, for text past `LINETYPE_FILE_LENGTH` characters, + * and when two of the files' names are one file's. */ -export function parseLinetypes(text: string): Linetype[] { +export function parseLinetypes( + text: string, + options: { readonly shapes?: ShapeFiles } = {}, +): Linetype[] { if (typeof text !== "string") throw new RangeError("A linetype file's text must be a string"); if (text.length > LINETYPE_FILE_LENGTH) throw new RangeError(`A linetype file is at most ${LINETYPE_FILE_LENGTH} characters`); + const numberOf = shapeNumbers( + typeof options === "object" && options !== null ? options.shapes : undefined, + ); const out: Linetype[] = []; let open: { name: string; description: string; line: number } | undefined; const rows = text.split(/\r\n|\r|\n/); @@ -136,7 +152,12 @@ export function parseLinetypes(text: string): Linetype[] { throw new RangeError(`${where}: a text or shape comes after the length it is drawn at`); if (marks.at(-1)?.after === pattern.length - 1) throw new RangeError(`${where}: one text or shape at the end of each length`); - marks.push(markOf(value, pattern.length - 1, where)); + const mark = markOf(value, pattern.length - 1, where); + marks.push( + "shape" in mark && typeof mark.shape === "string" + ? { ...mark, shape: numberOf(mark.file, mark.shape, where) ?? mark.shape } + : mark, + ); continue; } const length = Number(value); @@ -157,6 +178,45 @@ export function parseLinetypes(text: string): Linetype[] { return out; } +/** + * The number of a shape by its name in a file of `files`, or undefined when the file is not + * given. Each file is read once, when first asked for. + */ +function shapeNumbers( + files: ShapeFiles | undefined, +): (file: string, name: string, where: string) => number | undefined { + const given = givenShapeFiles(files); + // The files share one budget, as the plot's do, and the same bytes under many names are read once. + const read = shapeReader(); + const fold = (name: string) => name.replace(/[a-z]/g, (c) => c.toUpperCase()); + const named = new Map>(); + // Each file read has one table of its names, however many names give the file. + const tables = new Map>(); + return (file, name, where) => { + const key = shapeFileKey(file); + if (!given.has(key)) return undefined; + let names = named.get(key); + if (names === undefined) { + const shapes = read(given.get(key)); + if (shapes instanceof RangeError) + throw new RangeError(`${where}: the shape file ${file} does not read: ${shapes.message}`); + names = tables.get(shapes); + if (names === undefined) { + names = new Map(); + for (const shape of shapes.shapes) + if (shape.name !== "" && !names.has(fold(shape.name))) + names.set(fold(shape.name), shape.number); + tables.set(shapes, names); + } + named.set(key, names); + } + const number = names.get(fold(name)); + if (number === undefined) + throw new RangeError(`${where}: the shape file ${file} has no shape ${name}`); + return number; + }; +} + /** A line up to its comment: a `;` outside the quotes of a text. */ function withoutComment(row: string): string { let quoted = false; diff --git a/src/lint.ts b/src/lint.ts index a7bc00b..547ad53 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -85,6 +85,7 @@ import { Strings, type Check, } from "./shape.ts"; +import { shapeFinder, type ShapeFiles } from "./shapes.ts"; import { layerAuditKey, layerKey, layoutNameKey } from "./layers.ts"; import { STANDARD_FONT, STANDARD_TEXT_STYLE } from "./fonts.ts"; import { @@ -389,6 +390,11 @@ export type LintOptions = { * given there is not drawn. It does not check those drawings: lint each on its own. */ readonly xrefs?: XrefDrawings; + /** + * The bytes of each shape file the drawing's linetypes name, as `toSVG` takes them. `lint` then + * warns only of a shape the plot cannot draw from them. + */ + readonly shapes?: ShapeFiles; } & ( | { /** The DXF version to check against. Defaults to the drawing's own. */ @@ -2682,16 +2688,36 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) out.push({ rule: "block-cycle", severity: "error", message, block: block.name }); } - // A shape is drawn from its shape file, which a drawing does not hold. + // A shape is drawn from its shape file, which a drawing does not hold: the plot finds it in the + // files it is given, as here. + let findShape: ReturnType | undefined; + try { + findShape = shapeFinder(options?.shapes); + } catch (error) { + // `shapeFinder` throws only a RangeError, but `lint` never throws whatever it is given. + const message = + error instanceof RangeError ? error.message : "The shape files given do not read"; + out.push({ rule: "linetype-shape", severity: "warning", message }); + } + const gaps = { + file: "its file is not given", + unread: "its file does not read", + shape: "its file has no such shape", + }; for (const linetype of marked) { if (!used.has(layerKey(linetype.name))) continue; - if (!(linetype.marks ?? []).some((m) => "shape" in m)) continue; - out.push({ - rule: "linetype-shape", - severity: "warning", - message: `Linetype ${shown(linetype.name)} draws shapes of a shape file, where tsdraft's plot leaves a gap: CAD programs draw them from the file, which the drawing names and does not hold`, - ...named("linetype", linetype.name), - }); + for (const m of linetype.marks ?? []) { + if (!("shape" in m) || typeof m.shape !== "number" || typeof m.file !== "string") continue; + const found = findShape?.(m.file, m.shape) ?? { missing: "file" as const }; + if ("shape" in found) continue; + out.push({ + rule: "linetype-shape", + severity: "warning", + message: `Linetype ${shown(linetype.name)} draws shape ${m.shape} of ${shown(m.file)}, where tsdraft's plot leaves a gap because ${gaps[found.missing]}: CAD programs draw it only where they find the file`, + ...named("linetype", linetype.name), + }); + break; + } } if (stopped !== undefined) { diff --git a/src/pdf.ts b/src/pdf.ts index 2d8de82..08bbffa 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -9,6 +9,7 @@ import { FONTS, fontInfo, type Font, capHeightOf } from "./fonts.ts"; import { paperInfo } from "./papers.ts"; import { Sha256 } from "./sha256.ts"; import { filled } from "./shape.ts"; +import type { ShapeFiles } from "./shapes.ts"; import { SHEET_PICTURE, toSVG } from "./svg.ts"; import { fromBase64, plotDecodes, pngPixels, rasterInfo, uncompressed } from "./raster.ts"; import { readTrueType, type TrueType } from "./truetype.ts"; @@ -51,6 +52,8 @@ export interface PdfOptions { * JPEG and a PNG of no transparency as the file holds them, and any other PNG decoded. */ readonly images?: Readonly>; + /** The bytes of each shape file the drawing's linetypes name, as `toSVG` takes them, for every sheet. */ + readonly shapes?: ShapeFiles; } /** One sheet of a set whose sheets are drawings of their own. */ @@ -118,7 +121,12 @@ export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions const { drawing, layout, xrefs } = sheet; const own = sheet.images ?? images; pdf.page( - toSVG(drawing, { layout, ...(xrefs ? { xrefs } : {}), ...(own ? { images: own } : {}) }), + toSVG(drawing, { + layout, + ...(xrefs ? { xrefs } : {}), + ...(own ? { images: own } : {}), + ...(options.shapes ? { shapes: options.shapes } : {}), + }), ); } return pdf.finish(); diff --git a/src/rules.ts b/src/rules.ts index c2d8ec6..bef8d8e 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -1776,7 +1776,7 @@ export const MARK_TEXT_ROOM = /** What is wrong with a shape given by name. */ export const MARK_SHAPE_NAME = - "a shape by its name needs its shape file to number it: give the shape's number in the file"; + "a shape by its name needs its shape file to number it: give the shape's number in the file, or give parseLinetypes the file"; /** * Returns what is wrong with a linetype's marks, or undefined when they are valid. It takes @@ -1833,8 +1833,16 @@ export function marksProblem(marks: unknown, pattern: readonly number[]): string } const size = isText ? "height" : "scale"; const v = m[size]; - if (typeof v !== "number" || !Number.isFinite(v) || !(v > 0) || written(v) === 0) - return `${label}: ${size} must be a number greater than 0 as written`; + // A shape of a negative scale is drawn turned half a turn, as a linetype file may give it. + if ( + typeof v !== "number" || + !Number.isFinite(v) || + !(isText ? v > 0 : v !== 0) || + written(v) === 0 + ) + return isText + ? `${label}: height must be a number greater than 0 as written` + : `${label}: scale must be a number other than 0 as written`; const big = magnitudeProblem(v); if (big) return `${label}: ${size}: ${big}`; if (isText) { diff --git a/src/shapes.ts b/src/shapes.ts new file mode 100644 index 0000000..191bd4e --- /dev/null +++ b/src/shapes.ts @@ -0,0 +1,456 @@ +// Shape files: the compiled file of shapes a linetype draws along its line, read into outlines. +import type { Point } from "./drawing.ts"; + +/** One pen-down run of a shape: its points, and the bulge of each side as a polyline gives it. */ +export interface ShapeOutline { + readonly points: readonly Point[]; + /** The bulge of the side from each point to the next, as `Polyline.bulges`. Left out when none. */ + readonly bulges?: readonly number[]; +} + +/** A shape of a shape file, in the file's own units, from where its pen starts at [0, 0]. */ +export interface ShapeDefinition { + readonly number: number; + /** Its name, or "" when the file gives none. */ + readonly name: string; + readonly outlines: readonly ShapeOutline[]; + /** Where its pen is left. */ + readonly end: Point; +} + +/** A shape file's shapes, in the file's order. */ +export interface ShapeFile { + readonly shapes: readonly ShapeDefinition[]; +} + +/** The bytes of each shape file the drawing's linetypes name, by the file's name. */ +export type ShapeFiles = Readonly>; + +/** + * The key a shape file is found by, as the leading CAD app finds it: its name without regard to + * ASCII case, with or without `.shx`. + */ +export function shapeFileKey(file: string): string { + return file.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/\.shx$/, ""); +} + +/** The most bytes `parseShapes` reads. */ +export const SHAPE_FILE_LENGTH = 4_000_000; + +/** The most points `parseShapes` makes of a file, all its shapes with their subshapes drawn. */ +export const SHAPE_POINTS = 500_000; + +/** + * The most codes `parseShapes` runs of a file, each code of a subshape again each time it is + * drawn, so a shape that draws a shape many times over is bounded too. + */ +export const SHAPE_STEPS = 5_000_000; + +/** What reading shape files may still spend. */ +export interface Budget { + points: number; + steps: number; +} + +export const budgetOf = (): Budget => ({ points: SHAPE_POINTS, steps: SHAPE_STEPS }); + +/** How deep a shape may draw a shape that draws a shape. */ +const SUBSHAPES = 16; + +/** How many places a shape may push before it pops one. */ +const STACK = 4; + +/** The furthest a shape may move its pen, and the largest and smallest its scale may grow. */ +const REACH = 1e9; +const SCALE_LIMIT = 1e9; + +const HEADER = /^[A-Za-z]+-86 ([a-z]+) (\d+\.\d+)\r\n\x1a/; + +/** The 16 directions of a vector, each as a step of one along the longer of its two axes. */ +const DIRECTIONS: readonly Point[] = [ + [1, 0], + [1, 0.5], + [1, 1], + [0.5, 1], + [0, 1], + [-0.5, 1], + [-1, 1], + [-1, 0.5], + [-1, 0], + [-1, -0.5], + [-1, -1], + [-0.5, -1], + [0, -1], + [0.5, -1], + [1, -1], + [1, -0.5], +]; + +const OCTANT = Math.PI / 4; + +/** + * Reads a compiled shape file (`.shx`) of shapes, such as the one a firm's complex linetypes + * name, into each shape's outlines: its lines, and its arcs as bulges, as the leading CAD app + * draws them, with each shape it draws inside it drawn in place. A pen-down move of no length + * draws nothing. Shape 0 of a font, which holds the font's sizes and no outline, is left out. + * + * @throws RangeError when the bytes are not a shape file, a font of the `unifont` or `bigfont` + * kind among them, when they are longer than `SHAPE_FILE_LENGTH`, when a shape holds a code + * that is not a shape's or ends before its codes do, draws itself through its shapes, pops + * more places than it pushed, pushes more than 4, or moves its pen or scale out of reach, and + * when the file's shapes come to more than `SHAPE_POINTS` points or `SHAPE_STEPS` codes run. + * The message names the shape. + */ +export function parseShapes(bytes: Uint8Array): ShapeFile { + return parseWithin(bytes, budgetOf()); +} + +/** `parseShapes`, spending from `budget`, which several files may share. */ +export function parseWithin(bytes: Uint8Array, budget: Budget): ShapeFile { + try { + return parseBytes(bytes, budget); + } catch (error) { + // A value that only looks like bytes, such as a proxy that throws, does not read. + if (error instanceof RangeError) throw error; + throw new RangeError(`The shape file does not read: ${messageOf(error)}`); + } +} + +/** What an error says, or "" when even that throws. */ +function messageOf(error: unknown): string { + try { + return error instanceof Error ? error.message : String(error); + } catch { + return ""; + } +} + +function parseBytes(bytes: Uint8Array, budget: Budget): ShapeFile { + if (!(bytes instanceof Uint8Array)) throw new RangeError("A shape file is given as its bytes"); + if (bytes.length > SHAPE_FILE_LENGTH) + throw new RangeError(`A shape file has at most ${SHAPE_FILE_LENGTH} bytes`); + // Reading the index and the names costs a step for each 8 bytes of the file. + budget.steps -= Math.ceil(bytes.length / 8); + if (budget.steps < 0) + throw new RangeError(`The file's shapes run more than ${SHAPE_STEPS} codes`); + let head = ""; + for (let i = 0; i < Math.min(bytes.length, 40); i++) head += String.fromCharCode(bytes[i]!); + const header = HEADER.exec(head); + if (header === null) throw new RangeError("The bytes are not a compiled shape file"); + const [, kind, version] = header; + if (kind !== "shapes") + throw new RangeError(`The file is a font of the ${kind} kind, which is not read`); + if (version !== "1.0") + throw new RangeError(`The file is of shapes ${version}, and only shapes 1.0 is read`); + const u16 = (at: number): number => { + if (at + 2 > bytes.length) throw new RangeError("The shape file ends before its index does"); + return bytes[at]! | (bytes[at + 1]! << 8); + }; + let at = header[0].length; + const count = u16(at + 4); + at += 6; + const index: { number: number; length: number }[] = []; + for (let i = 0; i < count; i++, at += 4) index.push({ number: u16(at), length: u16(at + 2) }); + const raw = new Map(); + for (const { number, length } of index) { + if (at + length > bytes.length) + throw new RangeError(`Shape ${number}: the file ends before its codes do`); + const body = bytes.subarray(at, at + length); + at += length; + const nul = body.indexOf(0); + if (nul < 0) throw new RangeError(`Shape ${number}: its name has no end`); + let name = ""; + for (const b of body.subarray(0, nul)) name += String.fromCharCode(b); + if (raw.has(number)) throw new RangeError(`Shape ${number} is in the file twice`); + raw.set(number, { name, codes: body.subarray(nul + 1) }); + } + const shapes: ShapeDefinition[] = []; + for (const { number } of index) { + // Shape 0 of a font holds its sizes, not an outline. + if (number === 0) continue; + const { name } = raw.get(number)!; + shapes.push({ number, name, ...draw(number, raw, budget) }); + } + return { shapes }; +} + +/** A shape a mark names, or why it plots as a gap: no file given, one not read, or no such shape. */ +export type ShapeFound = + | { readonly shape: ShapeDefinition } + | { readonly missing: "file" | "unread" | "shape" }; + +/** + * Finds the shapes marks name in the files given, each file read once when first asked for, as + * the plot and `lint` both find them. + * + * @throws RangeError when two of the files' names are one file's, as `shapeFileKey` finds them. + */ +export function shapeFinder( + files: ShapeFiles | undefined, +): (file: string, number: number) => ShapeFound { + const given = givenShapeFiles(files); + const read = shapeReader(); + const found = new Map | undefined>(); + // Each file read has one table of its shapes, however many names give it. + const tables = new Map>(); + return (file, number) => { + const key = shapeFileKey(file); + if (!given.has(key)) return { missing: "file" }; + if (!found.has(key)) { + const shapes = read(given.get(key)); + if (shapes instanceof RangeError) found.set(key, undefined); + else { + let table = tables.get(shapes); + if (table === undefined) + tables.set(shapes, (table = new Map(shapes.shapes.map((d) => [d.number, d])))); + found.set(key, table); + } + } + const shapes = found.get(key); + if (shapes === undefined) return { missing: "unread" }; + const shape = shapes.get(number); + return shape === undefined ? { missing: "shape" } : { shape }; + }; +} + +/** + * The shape files given, by `shapeFileKey` of each name, as `ShapeFiles` gives them. + * + * @throws RangeError when two names are one file's, or the record does not read. + */ +export function givenShapeFiles(files: unknown): Map { + const given = new Map(); + if (typeof files !== "object" || files === null) return given; + let entries: [string, unknown][]; + try { + entries = Object.entries(files); + } catch (error) { + throw new RangeError(`The shape files given do not read: ${messageOf(error)}`); + } + for (const [name, bytes] of entries) { + const key = shapeFileKey(name); + if (given.has(key)) + throw new RangeError(`The shape files ${JSON.stringify(name)} and another are one file`); + given.set(key, bytes); + } + return given; +} + +/** + * Reads shape files from one budget, each value read once however many names give it: its + * shapes, or the RangeError it does not read with. + */ +export function shapeReader(): (bytes: unknown) => ShapeFile | RangeError { + const budget = budgetOf(); + const read = new Map(); + return (bytes) => { + let shapes = read.get(bytes); + if (shapes === undefined) { + try { + shapes = parseWithin(bytes as Uint8Array, budget); + } catch (error) { + shapes = error instanceof RangeError ? error : new RangeError(messageOf(error)); + } + read.set(bytes, shapes); + } + return shapes; + }; +} + +/** What a shape's codes leave: their outlines and where the pen ends. */ +function draw( + number: number, + raw: ReadonlyMap, + budget: Budget, +): { outlines: ShapeOutline[]; end: Point } { + const outlines: { points: Point[]; bulges: number[] }[] = []; + let open: { points: Point[]; bulges: number[] } | undefined; + const state = { x: 0, y: 0, down: true, scale: 1 }; + const stack: Point[] = []; + const drawing: number[] = []; + + const close = () => { + if (open !== undefined && open.points.length > 1) outlines.push(open); + open = undefined; + }; + const moveTo = (x: number, y: number, bulge: number, label: string) => { + if (!(Math.abs(x) <= REACH && Math.abs(y) <= REACH)) + throw new RangeError(`${label}: its pen moves out of reach`); + if (state.down && (x !== state.x || y !== state.y)) { + if (open === undefined) open = { points: [[state.x, state.y]], bulges: [] }; + if (--budget.points < 0) + throw new RangeError(`The file's shapes come to more than ${SHAPE_POINTS} points`); + open.points.push([x, y]); + open.bulges.push(bulge); + } else if (!state.down) close(); + state.x = x; + state.y = y; + }; + /** An arc from the pen, about the center its start angle puts it on, cut into quarter turns. */ + const arc = (radius: number, start: number, sweep: number, label: string) => { + const r = radius * state.scale; + const cx = state.x - r * Math.cos(start); + const cy = state.y - r * Math.sin(start); + const pieces = Math.max(1, Math.ceil(Math.abs(sweep) / (Math.PI / 2) - 1e-9)); + for (let k = 1; k <= pieces; k++) { + const angle = start + (sweep * k) / pieces; + moveTo( + cx + r * Math.cos(angle), + cy + r * Math.sin(angle), + Math.tan(sweep / pieces / 4), + label, + ); + } + }; + + const run = (shape: number) => { + const entry = raw.get(shape); + const label = `Shape ${shape}${entry && entry.name !== "" ? ` (${entry.name})` : ""}`; + if (entry === undefined) throw new RangeError(`${label}: the file has no such shape`); + if (drawing.includes(shape)) throw new RangeError(`${label}: it draws itself`); + if (drawing.length >= SUBSHAPES) + throw new RangeError(`${label}: its shapes draw shapes more than ${SUBSHAPES} deep`); + drawing.push(shape); + const codes = entry.codes; + let i = 0; + const next = (): number => { + if (i >= codes.length) throw new RangeError(`${label}: its codes end before a 0`); + if (--budget.steps < 0) + throw new RangeError(`The file's shapes run more than ${SHAPE_STEPS} codes`); + return codes[i++]!; + }; + const signed = (): number => { + const b = next(); + return b > 127 ? b - 256 : b; + }; + /** An arc's octant byte: its direction, first octant and count of octants, 0 for 8. */ + const octants = () => { + const b = next(); + return { turn: b & 0x80 ? -1 : 1, first: (b >> 4) & 7, count: b & 7 || 8 }; + }; + /** Steps over the command at `i`, for code 14 outside vertical text. */ + const skip = () => { + // A code 14 before code 14 skips the command after both. + let code = next(); + while (code === 14) code = next(); + if (code > 0x0f) return; + if (code === 3 || code === 4 || code === 7) i += 1; + else if (code === 8) i += 2; + else if (code === 10) i += 2; + else if (code === 11) i += 5; + else if (code === 12) i += 3; + else if (code === 9 || code === 13) { + for (;;) { + const dx = next(); + const dy = next(); + if (dx === 0 && dy === 0) break; + if (code === 13) next(); + } + } else if (code === 0 || code === 15) + throw new RangeError(`${label}: code 14 comes before ${code}`); + if (i > codes.length) throw new RangeError(`${label}: its codes end before a 0`); + }; + for (;;) { + const code = next(); + if (code === 0) break; + if (code > 0x0f) { + const [dx, dy] = DIRECTIONS[code & 0x0f]!; + const length = (code >> 4) * state.scale; + moveTo(state.x + dx * length, state.y + dy * length, 0, label); + continue; + } + switch (code) { + case 1: + state.down = true; + break; + case 2: + state.down = false; + close(); + break; + case 3: + case 4: { + const by = next(); + if (by === 0) throw new RangeError(`${label}: it scales by 0`); + state.scale = code === 3 ? state.scale / by : state.scale * by; + if (!(state.scale <= SCALE_LIMIT && state.scale >= 1 / SCALE_LIMIT)) + throw new RangeError(`${label}: its scale grows out of reach`); + break; + } + case 5: + if (stack.length >= STACK) + throw new RangeError(`${label}: it pushes more than ${STACK} places`); + stack.push([state.x, state.y]); + break; + case 6: { + const place = stack.pop(); + if (place === undefined) + throw new RangeError(`${label}: it pops a place it never pushed`); + // A pop moves the pen without drawing. + close(); + state.x = place[0]; + state.y = place[1]; + break; + } + case 7: + run(next()); + break; + case 8: + case 9: + for (;;) { + const dx = signed(); + const dy = signed(); + if (code === 9 && dx === 0 && dy === 0) break; + moveTo(state.x + dx * state.scale, state.y + dy * state.scale, 0, label); + if (code === 8) break; + } + break; + case 10: { + const radius = next(); + const { turn, first, count } = octants(); + arc(radius, first * OCTANT, turn * count * OCTANT, label); + break; + } + case 11: { + const from = next(); + const to = next(); + const radius = (next() << 8) | next(); + const { turn, first, count } = octants(); + const start = first * OCTANT + (turn * from * OCTANT) / 256; + const end = (first + turn * (count - 1)) * OCTANT + (turn * to * OCTANT) / 256; + let sweep = end - start; + // The arc runs the way its octant byte turns, a whole turn at most. + if (turn * sweep <= 0) sweep += turn * 2 * Math.PI; + arc(radius, start, sweep, label); + break; + } + case 12: + case 13: + for (;;) { + const dx = signed(); + const dy = signed(); + if (code === 13 && dx === 0 && dy === 0) break; + const bulge = signed(); + if (bulge === -128) throw new RangeError(`${label}: a bulge of -128`); + moveTo(state.x + dx * state.scale, state.y + dy * state.scale, bulge / 127, label); + if (code === 12) break; + } + break; + case 14: + // Only vertical text draws the next command, and a shape along a line is not. + skip(); + break; + default: + throw new RangeError(`${label}: ${code} is not a shape's code`); + } + } + drawing.pop(); + }; + run(number); + close(); + return { + outlines: outlines.map((o) => + o.bulges.some((b) => b !== 0) ? { points: o.points, bulges: o.bulges } : { points: o.points }, + ), + end: [state.x, state.y], + }; +} diff --git a/src/svg.ts b/src/svg.ts index f189c33..4e6e807 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -28,7 +28,7 @@ import { type Line, type Linetype, type LinetypeMark, - type LinetypeText, + type LinetypeShape, type Paragraph, type Point, type Polyline, @@ -140,6 +140,7 @@ import { } from "./rules.ts"; import { ellipsePoint, splinePieces, splinePolyline, unturned } from "./curves.ts"; import { filled, KEYED } from "./shape.ts"; +import { shapeFinder, type ShapeDefinition, type ShapeFiles } from "./shapes.ts"; import { isUnits } from "./units.ts"; /** @@ -352,6 +353,13 @@ export interface SvgOptions { * `margin` then defaults to 0. */ readonly view?: readonly [x0: number, y0: number, x1: number, y1: number]; + /** + * The bytes of each shape file the drawing's linetypes name, by the file's name, found without + * regard to case and with or without `.shx`, as `shapeFileKey` finds it. A linetype's shape + * whose file is not here, does not read, or lacks the shape, leaves its gap, as `lint` warns. + * The drawing's xrefs find their shapes here too. + */ + readonly shapes?: ShapeFiles; } /** How an entity is drawn. */ @@ -371,6 +379,13 @@ interface Dashes { readonly total: number; /** True when one has no length: a dot, which draws as a round cap. */ readonly dot: boolean; + /** + * The pattern's last dash, which the first of `lengths` starts with when the pattern ends with + * a dash, and the pattern's own first dash after it, which a line is fitted to. The dashes after + * that one up to the first gap are the rest of the first of `lengths`. + */ + readonly trail: number; + readonly lead: number; /** The texts and shapes the pattern draws, where each is along it. */ readonly marks?: readonly ScaledMark[]; } @@ -378,6 +393,9 @@ interface Dashes { /** A linetype's pattern as `alternating` gives it, with where along it each mark is drawn. */ interface LinePattern { readonly runs: readonly number[]; + /** The pattern's last dash, joined to the start of its first, and its first, as `Dashes` has them. */ + readonly trail: number; + readonly lead: number; /** Each mark, `at` its distance from the start of `runs`, in the pattern's units. */ readonly marks: readonly { readonly at: number; @@ -396,6 +414,8 @@ interface ScaledMark { readonly mark: LinetypeMark; /** A text's style, as the drawing has it. */ readonly style: TextStyle | undefined; + /** A shape's outlines, as its file holds them. */ + readonly shape?: ShapeDefinition; /** What its offset and its height are multiplied by, in the units of the space it is drawn in. */ readonly size: number; } @@ -1118,6 +1138,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): /** Each pattern scaled for each space, worked out when first drawn with. */ const scaled = new Map>(); + const findShape = shapeFinder(options.shapes); /** Each pattern's marks scaled for a space, by its scale and size. */ const marked = new Map>(); const dashesOf = ( @@ -1134,7 +1155,14 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // A pattern the leading CAD app takes has at most 12 lengths, but one given as data may hold any number. if (!spend(Math.floor((pattern.runs.length + pattern.marks.length) / 32))) refuse(where()); const lengths = pattern.runs.map((length) => length * scale); - found = { lengths, total: lengths.reduce((a, b) => a + b, 0), dot: lengths.includes(0) }; + found = { + lengths, + total: lengths.reduce((a, b) => a + b, 0), + // A gap of 0 is a pattern's of dashes alone. + dot: lengths.some((length, i) => i % 2 === 0 && length === 0), + trail: pattern.trail * scale, + lead: pattern.lead * scale, + }; byScale.set(scale, found); } if (pattern.marks.length === 0) return found; @@ -1146,17 +1174,25 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): if (!spend(Math.floor(pattern.marks.length / 32))) refuse(where()); const made: Dashes = { ...found, - marks: pattern.marks.map(({ at, end, mark }) => ({ - at: at * scale, - end, - mark, - style: fontOnly( - "text" in mark && typeof mark.style === "string" - ? styles.get(key(mark.style)) - : undefined, - ), - size, - })), + // A shape its file does not give leaves its gap. + marks: pattern.marks.flatMap(({ at, end, mark }): ScaledMark[] => { + const found = "shape" in mark ? findShape(mark.file, mark.shape as number) : undefined; + if (found !== undefined && !("shape" in found)) return []; + return [ + { + at: at * scale, + end, + mark, + style: fontOnly( + "text" in mark && typeof mark.style === "string" + ? styles.get(key(mark.style)) + : undefined, + ), + ...(found === undefined ? {} : { shape: found.shape }), + size, + }, + ]; + }), }; bySpace.set(space, made); return made; @@ -2456,17 +2492,23 @@ function roundToSvg(center: Point, round: ReturnType, s: string) * is turned to start with the dash after it. Undefined for a pattern with no gap, with no dash * or dot, or with no length, and the caller then draws the entity solid. */ -/** True for a mark whose fields a text can be drawn from, as `lint` holds them. */ -function drawable(mark: unknown): mark is LinetypeText { - if (typeof mark !== "object" || mark === null || !("text" in mark)) return false; +/** True for a mark whose fields a text or a shape can be drawn from, as `lint` holds them. */ +function drawable(mark: unknown): mark is LinetypeMark { + if (typeof mark !== "object" || mark === null) return false; const m = mark as Record; const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v); const offset = m.offset; + const what = + "text" in m + ? typeof m.text === "string" && finite(m.height) && (m.height as number) > 0 + : "shape" in m && + Number.isInteger(m.shape) && + typeof m.file === "string" && + finite(m.scale) && + m.scale !== 0; return ( - typeof m.text === "string" && + what && Number.isInteger(m.after) && - finite(m.height) && - (m.height as number) > 0 && (m.rotation === undefined || finite(m.rotation)) && (m.orient === undefined || (MARK_ORIENTS as readonly unknown[]).includes(m.orient)) && (m.style === undefined || typeof m.style === "string") && @@ -2481,20 +2523,26 @@ function drawable(mark: unknown): mark is LinetypeText { */ function linePattern(t: Linetype): LinePattern | undefined { const pattern = filled(t.pattern); - const runs = alternating(pattern); - if (runs === undefined) return undefined; + const marks: readonly LinetypeMark[] = Array.isArray(t.marks) ? filled(t.marks) : []; + // A pattern of dashes alone with marks draws them along a solid line, as one of no gap. + const solid = pattern.length > 0 && pattern.every((length) => length >= 0); + const whole = pattern.reduce((a, b) => a + Math.abs(b), 0); + const alternated = + solid && marks.length > 0 && whole > 0 ? { runs: [whole, 0], trail: 0 } : alternating(pattern); + if (alternated === undefined) return undefined; + const { runs, trail } = alternated; const total = runs.reduce((a, b) => a + b, 0); const first = pattern.findIndex((length) => length >= 0); const ends: number[] = []; let sum = 0; for (const length of pattern) ends.push((sum += Math.abs(length))); const shift = first > 0 ? ends[first - 1]! : 0; - const marks: readonly LinetypeMark[] = Array.isArray(t.marks) ? filled(t.marks) : []; - // A shape draws nothing, and of two marks at one length only the first is drawn, so a pattern - // has no more marks than lengths. + // Of two marks at one length only the first is drawn, so a pattern has no more marks than lengths. const seen = new Set(); return { runs, + trail, + lead: Math.abs(pattern[first]!), marks: marks.flatMap((mark) => { if (!drawable(mark)) return []; const end = ends[mark.after]; @@ -2509,7 +2557,7 @@ function linePattern(t: Linetype): LinePattern | undefined { }; } -function alternating(pattern: readonly number[]): number[] | undefined { +function alternating(pattern: readonly number[]): { runs: number[]; trail: number } | undefined { const first = pattern.findIndex((length) => length >= 0); if (first < 0) return undefined; const runs: number[] = []; @@ -2519,8 +2567,10 @@ function alternating(pattern: readonly number[]): number[] | undefined { else runs.push(Math.abs(length)); } if (runs.length < 2) return undefined; - if (runs.length % 2 === 1) runs[0]! += runs.pop()!; - return runs.reduce((a, b) => a + b, 0) > 0 ? runs : undefined; + // A pattern that ends with a dash runs it into its first. + const trail = runs.length % 2 === 1 ? runs.pop()! : 0; + runs[0]! += trail; + return runs.reduce((a, b) => a + b, 0) > 0 ? { runs, trail } : undefined; } /** @@ -2574,8 +2624,13 @@ function dashedPath( if (size > room) return true; if (length / total > MAX_DASHES) return false; const first = dashes[0]! * stretch; + // The first run starts with the pattern's last dash when it ends with one, and runs on into + // the dashes after its own first: a stretch starts with the pattern's own first dash, and is + // fitted to it. + const lead = pattern.lead * stretch; + const after = first - pattern.trail * stretch - lead; let i = 0; - let at = 0; + let at = -pattern.trail * stretch; let last = length; // A stretch shorter than its pattern is solid, whatever the pattern starts with. if (fitted && length < total * (1 - 1e-9)) { @@ -2587,15 +2642,15 @@ function dashedPath( const dotted = first === 0; if (fitted) { const k = Math.floor(length / total + 1e-9); - const end = (length + first - k * total) / 2; - dash(draw, 0, dotted ? 0 : end); - [i, at, last] = [1, end, length - end]; + const end = (length + lead - k * total) / 2; + dash(draw, 0, dotted ? 0 : end + after); + [i, at, last] = [1, end + after, length - end]; } // The pattern ends where the last dash starts, or where the stretch ends, to within what // rounding moves a number. const stop = last - total * stretch * 1e-9; for (; at < stop && size <= room; i = (i + 1) % dashes.length) { - if (i % 2 === 0) dash(draw, at, Math.min(at + dashes[i]! * stretch, last)); + if (i % 2 === 0) dash(draw, Math.max(at, 0), Math.min(at + dashes[i]! * stretch, last)); at += dashes[i]! * stretch; } // A fitted stretch ends with its last dash, or a dot at its end. @@ -2613,7 +2668,7 @@ function dashedPath( for (const { s, mark } of markSpots(length, pattern, fitted, stretch)) { if (size > room) return; const [p, t] = frame(s); - const drawn = letterAt(mark, p, t, matrix, letters.text); + const drawn = letterAt(mark, p, t, matrix, letters); if (drawn === undefined) continue; size += drawn.length + 1; letters.out.push(drawn); @@ -2653,19 +2708,22 @@ function dashedPath( stretch = 1, marked = true, ): boolean => { + // A negative turn runs clockwise, and its pattern runs that way from `start`. + const way = turn < 0 ? -1 : 1; const along = (t: number) => { - const angle = rad(start) + t / radius; + const angle = rad(start) + (way * t) / radius; return place(center[0] + radius * Math.cos(angle), center[1] + radius * Math.sin(angle)); }; // The pattern is fitted to the straight pieces the arc is cut into, and drawn along the arc. - const length = radius * rad(turn); - const pieces = piecesLength(radius, rad(turn), chord); + const length = radius * rad(Math.abs(turn)); + const pieces = piecesLength(radius, rad(Math.abs(turn)), chord); const k = pieces > 0 ? length / pieces : 1; if (marked) { const frame = arcFrame(center, radius, rad(start), rad(turn), length, chord); markAlong(pieces, (at) => frame(at * k), fitted, stretch); } const shape = rounded(radius, matrix); + const sweep = way > 0 ? shape.sweep : 1 - shape.sweep; return cut( pieces, (a, b) => { @@ -2675,10 +2733,10 @@ function dashedPath( const arc = `A ${fmt(shape.rx)} ${fmt(shape.ry)} ${fmt(shape.turn)}`; // A dash of a full turn ends where it starts, so it is drawn as two halves. if ((to - from) / radius > Math.PI && along(from) === along(to)) { - return `M ${along(from)} ${arc} 0 ${shape.sweep} ${along((from + to) / 2)} ${arc} 0 ${shape.sweep} ${along(to)}`; + return `M ${along(from)} ${arc} 0 ${sweep} ${along((from + to) / 2)} ${arc} 0 ${sweep} ${along(to)}`; } const large = (to - from) / radius > Math.PI ? 1 : 0; - return `M ${along(from)} ${arc} ${large} ${shape.sweep} ${along(to)}`; + return `M ${along(from)} ${arc} ${large} ${sweep} ${along(to)}`; }, fitted, stretch, @@ -2786,11 +2844,8 @@ function dashedPath( if (!isWide(side)) { if (!arc) straight(side.from, side.to, true); else { - // An arc that turns clockwise is cut from its end, which fits the same dashes, and - // its marks from its start. - const from = arc.sweep > 0 ? arc.start : arc.start + arc.sweep; - const turn = degrees(Math.abs(arc.sweep)); - round(arc.center, arc.radius, degrees(from), turn, true, 1, false); + // An arc is cut the way the polyline runs, clockwise or not. + round(arc.center, arc.radius, degrees(arc.start), degrees(arc.sweep), true, 1, false); const pieces = piecesLength(arc.radius, Math.abs(arc.sweep), chord); markAlong(pieces, sideFrame(side, arc, pieces, chord), true); } @@ -2925,17 +2980,25 @@ function fontOnly(style: TextStyle | undefined): TextStyle | undefined { return style === undefined ? undefined : { name: style.name, font: style.font }; } -/** Where the texts of a pen's linetype go, when it has any: drawn in its color, with no mark. */ +/** Where the texts and shapes of a pen's linetype go, when it has any: drawn in its pen, with no mark. */ function lettersOf(pen: Pen, look: Look): Letters | undefined { - if (!pen.dashes?.marks?.some((m) => "text" in m.mark)) return undefined; - void look; - return { out: [], text: (t, style) => textToSvg(t, style, pen, "", undefined, false) }; + if (!pen.dashes?.marks?.length) return undefined; + const stroked = `stroke="${pen.color}"${look.stroke(pen.lineweight)}`; + return { + out: [], + text: (t, style) => textToSvg(t, style, pen, "", undefined, false), + shape: (d) => ``, + }; } -/** Where the texts of a linetype go, and how a text is drawn: as the entity's own text. */ +/** + * Where the texts and shapes of a linetype go, and how each is drawn: a text as the entity's own + * text, and a shape's outlines as the path `d`, in the entity's pen and never dashed. + */ interface Letters { readonly out: string[]; readonly text: (t: Text, style: TextStyle | undefined) => string; + readonly shape: (d: string) => string; } /** @@ -2955,9 +3018,10 @@ function* markSpots( if (marks === undefined || !(total > 0) || length / total > MAX_DASHES) return; if (fitted) { if (length < total * (1 - 1e-9)) return; - const first = lengths[0]!; + // Each pattern starts with its own first dash, after the last dash the first run starts with. + const lead = dashes.lead; const count = Math.floor(length / total + 1e-9); - const start = (length + first - count * total) / 2 - first; + const start = (length + lead - count * total) / 2 - lead; for (let k = 0; k < count; k++) for (const mark of marks) yield { s: start + k * total + (mark.end ? total : mark.at), mark }; // A mark at the end of the pattern comes once more at the end of the stretch. @@ -3109,16 +3173,18 @@ function pieceTrace( * A linetype's text at a point of its line where the line runs along `t`, both in the entity's * own coordinates, drawn where `matrix` puts it. Its offset is along the line and to its left as * the line is drawn, and an upright text turns half a turn about the middle of its box where the - * line runs leftward in its own coordinates. A shape draws nothing. + * line runs leftward in its own coordinates. A shape is drawn from its file's outlines, from the + * same point, turned and scaled alike. */ function letterAt( m: ScaledMark, p: Point, t: Point, matrix: Matrix | undefined, - draw: Letters["text"], + letters: Letters, ): string | undefined { const mark = m.mark; + if (m.shape !== undefined && "shape" in mark) return shapeAt(m, m.shape, p, t, matrix, letters); if (!("text" in mark) || typeof mark.text !== "string") return undefined; const [px, py] = matrix ? mapPoint(matrix, p) : p; let [tx, ty] = matrix @@ -3148,7 +3214,58 @@ function letterAt( rotation += 180; } } - return draw({ ...text, at: [x, y], rotation }, m.style); + return letters.text({ ...text, at: [x, y], rotation }, m.style); +} + +/** A linetype's shape at a point of its line, as `letterAt` places a text, as one path. */ +function shapeAt( + m: ScaledMark, + shape: ShapeDefinition, + p: Point, + t: Point, + matrix: Matrix | undefined, + letters: Letters, +): string | undefined { + const mark = m.mark as LinetypeShape; + if (shape.outlines.length === 0) return undefined; + const [px, py] = matrix ? mapPoint(matrix, p) : p; + let [tx, ty] = matrix + ? [matrix[0] * t[0] + matrix[2] * t[1], matrix[1] * t[0] + matrix[3] * t[1]] + : t; + const along = Math.hypot(tx, ty); + if (!(along > 0)) return undefined; + [tx, ty] = [tx / along, ty / along]; + const [ox, oy] = mark.offset === undefined ? [0, 0] : [mark.offset[0], mark.offset[1]]; + const k = m.size; + const x = px + (ox * tx - oy * ty) * k; + const y = py + (ox * ty + oy * tx) * k; + const orient = mark.orient ?? "relative"; + let rotation = (orient === "absolute" ? 0 : Math.atan2(ty, tx)) + rad(mark.rotation ?? 0); + if (orient === "upright") { + const local = ((degrees(Math.atan2(t[1], t[0])) % 360) + 360) % 360; + if (local > 90 + 1e-9 && local < 270 - 1e-9) rotation += Math.PI; + } + const size = mark.scale * k; + const [c, s] = [Math.cos(rotation) * size, Math.sin(rotation) * size]; + const place = ([u, v]: Point): string => `${fmt(x + u * c - v * s)} ${fmt(y + u * s + v * c)}`; + const parts: string[] = []; + for (const { points, bulges } of shape.outlines) { + parts.push(`M ${place(points[0]!)}`); + for (let i = 1; i < points.length; i++) { + const bulge = bulges?.[i - 1] ?? 0; + if (bulge === 0) { + parts.push(`L ${place(points[i]!)}`); + continue; + } + const [a, b] = [points[i - 1]!, points[i]!]; + const turn = 4 * Math.atan(Math.abs(bulge)); + const radius = + (Math.hypot(b[0] - a[0], b[1] - a[1]) * Math.abs(size)) / (2 * Math.sin(turn / 2)); + const large = turn > Math.PI ? 1 : 0; + parts.push(`A ${fmt(radius)} ${fmt(radius)} 0 ${large} ${bulge > 0 ? 1 : 0} ${place(b)}`); + } + } + return letters.shape(parts.join(" ")); } /** diff --git a/test/shapes.test.ts b/test/shapes.test.ts new file mode 100644 index 0000000..82959fc --- /dev/null +++ b/test/shapes.test.ts @@ -0,0 +1,268 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + createDrawing, + lint, + parseLinetypes, + parseShapes, + toSVG, + type Drawing, +} from "../src/index.ts"; + +/** A compiled shape file of the given shapes: number, name and codes, as a compiler writes it. */ +function shapeFile(shapes: readonly [number, string, readonly number[]][], kind = "shapes 1.0") { + const bytes: number[] = [...`Test-86 ${kind}\r\n\x1a`].map((c) => c.charCodeAt(0)); + const u16 = (v: number) => bytes.push(v & 255, v >> 8); + const numbers = shapes.map(([n]) => n); + u16(Math.min(...numbers)); + u16(Math.max(...numbers)); + u16(shapes.length); + for (const [n, name, codes] of shapes) { + u16(n); + u16(name.length + 1 + codes.length); + } + for (const [, name, codes] of shapes) + bytes.push(...[...name].map((c) => c.charCodeAt(0)), 0, ...codes.map((c) => c & 255)); + bytes.push(...[..."EOF"].map((c) => c.charCodeAt(0))); + return new Uint8Array(bytes); +} + +const round = (points: readonly (readonly [number, number])[]) => + points.map(([x, y]) => [Math.round(x * 1000) / 1000, Math.round(y * 1000) / 1000]); + +test("parseShapes draws each code as the leading CAD app plots it", () => { + const { shapes } = parseShapes( + shapeFile([ + // Up 4, pen up, back down, pen down, east 4: the pen-up move draws nothing. + [1, "PEN", [0x44, 2, 0x4c, 1, 0x40, 0]], + // A pop moves the pen back without drawing; a subshape goes on from where it ends. + [2, "POP", [5, 0x44, 0x40, 6, 7, 1, 0]], + // Code 14 skips its whole next command outside vertical text. + [3, "VERT", [14, 8, -2, -3, 0x40, 0]], + // A clockwise fractional arc, its offsets turned the way it runs. + [4, "FRAC", [11, 56, 28, 0, 3, 0x92, 0]], + // A pen-down move of no length draws nothing. + [5, "DOT", [8, 0, 0, 0]], + ]), + ); + const [pen, pop, vert, frac, dot] = shapes; + assert.deepEqual( + pen!.outlines.map((o) => round(o.points)), + [ + [ + [0, 0], + [0, 4], + ], + [ + [0, 0], + [4, 0], + ], + ], + ); + assert.deepEqual( + pop!.outlines.map((o) => round(o.points)), + [ + [ + [0, 0], + [0, 4], + [4, 4], + ], + [ + [0, 0], + [0, 4], + ], + [ + [0, 0], + [4, 0], + ], + ], + ); + assert.deepEqual( + vert!.outlines.map((o) => round(o.points)), + [ + [ + [0, 0], + [4, 0], + ], + ], + ); + // From 45° less 56/256 of an octant, clockwise to 0° less 28/256 of one, about a center 3 away. + const [start, end] = [(Math.PI / 4) * (1 - 56 / 256), (-Math.PI / 4) * (28 / 256)]; + const center = [-3 * Math.cos(start), -3 * Math.sin(start)]; + assert.deepEqual( + round(frac!.outlines[0]!.points)[1], + round([[center[0]! + 3 * Math.cos(end), center[1]! + 3 * Math.sin(end)]])[0], + ); + assert.ok(frac!.outlines[0]!.bulges![0]! < 0); + assert.deepEqual(dot!.outlines, []); +}); + +test("parseShapes refuses what is not a shape file of its kind, and a shape that draws itself", () => { + for (const [bytes, message] of [ + [shapeFile([[1, "A", [0x10, 0]]], "unifont 1.0"), /unifont kind/], + [shapeFile([[1, "A", [0x10, 0]]], "shapes 1.1"), /only shapes 1.0/], + [ + shapeFile([ + [1, "A", [7, 2, 0]], + [2, "B", [7, 1, 0]], + ]), + /draws itself/, + ], + [shapeFile([[1, "A", [6, 0]]]), /never pushed/], + [shapeFile([[1, "A", [0x10]]]), /end before a 0/], + [new Uint8Array([1, 2, 3]), /not a compiled shape file/], + ] as const) { + assert.throws( + () => parseShapes(bytes), + (e: Error) => e instanceof RangeError && message.test(e.message), + ); + } +}); + +const FENCE = shapeFile([[133, "CIRC1", [10, 1, -0x40, 0]]]); + +function fence(): Drawing { + const d = createDrawing({ units: "in" }); + d.linetype({ + name: "FENCE", + pattern: [0.25, -0.1, -0.1, 1], + marks: [{ after: 1, shape: 133, file: "fence.shx", scale: 0.1, offset: [-0.1, 0] }], + }); + d.line([0, 0], [2.6, 0], { linetype: "FENCE" }); + return d.build(); +} + +test("a linetype's shape is drawn from its file, found as the CAD app finds it, and a gap without", () => { + const drawn = toSVG(fence(), { shapes: { FENCE: FENCE } }); + assert.match(drawn, / A 0\.1 0\.1 0 0 0 /); + assert.doesNotMatch(toSVG(fence()), / A 0\.1 /); + const warned = (shapes?: Record) => + lint(fence(), shapes ? { shapes } : {}).filter((d) => d.rule === "linetype-shape").length; + assert.equal(warned(), 1); + assert.equal(warned({ "Fence.SHX": FENCE }), 0); + assert.equal(warned({ "fence.shx": shapeFile([[1, "OTHER", [0x10, 0]]]) }), 1); +}); + +test("a pattern that ends with a dash is fitted to its own first dash", () => { + // 2.6 holds one pattern of 1.45: its first and last dashes are each (0.25 + 2.6 - 1.45) / 2. + const d = createDrawing({ units: "in" }); + d.linetype({ name: "LONG", pattern: [0.25, -0.1, -0.1, 1] }); + d.line([0, 0], [2.6, 0], { linetype: "LONG" }); + const path = /d="([^"]+)"/.exec(toSVG(d.build(), { margin: 0 }))?.[1] ?? ""; + const xs = [...path.matchAll(/[ML] (-?[\d.]+) /g)].map((m) => Number(m[1])); + assert.deepEqual(xs, [0, 0.7, 0.9, 1.9, 1.9, 2.6]); +}); + +test("parseLinetypes numbers a shape by its name in the file given, in any case", () => { + const text = "*FENCE,Fence\nA,.25,-.1,[circ1,fence,s=.1,x=-.1],-.1,1\n"; + const [named] = parseLinetypes(text); + assert.equal(named?.marks?.[0] && "shape" in named.marks[0] && named.marks[0].shape, "circ1"); + const [numbered] = parseLinetypes(text, { shapes: { "fence.shx": FENCE } }); + assert.equal( + numbered?.marks?.[0] && "shape" in numbered.marks[0] && numbered.marks[0].shape, + 133, + ); + assert.throws( + () => parseLinetypes(text, { shapes: { "fence.shx": shapeFile([[1, "BOX", [0x10, 0]]]) } }), + /line 2 of the linetype file: the shape file fence has no shape circ1/, + ); +}); + +test("a shape file whose shapes draw a shape many times over is refused, and quickly", () => { + // Each of three shapes draws the next 600 times: 216 million calls unbounded. + const fan = (next: number) => Array.from({ length: 600 }, () => [7, next]).flat(); + const started = performance.now(); + assert.throws( + () => + parseShapes( + shapeFile([ + [1, "A", [...fan(2), 0]], + [2, "B", [...fan(3), 0]], + [3, "C", [...fan(4), 0]], + [4, "D", [0]], + ]), + ), + /more than 5000000 codes/, + ); + assert.ok(performance.now() - started < 5000); + assert.equal(parseLinetypes("*X\nA,1,-1\n", null as never).length, 1); +}); + +test("a polyline's clockwise arc is cut the way the polyline runs", () => { + const d = createDrawing({ units: "in" }); + d.linetype({ name: "ASYM", pattern: [1, -1, 2, -2, 3] }); + d.polyline( + [ + [0, 0], + [6, 0], + ], + false, + { linetype: "ASYM", bulges: [-1] }, + ); + // Its first dash, (1 + 3π - 9) / 2 long, starts where the polyline does. + const path = /d="([^"]+)"/.exec(toSVG(d.build(), { margin: 0 }))?.[1] ?? ""; + assert.match(path, /^M 0 0 A 3 3 0 0 0 /); +}); + +test("parseLinetypes reads the files it is given within one budget, whatever their names", () => { + // About 4.3 million codes: one file is within SHAPE_STEPS, two copies are not. + const calls = (next: number) => Array.from({ length: 1200 }, () => [7, next]).flat(); + const big = shapeFile([ + [1, "A", [...calls(2), 0]], + [2, "B", [...calls(3), 0]], + [3, "C", [0]], + ]); + const text = "*L0\nA,1,[A,f0],-1\n*L1\nA,1,[A,f1],-1\n"; + assert.equal(parseLinetypes(text, { shapes: { f0: big } }).length, 2); + assert.throws( + () => parseLinetypes(text, { shapes: { f0: big, f1: new Uint8Array(big) } }), + /line 4 of the linetype file: the shape file f1 does not read: .*more than 5000000 codes/, + ); +}); + +test("hostile shape inputs are refused with RangeError, and one file under two names is read once", () => { + assert.throws(() => parseShapes(new Proxy(FENCE, {})), RangeError); + const throwing = Object.defineProperty({}, "fence", { + enumerable: true, + get: () => { + throw null; + }, + }); + assert.throws(() => toSVG(fence(), { shapes: throwing }), RangeError); + assert.throws(() => parseLinetypes("*X\nA,1,-1\n", { shapes: throwing }), RangeError); + assert.ok(lint(fence(), { shapes: throwing }).some((d) => d.rule === "linetype-shape")); + // About 4.3 million codes, within SHAPE_STEPS once: both names draw from the one read. + const calls = (next: number) => Array.from({ length: 1200 }, () => [7, next]).flat(); + const big = shapeFile([ + [133, "CIRC1", [10, 1, -0x40 & 255, 0]], + [1, "A", [...calls(2), 0]], + [2, "B", [...calls(3), 0]], + [3, "C", [0]], + ]); + assert.equal( + lint(fence(), { shapes: { fence: big, "./fence": big } }).filter( + (d) => d.rule === "linetype-shape", + ).length, + 0, + ); +}); + +test("a file of many shapes given under many names is tabled once", () => { + const many = shapeFile(Array.from({ length: 20000 }, (_, i) => [i + 1, `S${i}`, [0x10, 0]])); + const names = Array.from({ length: 2000 }, (_, i) => `f${i}`); + const shapes = Object.fromEntries(names.map((n) => [n, many])); + const started = performance.now(); + const d = createDrawing({ units: "in" }); + for (const [i, n] of names.entries()) + d.linetype({ + name: `L${i}`, + pattern: [1, -1], + marks: [{ after: 0, shape: 1, file: n, scale: 0.1 }], + }); + d.line([0, 0], [3, 0], { linetype: "L0" }); + const drawing = d.build(); + assert.equal(lint(drawing, { shapes }).filter((x) => x.rule === "linetype-shape").length, 0); + toSVG(drawing, { shapes }); + parseLinetypes(names.map((n) => `*${n}\nA,1,[S1,${n}],-1\n`).join(""), { shapes }); + assert.ok(performance.now() - started < 10000); +}); From 4a98d819c5f20dfc0dc05ad1a61dbbb2c9381dd0 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 08:07:12 -0500 Subject: [PATCH 24/35] An entity's own color, by index or as a true color: written, read and plotted as CAD programs hold it An entity can have a color of its own, in R2018 drawings. Every entity but a table takes `color`, an insert, a dimension and a leader included: an index from 1 to 255, `"ByLayer"` (the default, left out of the drawing), `"ByBlock"`, or a true color `[red, green, blue]`. - `toDXF` writes an index in group 62, 0 for ByBlock, and a true color in group 420 with the index the leading CAD app matches it to in group 62, the same index it works out itself. - `toSVG` and `toPDF` plot an index through the layout's plot style table and a true color as it is under each of the four tables tsdraft offers, `monochrome.ctb` included, so an entity that must plot gray on a black sheet takes a true gray. An entity of a block set ByBlock takes its insert's color, the insert's layer's when the insert is ByLayer. A dimension and a leader draw every part in their color. - A paragraph's `\c` code sets a true color, with its blue first (`\c255;` is red), and `\C0;` and `\C256;` plot ByBlock and in the layer's color. - `lint` and the builder refuse any other color under the rule `entity-color`, and a color in an R12 drawing; a literal color outside the ranges is a compile error. - `readDXF` and `readDWG` read a color of a color book as `colorBook`, its `book` and `name`, with its true color in `trueColor`. - The example sheet's existing sidewalk plots gray among the black. [Colors](docs/colors.md) has the rest. A table's style and its cells give its colors, and the builder and `lint` refuse a color of its own. Transparency comes in a pull request of its own. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 10 ++ GUIDE.md | 3 +- README.md | 6 +- docs/colors.md | 66 +++++++++ docs/dimensions.md | 4 +- docs/format.md | 4 + docs/paragraphs.md | 8 +- docs/reading.md | 6 +- docs/rules.md | 7 +- examples/site-plan.ts | 7 +- src/blocks.ts | 42 +++++- src/colors.ts | 122 +++++++++++++++++ src/drawing.ts | 289 +++++++++++++++++++++++++++++----------- src/dxf-r2018.ts | 20 ++- src/index.ts | 3 + src/lint.ts | 11 ++ src/paragraph-codes.ts | 20 ++- src/read/check.ts | 1 + src/read/dxf.ts | 7 +- src/read/entities.ts | 23 +++- src/read/model.ts | 8 ++ src/rules.ts | 54 +++++++- src/shape.ts | 64 ++++++++- src/svg.ts | 84 ++++++++---- test/paragraphs.test.ts | 2 +- test/read-agreement.ts | 9 +- test/rules.test.ts | 77 ++++++++++- test/shape.test.ts | 14 +- test/tables.test.ts | 16 +++ 29 files changed, 836 insertions(+), 151 deletions(-) create mode 100644 docs/colors.md create mode 100644 src/colors.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 277f2f6..3c738ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,16 @@ knots of the wrong count or that decrease, weights not above 0, and more than 32,767 knots. `ellipsePoint`, `ellipseBox`, `splinePoint`, `splineBox`, `fitSpline` and `clamped` give their geometry. +- An entity's own color, in R2018 drawings. Every entity but a table, an insert, a dimension and a + leader included, takes `color`: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a + true color `[red, green, blue]`. `toDXF` writes an index in group 62, and a true color in + group 420 with the index the leading CAD app matches it to in group 62. `toSVG` and `toPDF` plot an index + through the layout's plot style table and a true color as it is under each table, and an + entity of a block set ByBlock in its insert's color. A paragraph's `\c` code sets a true color, + with its blue first, and `\C0;` and `\C256;` plot ByBlock and in the layer's color. `lint` and + the builder refuse any other color under the rule `entity-color`, and a color in an R12 + drawing. `readDXF` and `readDWG` read a color of a color book as `colorBook`, with its true + color in `trueColor`. - Solid fills, wipeouts and masks, in R2018 drawings. `d.hatch(boundary)` fills the area inside one outline, or inside a list of loops `{ points, bulges? }`, solid in its layer's color: the area inside an odd number of loops is filled, so a loop inside another is a hole, whichever diff --git a/GUIDE.md b/GUIDE.md index 925efca..b682060 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -680,7 +680,8 @@ writeFileSync("plan.dxf", toDXF(drawing)); for another plotter. - The spacing of characters inside a paragraph, `\T`, and an overline, `\O`. - Ellipses and splines. -- A color on a single entity. Color comes from the layer. +- Transparency on a single entity, and a color of a color book. A color of an entity is an index + or a true color: see [docs/colors.md](docs/colors.md). - DWG files. tsdraft writes DXF. - An existing drawing as a background or a base to edit. `readDXF` reads a DXF's tables, blocks, layouts and a census of what it draws, and with `geometry` what each space draws, as diff --git a/README.md b/README.md index 06509b2..a75581c 100644 --- a/README.md +++ b/README.md @@ -313,13 +313,13 @@ starts each breaking change with `Breaking:`. It draws layers, lines, polylines with arcs and widths, rectangles, revision clouds, donuts, circles, arcs, single-line text and paragraph text that wraps to a width, with lists, tab -stops and columns, linetypes and lineweights, text styles and justification, blocks with attributes and inserts +stops and columns, linetypes and lineweights, an entity's own color by index or as a true color, text styles and justification, blocks with attributes and inserts of them, references to DWG files as xrefs, linear and aligned dimensions in decimal units or feet and inches with stacked fractions, words below the line and text on a leader, leaders, layouts with a page setup and viewports, which can freeze their own layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have overlines in paragraph text, ellipses, splines or points, tables, color or transparency set on one +It does not yet have overlines in paragraph text, ellipses, splines or points, tables, transparency set on one entity, PDF underlays, or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit @@ -430,6 +430,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version - [Fills, wipeouts and masks](docs/fills.md) covers hatches with holes, solid, of a pattern file's patterns or of a gradient, wipeouts, the masks of paragraphs, leaders and dimensions, the draw order, and what `lint` refuses. +- [Colors](docs/colors.md) covers an entity's own color by index or as a true color, ByBlock in + a block, how each plots under a plot style table, and the color codes of paragraph text. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. - [Xrefs](docs/xrefs.md) covers references to DWG files: the path, units, a diff --git a/docs/colors.md b/docs/colors.md new file mode 100644 index 0000000..6a6398e --- /dev/null +++ b/docs/colors.md @@ -0,0 +1,66 @@ +# Colors + +An entity draws in its layer's color unless it has a color of its own. `color` takes four kinds of +value: + +- An index from 1 to 255 of the color index CAD programs share. 7 is black on paper. +- `"ByLayer"`, the layer's color, which is the default and is left out of the drawing. +- `"ByBlock"`, the color of the insert that places the entity's block. +- A true color, `[red, green, blue]`, each a whole number from 0 to 255. + +```ts +const d = createDrawing({ units: "ft" }); +d.layer("C-PAVE", { color: 7 }, () => { + d.line([0, 0], [100, 0]); + // The existing sidewalk, gray among the black. + d.line([0, -5], [100, -5], { color: [128, 128, 128] }); +}); +``` + +Every entity but a table takes a color: lines, polylines, circles, arcs, ellipses, splines, texts, +paragraphs, hatches, wipeouts, images, inserts, dimensions and leaders. A table's style and its cells +give its colors, and the builder and `lint` refuse a color of its own. A dimension draws every part in its color, its text and +arrowheads included, and so does a leader. A wipeout's color is its frame's; it still hides what is +behind it in the paper's color. + +Colors are R2018 only. The builder and `lint` refuse a color but `"ByLayer"` in an R12 drawing. + +## How a color plots + +A plot style table decides how an index plots: `monochrome.ctb` plots every index black, +`Grayscale.ctb` each in a gray of its own, `acad.ctb` each in its color. A true color plots as it +is under each of those tables, `monochrome.ctb` included, in the leading CAD app's plot. So an entity that must plot gray on a sheet that +plots black takes a true gray, such as `[128, 128, 128]`; an index 8 plots black there. + +## ByBlock + +An entity of a block set `"ByBlock"` takes the color of the insert that places the block: its own +color, its layer's when the insert is ByLayer, and the color of the insert around it when the +insert is ByBlock too. An entity on layer `"0"` of a block that is ByLayer draws in the insert's +layer's color, not in the insert's own color. An entity ByBlock outside any block draws as index 7. + +```ts +d.block("VALVE", {}, () => { + d.layer("0", {}, () => d.circle([0, 0], 0.5, { color: "ByBlock" })); +}); +d.layer("C-WATR", { color: 5 }, () => { + d.insert("VALVE", [10, 10]); // blue, its layer's color + d.insert("VALVE", [20, 10], { color: 1 }); // red +}); +``` + +## In a paragraph + +A paragraph's `\C` code colors the characters after it by an index: `\C1;` red, `\C0;` ByBlock and +`\C256;` ByLayer, the layer's color, not the paragraph's own. `\c` gives a true color as one number, +with its blue first: `\c255;` is red, `\c16711680;` blue, and `\c65280;` green. + +```ts +d.paragraph("EXISTING {\\C1;TO BE REMOVED}", { at: [0, 0], height: 0.125 }); +``` + +## In the file + +The DXF holds an index in group 62, with 0 for ByBlock, and a true color in group 420 as +`0xRRGGBB` with an index beside it in group 62: the one the leading CAD app matches the true color to, +which tsdraft writes as they do. A drawing read back gives both, as [Reading](reading.md) says. diff --git a/docs/dimensions.md b/docs/dimensions.md index 796123d..c9993ac 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -152,8 +152,8 @@ Both take `style`, the name of the dimension style, and optionally: gap above the line too, and the line breaks for the wider of the two. - `id`, as any entity takes one: see [Ids](format.md#ids). -A dimension is on the current layer, and is drawn in that layer's color and lineweight. It -takes no linetype or lineweight of its own. It goes in model space or on a +A dimension is on the current layer, and is drawn in that layer's color and lineweight, or in a +`color` of its own, as [Colors](colors.md) says. It takes no linetype or lineweight of its own. It goes in model space or on a [layout](layouts.md), and not in a block. ### Radius, diameter and jogged radius diff --git a/docs/format.md b/docs/format.md index 44342b1..268af20 100644 --- a/docs/format.md +++ b/docs/format.md @@ -36,6 +36,10 @@ existed. A linetype has `marks` only where it draws a text or a shape, and a polyline `linetypeGeneration` only where it is `true`, so a drawing with neither has the JSON it had before they existed. +Every entity but a table, an insert, a dimension and a leader included, has a `color` where it has +one of its own: an index from 1 to 255, `"ByBlock"`, or a true color `[red, green, blue]`. A drawing whose +entities draw ByLayer has the JSON it had before colors existed. [Colors](colors.md) describes them. + A drawing lists its blocks in `blocks`, and leaves the field out when it has none. A block has a `name`, its `entities`, and where they differ from their defaults a `base` point and its `attributes`: each a `tag`, a `value`, a `layer` and the fields of a text, with a `prompt` diff --git a/docs/paragraphs.md b/docs/paragraphs.md index 4a8657a..fce0b0a 100644 --- a/docs/paragraphs.md +++ b/docs/paragraphs.md @@ -82,7 +82,8 @@ these: | `\W0.8;` | Their width factor, in the place of the style's | | `\Q15;` | Their oblique angle in degrees, -85 to 85, in the place of the style's | | `\A0;` to `\A2;` | Where they sit on the line: on the baseline, centered or at the top | -| `\C1;` | A color by its index, which moves nothing and which the preview draws | +| `\C1;` | A color by its index, `\C0;` ByBlock and `\C256;` ByLayer: see colors.md | +| `\c255;` | A true color, its blue first, so 255 is red, which moves nothing | | `\fArial\|b1;` | A TrueType font of `FONTS`, in bold with `b1`: `i0`, `c` and `p` pass | | `\Fromans.shx;` | An SHX font of `FONTS` | | `\S1/2;` | A fraction stacked over a level bar | @@ -183,10 +184,9 @@ message names the code. lay out. - A code of the table above whose number is not one it takes: a height or width factor of 0 or of more than 15 digits before its point, an oblique angle past 85, `\A` other than 0, 1 or 2, a - color number past 257. + color number past 257, and a true color past 16777215. - The codes tsdraft does not lay out yet: `\T` the spacing of the characters after it, which the - leading CAD app plots as a spacing of its own between characters; `\c`, a true color, which - the preview cannot draw as the plot does yet; `\O`, an overline, which sits + leading CAD app plots as a spacing of its own between characters; `\O`, an overline, which sits at a TrueType font's ascent, which tsdraft's tables do not hold; `\X`, which only a dimension's text holds; and `\M+NXXXX`, a character of a code page. A paragraph that held one would plot otherwise than tsdraft draws it. diff --git a/docs/reading.md b/docs/reading.md index ce275e0..2d5b2cf 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -244,8 +244,10 @@ handle where the table gives none. Without a sort table they draw in the order o order of `entities`. Each keeps the pen it sets for itself, each part left out when it is ByLayer: `color`, an index -with 0 for ByBlock, `trueColor` as `0xRRGGBB`, `linetype`, `lineweight` in hundredths of a -millimeter with -2 for ByBlock and -3 for the default, and `linetypeScale`. +with 0 for ByBlock, and with a true color the index CAD programs match it to; `trueColor` as +`0xRRGGBB`; `colorBook`, the `book` and the `name` of a color of a color book, whose true color +`trueColor` holds; `linetype`, `lineweight` in hundredths of a millimeter with -2 for ByBlock and +-3 for the default, and `linetypeScale`. A text, an attribute and an attribute definition say where they are and how they are justified: `align` and `valign` as a `Text` has them, or `aligned`, `fit` or `middle`; `alignAt`, the point diff --git a/docs/rules.md b/docs/rules.md index 8eaf822..bf847f1 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -143,12 +143,15 @@ it would take `1e+100` for `1e+10` and report nothing. - A lineweight is one of the leading CAD app's: 0, 0.05, 0.09, 0.13, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.53, 0.6, 0.7, 0.8, 0.9, 1, 1.06, 1.2, 1.4, 1.58, 2 or 2.11 millimetres. That app discards a drawing with an entity of any other. +- An entity's color is an index from 1 to 255, `"ByLayer"`, `"ByBlock"` or a true color of + three whole numbers from 0 to 255. CAD programs store 0 for ByBlock and 256 for ByLayer, which + tsdraft takes only by those names. - Layer `0` cannot be frozen. It is the current layer, and the leading CAD app does not freeze the current layer. - The linetype scale is a size, like a radius. The leading CAD app reads 0 or less as 1. - An R12 drawing has no linetypes but `Continuous`, no linetype scale, no - lineweights and no layer states. Its entities take no linetype or lineweight - of their own, and draw ByLayer. Its texts are in `Standard`, left on the + lineweights and no layer states. Its entities take no color, linetype or + lineweight of their own, and draw ByLayer. Its texts are in `Standard`, left on the baseline, and it defines no text style. - Block names follow the rules of layer names. The leading CAD app discards a drawing over a block name it refuses. It keeps names that start with `*` for the blocks it makes itself, and its diff --git a/examples/site-plan.ts b/examples/site-plan.ts index f0b587e..abb6974 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -364,9 +364,12 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee d.line([view.left, pavement.near], [open.from, pavement.near]); d.line([open.to, pavement.near], [view.right, pavement.near]); d.line([view.left, pavement.far], [view.right, pavement.far]); + // The existing sidewalk plots gray among the black: a true color plots as it is, whatever the + // sheet's plot style table, where an index plots black under the standard's monochrome.ctb. + const existing = { color: [128, 128, 128] } as const; for (const y of [-sidewalk.fromLot, -sidewalk.fromLot - sidewalk.width]) { - d.line([view.left, y], [driveX, y]); - d.line([driveX + driveway.width, y], [view.right, y]); + d.line([view.left, y], [driveX, y], existing); + d.line([driveX + driveway.width, y], [view.right, y], existing); } }); d.layer("C-ROAD-CNTR", () => d.line([view.left, centerline], [view.right, centerline])); diff --git a/src/blocks.ts b/src/blocks.ts index 31b3ef9..f10d310 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -9,10 +9,12 @@ import type { Paragraph, ParagraphAttributeDefinition, Point, + Rgb, Text, TextStyle, Xref, } from "./drawing.ts"; +import { isRgb } from "./colors.ts"; import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; import { STANDARD_FONT } from "./fonts.ts"; @@ -719,6 +721,24 @@ export function referencedTree( return { xrefs: top, problems, unreported, unreportedShapes: shapes }; } +/** The color of an insert that its entities set ByBlock take: its own, or its layer's. */ +export type BlockColor = { readonly color: number | Rgb } | { readonly layer: LayerRef }; + +/** + * The color an insert gives what its block sets ByBlock: its own index or true color, its layer's + * when it is ByLayer, and the color of the insert that holds it when it is ByBlock. + */ +function insertColor( + insert: Insert, + layer: LayerRef, + outer: BlockColor | undefined, +): BlockColor | undefined { + const color: unknown = insert.color; + if (color === "ByBlock") return outer; + if (typeof color === "number" || isRgb(color)) return { color }; + return { layer }; +} + /** Where one entity is drawn. */ export interface Placement { /** The matrix from the entity's coordinates to the drawing's, or undefined in model space. */ @@ -735,6 +755,11 @@ export interface Placement { * names. Undefined for an entity of the drawing itself. */ readonly from: Referenced | undefined; + /** + * The color an entity set `"ByBlock"` takes: the color of the insert that holds it, or its + * layer's where the insert is ByLayer. Undefined in model space, where ByBlock draws as index 7. + */ + readonly byBlock?: BlockColor | undefined; /** For the text of an insert's attribute, the attribute's tag. */ readonly attribute?: string; /** @@ -756,6 +781,8 @@ interface Entered { /** The block's base point. */ readonly base: Point | undefined; readonly layer: LayerRef; + /** The color what the block sets ByBlock takes. */ + readonly byBlock: BlockColor | undefined; readonly inside: Referenced | undefined; /** The blocks its inserts find theirs among. */ readonly inner: ReadonlyMap; @@ -825,6 +852,7 @@ export function eachDrawn( from: Referenced | undefined, outer: Matrix | undefined, layer: LayerRef, + byBlock: BlockColor | undefined, ): boolean => { if (isFrozen(layer)) return true; const name = key(insert.block); @@ -846,6 +874,7 @@ export function eachDrawn( outer, base: block?.base, layer, + byBlock: insertColor(insert, layer, byBlock), // What the insert holds names the layers, linetypes and text styles of this drawing. inside: referenced ?? from, inner: referenced ? referenced.blocks : within, @@ -854,7 +883,7 @@ export function eachDrawn( }); return true; }; - if (!enter(entity, blocks, undefined, undefined, { name: entity.layer })) return false; + if (!enter(entity, blocks, undefined, undefined, { name: entity.layer }, undefined)) return false; while (stack.length > 0) { const at = stack.at(-1)!; const { inside } = at; @@ -863,7 +892,9 @@ export function eachDrawn( // One at a time, so two that place one block do not find it open. if (at.queued !== undefined && at.queued.next < at.queued.inserts.length) { const insert = at.queued.inserts[at.queued.next++]!; - if (!enter(insert, at.inner, inside, at.matrix, layerOf(insert.layer))) return false; + if (!enter(insert, at.inner, inside, at.matrix, layerOf(insert.layer), at.byBlock)) { + return false; + } continue; } if (at.entities && !holds(at.items, at.next)) [at.entities, at.next] = [false, 0]; @@ -876,13 +907,16 @@ export function eachDrawn( layer: layerOf(item.layer), insertLayer: at.layer, from: inside, + byBlock: at.byBlock, }; draw(item, placement); if (inside !== undefined && holding !== undefined) { const inserts = holding(item, placement); at.queued = inserts.length > 0 ? { inserts, next: 0 } : undefined; } - } else if (!enter(item, at.inner, inside, at.matrix, layerOf(item.layer))) return false; + } else if (!enter(item, at.inner, inside, at.matrix, layerOf(item.layer), at.byBlock)) { + return false; + } continue; } if (holds(at.definitions, at.next)) { @@ -905,6 +939,7 @@ export function eachDrawn( layer: layerOf(definition.layer), insertLayer: at.layer, from: inside, + byBlock: at.byBlock, attribute: definition.tag, made: placed.paragraph!.uneven, }); @@ -915,6 +950,7 @@ export function eachDrawn( layer: layerOf(definition.layer), insertLayer: at.layer, from: inside, + byBlock: at.byBlock, attribute: definition.tag, }); continue; diff --git a/src/colors.ts b/src/colors.ts new file mode 100644 index 0000000..c0d34f6 --- /dev/null +++ b/src/colors.ts @@ -0,0 +1,122 @@ +// An entity's own color: an index of the color index CAD programs share, ByBlock, or a true color, +// and how each is written and plotted. +import type { EntityColor, Rgb } from "./drawing.ts"; +import { ENTITY_COLOR } from "./rules.ts"; + +/** The values of the five shades of each hue of the index, from the brightest. */ +const SHADES = [255, 204, 153, 127, 76] as const; + +/** + * The colors the leading CAD app matches a true color against to find the index it stores beside + * it, which are neither the colors it plots nor the colors it shows on screen. Indexes 10 to 249 + * are 24 hues 15 degrees apart from red, each in five shades, full and at half saturation, each + * channel the whole part of its exact value; 250 to 255 are grays from a fifth of white to white. + */ +const MATCHED: readonly Rgb[] = (() => { + const out: Rgb[] = [ + [0, 0, 0], + [255, 0, 0], + [255, 255, 0], + [0, 255, 0], + [0, 255, 255], + [0, 0, 255], + [255, 0, 255], + [255, 255, 255], + [128, 128, 128], + [192, 192, 192], + ]; + for (let index = 10; index < 250; index++) { + const hue = Math.floor(index / 10) - 1; + const value = SHADES[Math.floor((index % 10) / 2)]!; + // In 120ths of the value, so each channel's exact value is a whole number of them. + const low = index % 2 === 0 ? 0 : 60; + const step = (hue % 4) * 15; + const rising = low + ((120 - low) * step) / 60; + const falling = low + ((120 - low) * (60 - step)) / 60; + const of = (part: number) => Math.floor((value * part) / 120); + const [v, up, down, lo] = [of(120), of(rising), of(falling), of(low)]; + const sector = Math.floor(hue / 4); + out.push( + ( + [ + [v, up, lo], + [down, v, lo], + [lo, v, up], + [lo, down, v], + [up, lo, v], + [v, lo, down], + ] as const + )[sector]!, + ); + } + for (let k = 0; k < 6; k++) { + const gray = Math.floor((255 * (5 + 4 * k)) / 25); + out.push([gray, gray, gray]); + } + return out; +})(); + +/** + * The index the leading CAD app stores beside a true color: the nearest of `MATCHED` by the sum + * of the squares of the channels' differences, the lowest index where two are as near. + */ +export function matchedIndex(rgb: Rgb): number { + const [red, green, blue] = [rgb[0], rgb[1], rgb[2]]; + let best = 1; + let nearest = Infinity; + for (let index = 1; index <= 255; index++) { + const [r, g, b] = MATCHED[index]!; + const distance = (red - r) ** 2 + (green - g) ** 2 + (blue - b) ** 2; + if (distance < nearest) [best, nearest] = [index, distance]; + } + return best; +} + +/** A true color as one number, 0xRRGGBB, as DXF group 420 holds it. */ +export const rgbValue = (rgb: Rgb): number => (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]; + +/** True for a true color: three whole numbers from 0 to 255. */ +export function isRgb(value: unknown): value is Rgb { + if (!Array.isArray(value) || value.length !== 3) return false; + // Read by index, so an empty slot is no channel. + for (let k = 0; k < 3; k++) { + const v: unknown = value[k]; + if (!Number.isInteger(v) || (v as number) < 0 || (v as number) > 255) return false; + } + return true; +} + +/** What is wrong with an entity's color, or undefined when it is one. */ +export function entityColorProblem(color: unknown): string | undefined { + if (color === "ByLayer" || color === "ByBlock") return undefined; + if (typeof color === "number") { + return Number.isInteger(color) && color >= 1 && color <= 255 ? undefined : ENTITY_COLOR; + } + return isRgb(color) ? undefined : ENTITY_COLOR; +} + +/** + * What a file holds of an entity's color: its index, 0 for ByBlock, and with a true color the + * index the leading CAD app matches it to; and the true color. Undefined for ByLayer, which a file + * leaves out. + */ +export function storedColor( + color: EntityColor | undefined, +): { readonly index: number; readonly rgb?: number } | undefined { + if (color === undefined || color === "ByLayer") return undefined; + if (color === "ByBlock") return { index: 0 }; + if (typeof color === "number") return { index: color }; + return { index: matchedIndex(color), rgb: rgbValue(color) }; +} + +/** + * A color as a multileader holds the color of its note, 32 bits: 0xC0 and nothing for ByLayer, + * 0xC1 for ByBlock, 0xC3 and the index, and 0xC2 and a true color. The leading CAD app saves a + * leader's own color there. + */ +export function heldColor(color: EntityColor | undefined): number { + const stored = storedColor(color); + if (stored === undefined) return 0xc0000000 | 0; + if (stored.rgb !== undefined) return 0xc2000000 | stored.rgb | 0; + return stored.index === 0 ? 0xc1000000 | 0 : 0xc3000000 | stored.index | 0; +} diff --git a/src/drawing.ts b/src/drawing.ts index 400dd3f..2c2bcec 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -1,3 +1,4 @@ +import { entityColorProblem } from "./colors.ts"; import type { ParagraphColumns } from "./paragraphs.ts"; import { definitionHandle, @@ -111,6 +112,7 @@ import { leaderStyleProblem, leaderStyleTwinProblem, standardTableStyleProblem, + TABLE_COLOR, TABLE_IN_BLOCK, tableColumnsProblem, tableTextsProblem, @@ -223,6 +225,9 @@ import { type WidthFactor, type XrefPath, type LayerColor, + type EntityColorGiven, + type EntityColorOf, + type R12EntityColor, type LayerName, type LayoutName, type PaperLength, @@ -462,6 +467,17 @@ export interface Layer { readonly plot?: boolean; } +/** A true color: its red, green and blue, each a whole number from 0 to 255. */ +export type Rgb = readonly [red: number, green: number, blue: number]; + +/** + * An entity's color: an index of the color index CAD programs share, from 1 to 255; `"ByLayer"`, + * its layer's; `"ByBlock"`, the color of the insert that places its block; or a true color. CAD + * programs plot an index through the layout's plot style table, and a true color as it is under + * every table. + */ +export type EntityColor = number | "ByLayer" | "ByBlock" | Rgb; + interface Placed { /** * A name for this entity that stays the same when the drawing's code changes around it: 1 to @@ -474,6 +490,8 @@ interface Placed { * places the block. */ readonly layer: string; + /** Its own color. Defaults to `"ByLayer"`. R2018 only. */ + readonly color?: EntityColor; } interface EntityBase extends Placed { @@ -1058,9 +1076,6 @@ export type HatchPatternChoice = readonly origin?: Point; }; -/** A true color: its red, green and blue, each a whole number from 0 to 255. */ -export type Rgb = readonly [red: number, green: number, blue: number]; - /** * How a gradient runs from its first color to its second. `linear` runs across the box of the * loops; `cylinder` from the first color at both sides to the second along the middle; `spherical` @@ -1773,12 +1788,15 @@ export interface EntityOptions< I extends string = string, Z extends Standard | undefined = undefined, P extends string = string, + C extends EntityColorGiven = EntityColor, > { /** * A name for the entity that no other entity of the drawing has: 1 to 64 letters A to Z or a * to z, digits, `.`, `-` and `_`. Diagnostics and `toSVG` carry it. */ readonly id?: EntityId; + /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ + readonly color?: V extends "R12" ? "ByLayer" | R12EntityColor : EntityColorOf; /** * A linetype of the drawing, `"Continuous"`, `"ByBlock"` or `"ByLayer"`. R2018 only. Under a * standard, a linetype of the standard by name, which the drawing then has. @@ -1817,7 +1835,8 @@ export interface EllipseOptions< I extends string = string, Z extends Standard | undefined = undefined, P extends string = string, -> extends EntityOptions { + O extends EntityColorGiven = EntityColor, +> extends EntityOptions { /** * For an arc of the ellipse, the parameter it starts at, in degrees counterclockwise from the end * of the major axis. Given with `endParameter` or not at all. Brought into 0 up to 360. @@ -1839,7 +1858,8 @@ export interface SplineOptions< S extends Point = Point, E extends Point = Point, C extends boolean = boolean, -> extends EntityOptions { + O extends EntityColorGiven = EntityColor, +> extends EntityOptions { /** The direction it leaves the first point in. Worked out from the points when left out. */ readonly startTangent?: [C] extends [true] ? typeof SPLINE_CLOSED_TANGENT : Tangent; /** The direction it arrives at the last point in. Worked out from the points when left out. */ @@ -1861,7 +1881,8 @@ export interface ControlSplineOptions< K extends readonly number[] = readonly number[], C extends readonly Point[] = readonly Point[], H extends readonly number[] = readonly number[], -> extends EntityOptions { + O extends EntityColorGiven = EntityColor, +> extends EntityOptions { /** From 1 up to `SPLINE_DEGREE_MOST`. Defaults to 3. */ readonly degree?: SplineDegree; /** @@ -1921,7 +1942,8 @@ export type HatchOptions< P extends string = string, S extends number = number, G extends HatchGradient = HatchGradient, -> = EntityOptions & + C extends EntityColorGiven = EntityColor, +> = EntityOptions & ( | { /** @@ -1968,8 +1990,9 @@ export interface PolylineOptions< P extends string = string, N extends number = number, R extends number = number, + C extends EntityColorGiven = EntityColor, > - extends EntityOptions, Widened { + extends EntityOptions, Widened { /** * The bulge of each side, one for each: 0 for a straight side, and for an arc the tangent of a * quarter of the angle it turns through, greater than 0 when it turns counterclockwise. @@ -2002,7 +2025,8 @@ export interface RectOptions< Z extends Standard | undefined = undefined, P extends string = string, R extends number = number, -> extends EntityOptions { + C extends EntityColorGiven = EntityColor, +> extends EntityOptions { /** Rounds each corner with a quarter circle of this radius, at most half the shorter side. R2018 only. */ readonly radius?: V extends "R12" ? R12Polylines : Positive; } @@ -2022,8 +2046,9 @@ export interface CloudOptions< Z extends Standard | undefined = undefined, P extends string = string, N extends number = number, + C extends EntityColorGiven = EntityColor, > - extends EntityOptions<"R2018", T, W, L, I, Z, P>, Widened<"R2018", N> { + extends EntityOptions<"R2018", T, W, L, I, Z, P, C>, Widened<"R2018", N> { /** * About how far apart the ends of each arc are, in drawing units: each side of the outline * holds the whole number of arcs nearest its length over this, and at least one. @@ -2044,7 +2069,8 @@ export interface DonutOptions< I extends string = string, Z extends Standard | undefined = undefined, P extends string = string, -> extends EntityOptions<"R2018", T, W, L, I, Z, P> { + C extends EntityColorGiven = EntityColor, +> extends EntityOptions<"R2018", T, W, L, I, Z, P, C> { /** The diameter of its hole, less than the outside diameter. Defaults to 0: a filled dot. */ readonly inside?: DonutHole; } @@ -2065,7 +2091,8 @@ export interface ImageOptions< I extends string = string, Z extends Standard | undefined = undefined, P extends string = string, -> extends EntityOptions<"R2018", T, W, L, I, Z, P> { + C extends EntityColorGiven = EntityColor, +> extends EntityOptions<"R2018", T, W, L, I, Z, P, C> { /** The file's width and height in pixels, which `rasterSize` reads from its bytes. */ readonly pixels: readonly [width: number, height: number]; /** How wide the image is along its bottom edge, in drawing units. */ @@ -2148,7 +2175,8 @@ export type TextOptions< Z extends Standard | undefined = undefined, P extends string = string, R extends string = string, -> = EntityOptions & + C extends EntityColorGiven = EntityColor, +> = EntityOptions & TextPlacement & Sized< Z, @@ -2189,7 +2217,8 @@ export type ParagraphOptions< R extends string = string, N extends number = number, F extends number = number, -> = EntityOptions<"R2018", T, W, L, I, Z, P> & + C extends EntityColorGiven = EntityColor, +> = EntityOptions<"R2018", T, W, L, I, Z, P, C> & ParagraphPlacement & Sized, TextStyleChoice>; @@ -2347,7 +2376,8 @@ export type InsertOptions< S extends number | readonly [number, number] = number, I extends string = string, Z extends Standard | undefined = undefined, -> = InsertFields & + C extends EntityColorGiven = EntityColor, +> = InsertFields & (Z extends Standard ? | (Scaled & { readonly view: View }) @@ -2355,12 +2385,14 @@ export type InsertOptions< : Scaled>); /** What an insert holds besides its scale and its view. */ -interface InsertFields { +interface InsertFields { /** * A name for the insert that no other entity of the drawing has. The insert's attributes * keep their handles with it. */ readonly id?: EntityId; + /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ + readonly color?: EntityColorOf; /** Degrees counterclockwise, about the insert's point. Defaults to 0. */ readonly rotation?: number; /** A value for each attribute to set, by its tag. The others have their default values. */ @@ -2496,6 +2528,7 @@ interface DimensionOptions< S extends string = string, T extends string = string, I extends string = string, + C extends EntityColorGiven = EntityColor, > { /** A dimension style of the drawing. */ readonly style: DimensionStyleName; @@ -2511,6 +2544,8 @@ interface DimensionOptions< readonly textBelow?: DimensionText; /** A name for the dimension that no other entity of the drawing has. */ readonly id?: EntityId; + /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ + readonly color?: EntityColorOf; readonly view?: ViewWithoutStandard; } @@ -2519,7 +2554,8 @@ export interface LinearDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> extends DimensionOptions { + C extends EntityColorGiven = EntityColor, +> extends DimensionOptions { /** * The direction it measures along: `"x"`, the default, `"y"`, or an angle in degrees * counterclockwise from +X. @@ -2532,14 +2568,16 @@ export type AlignedDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> = DimensionOptions; + C extends EntityColorGiven = EntityColor, +> = DimensionOptions; /** The options of `radiusDimension()`. */ export interface RadiusDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> extends DimensionOptions { + C extends EntityColorGiven = EntityColor, +> extends DimensionOptions { /** * How far the middle of its text is from the center, along its line, past the center for less * than 0. Left out, the text stands outside the circle, past the arrowhead. @@ -2552,21 +2590,24 @@ export type DiameterDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> = RadiusDimensionOptions; + C extends EntityColorGiven = EntityColor, +> = RadiusDimensionOptions; /** The options of `arcLengthDimension()`. */ export type ArcLengthDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> = DimensionOptions; + C extends EntityColorGiven = EntityColor, +> = DimensionOptions; /** The options of `ordinateDimension()`. */ export interface OrdinateDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> extends DimensionOptions { + C extends EntityColorGiven = EntityColor, +> extends DimensionOptions { /** `"x"` gives the feature's X from the origin, with its leader along Y; `"y"` its Y. */ readonly axis: "x" | "y"; /** The point it measures from. Defaults to `[0, 0]`. */ @@ -2578,14 +2619,16 @@ export type AngularDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> = DimensionOptions; + C extends EntityColorGiven = EntityColor, +> = DimensionOptions; /** The options of `joggedRadiusDimension()`. */ export type JoggedRadiusDimensionOptions< S extends string = string, T extends string = string, I extends string = string, -> = DimensionOptions; + C extends EntityColorGiven = EntityColor, +> = DimensionOptions; /** * What a dimension is drawn with under the standard `Z`: a dimension style of the standard by its @@ -2600,6 +2643,7 @@ export interface StandardAlignedDimensionOptions< T extends string = string, I extends string = string, Z extends Standard = Standard, + C extends EntityColorGiven = EntityColor, > { /** A dimension style of the standard, by its id. Defaults to its `defaultDimensionStyle`. */ readonly style?: DimensionStyleOfStandard; @@ -2614,6 +2658,8 @@ export interface StandardAlignedDimensionOptions< readonly textBelow?: DimensionText; /** A name for the dimension that no other entity of the drawing has. */ readonly id?: EntityId; + /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ + readonly color?: EntityColorOf; } /** The options of `radiusDimension()` and `diameterDimension()` under the standard `Z`. */ @@ -2622,7 +2668,8 @@ export interface StandardRadiusDimensionOptions< T extends string = string, I extends string = string, Z extends Standard = Standard, -> extends StandardAlignedDimensionOptions { + C extends EntityColorGiven = EntityColor, +> extends StandardAlignedDimensionOptions { /** How far the middle of its text is from the center, as `RadiusDimensionOptions` says. */ readonly textFromCenter?: number; } @@ -2633,7 +2680,8 @@ export interface StandardOrdinateDimensionOptions< T extends string = string, I extends string = string, Z extends Standard = Standard, -> extends StandardAlignedDimensionOptions { + C extends EntityColorGiven = EntityColor, +> extends StandardAlignedDimensionOptions { /** `"x"` gives the feature's X from the origin, with its leader along Y; `"y"` its Y. */ readonly axis: "x" | "y"; /** The point it measures from. Defaults to `[0, 0]`. */ @@ -2646,7 +2694,8 @@ export interface StandardLinearDimensionOptions< T extends string = string, I extends string = string, Z extends Standard = Standard, -> extends StandardAlignedDimensionOptions { + C extends EntityColorGiven = EntityColor, +> extends StandardAlignedDimensionOptions { /** * The direction it measures along: `"x"`, the default, `"y"`, or an angle in degrees * counterclockwise from +X. @@ -2757,6 +2806,7 @@ export interface LeaderOptions< G extends number = number, TO extends LeaderTargets = LeaderTargets, W extends number = number, + C extends EntityColorGiven = EntityColor, > extends LeaderPlacement { /** A leader style of the drawing. */ readonly style: LeaderStyleName; @@ -2774,6 +2824,8 @@ export interface LeaderOptions< readonly gap?: LeaderSize; /** A name for the leader that no other entity of the drawing has. */ readonly id?: EntityId; + /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ + readonly color?: EntityColorOf; readonly view?: ViewWithoutStandard; readonly role?: RoleWithoutStandard; } @@ -2796,6 +2848,7 @@ export interface StandardLeaderOptions< G extends number = number, TO extends LeaderTargets = LeaderTargets, W extends number = number, + C extends EntityColorGiven = EntityColor, > extends LeaderPlacement { /** A leader style of the standard, by its id. Defaults to its `defaultLeaderStyle`. */ readonly style?: LeaderStyleOfStandard; @@ -2813,13 +2866,18 @@ export interface StandardLeaderOptions< readonly gap?: LeaderSize; /** A name for the leader that no other entity of the drawing has. */ readonly id?: EntityId; + /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ + readonly color?: EntityColorOf; readonly textStyle?: LeaderRoleAndText; readonly textHeight?: LeaderRoleAndText; } /** What `layout()` sets on a layout. */ /** The options of `table()`: the table, but for its kind and its layer, which is the current one. */ -export type TableOptions = Omit; +export type TableOptions = Omit & { + /** A table has no color of its own: its style and its cells give its colors. */ + readonly color?: "ByLayer"; +}; export interface LayoutOptions

{ /** One of `PAPERS`, such as `"ARCH D"`. */ @@ -3526,7 +3584,8 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, - >(from: Point, to: Point, options: EntityOptions = {}): this { + const C extends EntityColorGiven = EntityColor, + >(from: Point, to: Point, options: EntityOptions = {}): this { return this.#add(DrawingBuilder.prototype.line, options, () => ({ kind: "line", layer: this.#current, @@ -3548,10 +3607,11 @@ export class DrawingBuilder< P extends string = string, N extends number = number, R extends number = number, + const C extends EntityColorGiven = EntityColor, >( points: readonly Point[], closed = false, - options: PolylineOptions = {}, + options: PolylineOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.polyline, options, () => { if (points.length < 2) refuse("geometry", "A polyline needs at least 2 points"); @@ -3572,11 +3632,12 @@ export class DrawingBuilder< I extends string = string, P extends string = string, R extends number = number, + const C extends EntityColorGiven = EntityColor, >( corner: Point, width: Positive, height: Positive, - options: RectOptions = {}, + options: RectOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.rect, options, () => { const [x, y] = pt(corner); @@ -3611,9 +3672,10 @@ export class DrawingBuilder< I extends string = string, P extends string = string, N extends number = number, + const C extends EntityColorGiven = EntityColor, >( outline: readonly Point[], - options: V extends "R12" ? R12Polylines : CloudOptions, + options: V extends "R12" ? R12Polylines : CloudOptions, ): this { const o = options as unknown as CloudOptions; return this.#add(DrawingBuilder.prototype.cloud, o, () => { @@ -3650,10 +3712,11 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, + const C extends EntityColorGiven = EntityColor, >( center: Point, outside: V extends "R12" ? R12Polylines : Positive, - options?: V extends "R12" ? R12Polylines : DonutOptions, + options?: V extends "R12" ? R12Polylines : DonutOptions, ): this { const o = (options ?? {}) as unknown as DonutOptions; return this.#add(DrawingBuilder.prototype.donut, o, () => { @@ -3723,9 +3786,10 @@ export class DrawingBuilder< P extends string = string, S extends number = number, const G extends HatchGradient = HatchGradient, + const C extends EntityColorGiven = EntityColor, >( boundary: readonly Point[] | readonly HatchLoop[], - options: HatchOptions = {}, + options: HatchOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.hatch, options, () => { if (this.dxf === "R12") refuse("hatch", R12_ONLY.hatches); @@ -3811,7 +3875,8 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, - >(points: readonly Point[], options: EntityOptions = {}): this { + const C extends EntityColorGiven = EntityColor, + >(points: readonly Point[], options: EntityOptions = {}): this { return this.#add(DrawingBuilder.prototype.wipeout, options, () => { if (this.dxf === "R12") refuse("wipeout", R12_ONLY.hatches); if (!Array.isArray(points) || points.length < 3) @@ -3844,10 +3909,11 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, + const C extends EntityColorGiven = EntityColor, >( path: V extends "R12" ? R12Images : ImagePath, at: Point, - options: V extends "R12" ? R12Images : ImageOptions, + options: V extends "R12" ? R12Images : ImageOptions, ): this { const o = options as unknown as ImageOptions; return this.#add(DrawingBuilder.prototype.image, o, () => { @@ -3965,7 +4031,8 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, - >(center: Point, radius: Positive, options: EntityOptions = {}): this { + const C extends EntityColorGiven = EntityColor, + >(center: Point, radius: Positive, options: EntityOptions = {}): this { return this.#add(DrawingBuilder.prototype.circle, options, () => ({ kind: "circle", layer: this.#current, @@ -3990,12 +4057,13 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, + const C extends EntityColorGiven = EntityColor, >( center: Point, radius: Positive, startAngle: number, endAngle: number, - options: EntityOptions = {}, + options: EntityOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.arc, options, () => { const start = turn(num(startAngle, "startAngle")); @@ -4032,11 +4100,12 @@ export class DrawingBuilder< const L extends LinetypeValue = LinetypeDefinition, I extends string = string, P extends string = string, + const O extends EntityColorGiven = EntityColor, >( center: Point, majorAxis: Point, ratio: EllipseRatio, - options: EllipseOptions = {}, + options: EllipseOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.ellipse, options, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); @@ -4078,12 +4147,13 @@ export class DrawingBuilder< const S extends Point = Point, const E extends Point = Point, C extends boolean = false, - >(fitPoints: FitPoints, options: SplineOptions = {}): this { + const O extends EntityColorGiven = EntityColor, + >(fitPoints: FitPoints, options: SplineOptions = {}): this { return this.#add(DrawingBuilder.prototype.spline, options, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); if (!Array.isArray(fitPoints)) refuse("geometry", "A spline's fit points are a list of points"); - const o = options as SplineOptions; + const o = options as unknown as SplineOptions; const points = (fitPoints as readonly Point[]).map(pt); const startTangent = o.startTangent === undefined ? undefined : pt(o.startTangent as Point); const endTangent = o.endTangent === undefined ? undefined : pt(o.endTangent as Point); @@ -4127,15 +4197,16 @@ export class DrawingBuilder< D extends number = 3, const K extends readonly number[] = readonly number[], const H extends readonly number[] = readonly number[], + const O extends EntityColorGiven = EntityColor, >( controlPoints: ControlPoints, - options: ControlSplineOptions = {}, + options: ControlSplineOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.controlSpline, options, () => { if (this.dxf === "R12") refuse("geometry", R12_ONLY.curves); if (!Array.isArray(controlPoints)) refuse("geometry", "A spline's control points are a list of points"); - const o = options as ControlSplineOptions; + const o = options as unknown as ControlSplineOptions; const degree: unknown = o.degree ?? 3; const given = (controlPoints as readonly Point[]).map(pt); const closed = o.closed === true; @@ -4191,7 +4262,8 @@ export class DrawingBuilder< const D extends TextStyleValue = TextStyleDefinition, P extends string = string, R extends string = string, - >(at: Point, value: string, options: TextOptions = {}): this { + const C extends EntityColorGiven = EntityColor, + >(at: Point, value: string, options: TextOptions = {}): this { return this.#add(DrawingBuilder.prototype.text, options, () => ({ kind: "text", layer: this.#current, @@ -4227,9 +4299,12 @@ export class DrawingBuilder< R extends string = string, N extends number = number, F extends number = number, + const C extends EntityColorGiven = EntityColor, >( value: ParagraphValue, - options: V extends "R12" ? R12Paragraphs : ParagraphOptions, + options: V extends "R12" + ? R12Paragraphs + : ParagraphOptions, ): this { const o = options as unknown as ParagraphOptions; return this.#add(DrawingBuilder.prototype.paragraph, o, () => { @@ -4575,10 +4650,11 @@ export class DrawingBuilder< N extends string, const S extends number | readonly [number, number] = number, I extends string = string, + const C extends EntityColorGiven = EntityColor, >( block: V extends "R12" ? R12Blocks : BlockName, at: Point, - options: InsertOptions = {}, + options: InsertOptions = {}, ): this { return this.#add(DrawingBuilder.prototype.insert, options, () => this.#placed(block, at, options), @@ -4837,15 +4913,20 @@ export class DrawingBuilder< * or along `options.along`, with its dimension line through `line`. The leading CAD app holds it * as a dimension, which reads its length again when its points move. */ - linearDimension( + linearDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( from: Point, to: Point, line: Point, options: Z extends Standard - ? StandardLinearDimensionOptions + ? StandardLinearDimensionOptions : V extends "R12" ? R12Dimensions - : LinearDimensionOptions, + : LinearDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.linearDimension, idOf(options), () => { const o = options as unknown as LinearDimensionOptions | undefined; @@ -4876,15 +4957,20 @@ export class DrawingBuilder< * its dimension line `offset` to the left of the way from the first to the second, or to the * right for an offset less than 0. */ - alignedDimension( + alignedDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( from: Point, to: Point, offset: number, options: Z extends Standard - ? StandardAlignedDimensionOptions + ? StandardAlignedDimensionOptions : V extends "R12" ? R12Dimensions - : AlignedDimensionOptions, + : AlignedDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.alignedDimension, idOf(options), () => this.#dimension(options as unknown as AlignedDimensionOptions | undefined, (style, text) => ({ @@ -4904,14 +4990,19 @@ export class DrawingBuilder< * of the circle or arc it measures, read with an R. Its line runs from the center through * `point`, and its text stands outside the circle unless `options.textFromCenter` places it. */ - radiusDimension( + radiusDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( center: Point, point: Point, options: Z extends Standard - ? StandardRadiusDimensionOptions + ? StandardRadiusDimensionOptions : V extends "R12" ? R12Dimensions - : RadiusDimensionOptions, + : RadiusDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.radiusDimension, idOf(options), () => this.#radial("radius-dimension", center, point, options), @@ -4924,14 +5015,19 @@ export class DrawingBuilder< * opposite, and its text stands at `point`'s end, outside the circle unless * `options.textFromCenter` places it. */ - diameterDimension( + diameterDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( center: Point, point: Point, options: Z extends Standard - ? StandardRadiusDimensionOptions + ? StandardRadiusDimensionOptions : V extends "R12" ? R12Dimensions - : DiameterDimensionOptions, + : DiameterDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.diameterDimension, idOf(options), () => this.#radial("diameter-dimension", center, point, options), @@ -4943,16 +5039,21 @@ export class DrawingBuilder< * for an arc whose center is far off. Its line starts at `start`, jogs across at `jog`, and runs * on toward the center to `point`, with its text along the last stretch. */ - joggedRadiusDimension( + joggedRadiusDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( center: Point, point: Point, start: Point, jog: Point, options: Z extends Standard - ? StandardAlignedDimensionOptions + ? StandardAlignedDimensionOptions : V extends "R12" ? R12Dimensions - : JoggedRadiusDimensionOptions, + : JoggedRadiusDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.joggedRadiusDimension, idOf(options), () => this.#dimension( @@ -4976,16 +5077,21 @@ export class DrawingBuilder< * `from` and to `to`, with its arc through `at`. The arc's point picks which angle, so the order * of `from` and `to` means nothing. */ - angularDimension( + angularDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( vertex: Point, from: Point, to: Point, at: Point, options: Z extends Standard - ? StandardAlignedDimensionOptions + ? StandardAlignedDimensionOptions : V extends "R12" ? R12Dimensions - : AngularDimensionOptions, + : AngularDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.angularDimension, idOf(options), () => this.#dimension(options as unknown as AngularDimensionOptions | undefined, (style, text) => ({ @@ -5006,17 +5112,22 @@ export class DrawingBuilder< * `radius`, counterclockwise from `startAngle` to `endAngle` in degrees, as `arc` takes them, * with its own arc through `at`. */ - arcLengthDimension( + arcLengthDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( center: Point, radius: number, startAngle: number, endAngle: number, at: Point, options: Z extends Standard - ? StandardAlignedDimensionOptions + ? StandardAlignedDimensionOptions : V extends "R12" ? R12Dimensions - : ArcLengthDimensionOptions, + : ArcLengthDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.arcLengthDimension, idOf(options), () => this.#dimension( @@ -5040,14 +5151,19 @@ export class DrawingBuilder< * Draws an ordinate dimension on the current layer: the distance from `options.origin`, or from * `[0, 0]`, to `feature` along `options.axis`, on a leader from near `feature` to `leaderEnd`. */ - ordinateDimension( + ordinateDimension< + S extends string, + T extends string = string, + I extends string = string, + const C extends EntityColorGiven = EntityColor, + >( feature: Point, leaderEnd: Point, options: Z extends Standard - ? StandardOrdinateDimensionOptions + ? StandardOrdinateDimensionOptions : V extends "R12" ? R12Dimensions - : OrdinateDimensionOptions, + : OrdinateDimensionOptions, ): this { return this.#add(DrawingBuilder.prototype.ordinateDimension, idOf(options), () => { const o = options as unknown as OrdinateDimensionOptions | undefined; @@ -5494,6 +5610,7 @@ export class DrawingBuilder< if (this.dxf === "R12") refuse("table", R12_ONLY.tables); if (this.#open) refuse("table", TABLE_IN_BLOCK); const o = (typeof given === "object" && given !== null ? given : {}) as Record; + if (o.color !== undefined && o.color !== "ByLayer") refuse("entity-color", TABLE_COLOR); const named = o.style; const nameProblem = tableStyleNameProblem(named); if (nameProblem) refuse("undefined-table-style", nameProblem); @@ -5564,13 +5681,14 @@ export class DrawingBuilder< R extends string = string, TO extends LeaderTargets = LeaderTargets, W extends number = number, + const C extends EntityColorGiven = EntityColor, >( text: LeaderText | LeaderBlockContent, options: Z extends Standard - ? StandardLeaderOptions + ? StandardLeaderOptions : V extends "R12" ? R12Leaders - : LeaderOptions, + : LeaderOptions, ): this { return this.#add(DrawingBuilder.prototype.leader, idOf(options), () => this.#leader(text as unknown, options as unknown), @@ -6609,7 +6727,9 @@ export class DrawingBuilder< const key = id === undefined ? undefined : this.#idKey(id); if (key !== undefined) this.#freeIdHandle(id as string); const named = id === undefined ? {} : { id: id as string }; - const made = { ...make(), ...named, ...this.#style(o) } as Entity; + // Before `make`, which takes a dimension's handles. + const color = this.#color(o); + const made = { ...make(), ...named, ...this.#style(o), ...color } as Entity; (this.#open ?? this.#sheet ?? { entities: this.#entities }).entities.push(made); if (this.#open && this.#drawsRoles(made, o)) this.#open.roles = true; if (key !== undefined) { @@ -6689,6 +6809,21 @@ export class DrawingBuilder< ); } + /** The color an entity is stored with: none for ByLayer, and a true color as a copy. */ + #color(options: object): { readonly color?: EntityColor } { + const color: unknown = (options as { readonly color?: unknown }).color; + if (color === undefined) return {}; + const problem = entityColorProblem(color); + if (problem) refuse("entity-color", problem); + if (color === "ByLayer") return {}; + if (this.dxf === "R12") refuse("entity-color", R12_ONLY.entityColor); + return { + color: Array.isArray(color) + ? ([color[0], color[1], color[2]] as const) + : (color as EntityColor), + }; + } + /** The linetype and lineweight an entity is stored with. */ #style(options: EntityOptions): EntityStyle { const style: { -readonly [K in keyof EntityStyle]: EntityStyle[K] } = {}; @@ -7037,10 +7172,10 @@ function titleBlockValues( return values; } -/** The id among the options of a dimension, which have no linetype or lineweight to take. */ -function idOf(options: unknown): { readonly id?: unknown } { - const id: unknown = (options as { id?: unknown } | null | undefined)?.id; - return id === undefined ? {} : { id }; +/** The id and the color among the options of a dimension, which have no linetype or lineweight to take. */ +function idOf(options: unknown): { readonly id?: unknown; readonly color?: unknown } { + const { id, color } = (options ?? {}) as { id?: unknown; color?: unknown }; + return { ...(id === undefined ? {} : { id }), ...(color === undefined ? {} : { color }) }; } /** diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index 6f5b322..c61b7fc 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -1,3 +1,4 @@ +import { heldColor, matchedIndex, storedColor } from "./colors.ts"; import { attributeTextStart, definitionHandle, @@ -44,6 +45,7 @@ import type { DimensionStyle, Drawing, Entity, + EntityColor, Image, Insert, Layout, @@ -67,7 +69,6 @@ import { isFitSpline } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; import { drawingTables } from "./table-pictures.ts"; import { clamped, fitSpline } from "./curves.ts"; -import { nearestColorIndex } from "./svg.ts"; import { dimensionMask, GRADIENT_NAMES, @@ -1258,6 +1259,7 @@ function writeInsert( g(100, "AcDbEntity"); if (paper) g(67, 1); g(8, e.layer); + writeColor(g, e.color); g(100, "AcDbBlockReference"); if (hasAttributes) g(66, 1); // attributes follow g(2, e.block); @@ -1465,6 +1467,14 @@ function writeSpline(g: Group, e: Spline, begin: () => void): void { /** The vertical justification of the text a paragraph attribute would be as a line. */ const TEXT_VALIGN_OF = { top: "top", middle: "middle", bottom: "bottom" } as const; +/** An entity's own color, after its linetype: group 62, and 420 for a true color. */ +function writeColor(g: Group, color: EntityColor | undefined): void { + const stored = storedColor(color); + if (stored === undefined) return; + g(62, stored.index); + if (stored.rgb !== undefined) g(420, stored.rgb); +} + /** * Writes an entity. `style` is the text style of a text that is not in `Standard`, and `paper` * is true for an entity of a layout. @@ -1487,6 +1497,7 @@ function writeEntity( g(8, e.layer); const linetype = entityLinetype(e); if (linetype !== undefined) g(6, linetype); + writeColor(g, e.color); if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { g(370, lineweightCode(e.lineweight)); } @@ -1654,7 +1665,7 @@ function writeEntity( g(453, 2); gradient.colors.forEach((color, k) => { g(463, k); - g(63, nearestColorIndex(color)); + g(63, matchedIndex(color)); g(421, rgbNumber(color)); }); g(470, GRADIENT_NAMES[gradient.name]); @@ -1826,6 +1837,7 @@ function writeDimension( g(100, "AcDbEntity"); if (paper) g(67, 1); g(8, e.layer); + writeColor(g, e.color); g(100, "AcDbDimension"); if (block !== undefined) g(2, block); point(g, 10, ...picture.definitionPoint); @@ -2472,6 +2484,7 @@ function writeImage(g: Group, e: Image, place: ImagePlace): void { g(8, e.layer); const linetype = entityLinetype(e); if (linetype !== undefined) g(6, linetype); + writeColor(g, e.color); if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { g(370, lineweightCode(e.lineweight)); } @@ -2727,6 +2740,7 @@ function writeLeader( g(100, "AcDbEntity"); if (where.paper) g(67, 1); g(8, e.layer); + writeColor(g, e.color); g(100, "AcDbMLeader"); g(270, 2); // version g(300, "CONTEXT_DATA{"); @@ -2783,7 +2797,7 @@ function writeLeader( g(44, 0); g(45, 1); // line spacing g(170, 1); // at least as set - g(90, COLOR_BY_LAYER); + g(90, heldColor(e.color)); // the note's color, the leader's own g(171, picture.noteAttachment); // held by its top left, top center or top right g(172, 5); // flow // A mask in the drawing's background, or in a color of its own. diff --git a/src/index.ts b/src/index.ts index 40f827b..33cc7e3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -147,6 +147,7 @@ export { type Point, type Rgb, type Polyline, + type EntityColor, type PolylineOptions, type RadiusDimension, type RadiusDimensionOptions, @@ -175,6 +176,7 @@ export { type Xref, type Zone, } from "./drawing.ts"; +export { heldColor, storedColor } from "./colors.ts"; export { toDXF, type DxfOptions } from "./dxf.ts"; export { parsePatterns, PATTERN_FILE_LENGTH } from "./patterns.ts"; export { fifteenDigits } from "./format.ts"; @@ -478,6 +480,7 @@ export { type ReadDimensionStyle, type ReadDrawingFile, type ReadEntity, + type ReadColorBook, type ReadEntityBase, type ReadField, type ReadHatch, diff --git a/src/lint.ts b/src/lint.ts index 547ad53..d9e7bbd 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -1,3 +1,4 @@ +import { entityColorProblem } from "./colors.ts"; import { definitionHandle, insertAttributeHandle, @@ -144,6 +145,7 @@ import { leaderStyleTwinProblem, isStandardTableStyle, standardTableStyleProblem, + TABLE_COLOR, TABLE_IN_BLOCK, tableColumnsProblem, tableTextsProblem, @@ -250,6 +252,7 @@ export type LintRule = | "duplicate-linetype" | "undefined-linetype" | "lineweight" + | "entity-color" | "layer-state" | "geometry" | "text" @@ -2195,6 +2198,14 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (layer) add("undefined-layer", "error", layer); const problems = geometryProblems(entity); for (const problem of problems) add("geometry", "error", problem); + const color: unknown = entity.color; + if (color !== undefined) { + const problem = + entityColorProblem(color) ?? + (r12 && color !== "ByLayer" ? R12_ONLY.entityColor : undefined) ?? + (entity.kind === "table" && color !== "ByLayer" ? TABLE_COLOR : undefined); + if (problem) add("entity-color", "error", problem); + } if ( r12 && entity.kind === "polyline" && diff --git a/src/paragraph-codes.ts b/src/paragraph-codes.ts index 9d3c81d..c2feed6 100644 --- a/src/paragraph-codes.ts +++ b/src/paragraph-codes.ts @@ -33,7 +33,6 @@ export const PARAGRAPH_STACK_PART = /** What each code a paragraph may hold but tsdraft does not lay out yet does. */ export const PARAGRAPH_NOT_LAID_OUT = { T: "sets the spacing of the characters after it", - c: "sets the true color of the characters after it", X: "starts the part of a dimension's text below its line", M: "holds a character of a code page", m: "holds a character of a code page", @@ -132,7 +131,10 @@ export interface RunFormat { readonly obliqueAngle: number | undefined; /** Where the characters and stacks sit up and down the line, `\A`: 0 on it, 1 centered, 2 at its top. */ readonly align: 0 | 1 | 2; - /** The color by its index, 0 to 257, that a `\C` code sets, or undefined for the entity's. */ + /** + * The color a `\C` code sets by its index, 0 to 257, or a `\c` code as a true color, `TRUE_COLOR` + * plus 0xRRGGBB; undefined for the entity's. + */ readonly color: number | undefined; } @@ -258,6 +260,7 @@ const ARGUMENTS: Readonly> = { Q: /^-?(?:(?:\d|[1-7]\d|8[0-4])(?:\.\d{1,64})?|85(?:\.0{1,64})?)$/, A: /^[012]$/, C: /^(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-7])$/, + c: /^\d{1,8}$/, }; /** @@ -281,8 +284,18 @@ const CODE_SETS: Readonly< Q: (argument, format) => ({ ...format, obliqueAngle: Number(argument) }), A: (argument, format) => ({ ...format, align: Number(argument) as 0 | 1 | 2 }), C: (argument, format) => ({ ...format, color: Number(argument) }), + // A true color, with its blue first: 255 is red. + c: (argument, format) => { + const bgr = Number(argument); + if (bgr > 0xffffff) return undefined; + const rgb = ((bgr & 0xff) << 16) | (bgr & 0xff00) | ((bgr >> 16) & 0xff); + return { ...format, color: TRUE_COLOR + rgb }; + }, }; +/** What a run's color holds for a true color: this, plus the color as 0xRRGGBB. */ +export const TRUE_COLOR = 0x1000000; + /** The codes before a `;` that take an argument, and what each takes. */ export const PARAGRAPH_CODE_ARGUMENTS = { H: "a height above 0, in drawing units, or with an x after it a factor of the height before it", @@ -290,6 +303,7 @@ export const PARAGRAPH_CODE_ARGUMENTS = { Q: "an oblique angle in degrees, from -85 to 85", A: "0, 1 or 2: on the baseline, centered or at the top", C: "a color number from 0 to 257", + c: "a true color, a whole number from 0 to 16777215 with its blue first", } as const; export type ArgumentCode = keyof typeof PARAGRAPH_CODE_ARGUMENTS; @@ -497,7 +511,7 @@ export function parseParagraph(value: string): ParsedParagraph { fail(paragraphNoSemicolon(letter)); return n; } - if (letter === "T" || letter === "c") { + if (letter === "T") { fail(paragraphNotLaidOut(letter)); return end + 1; } diff --git a/src/read/check.ts b/src/read/check.ts index ad4e294..e702d30 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -87,6 +87,7 @@ const BASE = { layer: "string", "color?": "number", "trueColor?": "number", + "colorBook?": { fields: { book: "string", name: "string" } }, "linetype?": "string", "lineweight?": "number", "linetypeScale?": "number", diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 33f68d9..2681769 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -1357,8 +1357,11 @@ class DxfReader { at: insert.at, scale: insert.scale, })); - if (this.#spaceName !== MODEL && space.inserts.length < this.#limits.census) - space.inserts.push(insert); + if (this.#spaceName !== MODEL && space.inserts.length < this.#limits.census) { + // Without geometry a read keeps no text, a color book's names among it. + const { colorBook: _book, ...kept } = insert; + space.inserts.push(this.#geometry ? insert : kept); + } } #closeOwner(): void { diff --git a/src/read/entities.ts b/src/read/entities.ts index 41f9b91..ac8677c 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -57,10 +57,25 @@ export function handleAt(r: Rec, code: number): string | undefined { /** The most tags of one insert, and labels of one multileader's block, that are kept. */ export const MAX_TAGS = 1000; +/** + * A color of a book as DXF group 430 holds it, the book's name and the color's with a `$` between + * them, or undefined for none. + */ +export function colorBookOf( + value: string | undefined, +): { readonly book: string; readonly name: string } | undefined { + if (value === undefined || value === "") return undefined; + const at = value.indexOf("$"); + return at < 0 + ? { book: "", name: value } + : { book: value.slice(0, at), name: value.slice(at + 1) }; +} + /** The pen an entity sets for itself, with each part left out at ByLayer. */ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadEntityBase { const color = num(r, 62); const trueColor = num(r, 420); + const book = colorBookOf(name(r, 430)); const linetype = name(r, 6); const lineweight = num(r, 370); const linetypeScale = num(r, 48); @@ -69,6 +84,7 @@ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadE layer, ...(color !== undefined && color !== 256 && { color }), ...(trueColor !== undefined && { trueColor }), + ...(book !== undefined && { colorBook: book }), ...(linetype !== undefined && !/^bylayer$/i.test(linetype.trim()) && { linetype }), ...(lineweight !== undefined && lineweight !== -1 && { lineweight }), ...(linetypeScale !== undefined && linetypeScale !== 1 && { linetypeScale }), @@ -1319,6 +1335,7 @@ export const attributeCost = (a: ReadAttribute): number => chars(a.value) + chars(a.layer) + chars(a.linetype) + + (a.colorBook ? chars(a.colorBook.book) + chars(a.colorBook.name) : 0) + (a.paragraph ? 2 + chars(a.paragraph.style) : 0); /** @@ -1327,7 +1344,11 @@ export const attributeCost = (a: ReadAttribute): number => * names and its text. */ export function costOf(e: ReadEntity): number { - const own = 1 + chars(e.layer) + chars(e.linetype); + const own = + 1 + + chars(e.layer) + + chars(e.linetype) + + (e.colorBook ? chars(e.colorBook.book) + chars(e.colorBook.name) : 0); switch (e.kind) { case "line": return own + 2; diff --git a/src/read/model.ts b/src/read/model.ts index b7b0681..78f4a9c 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -294,6 +294,12 @@ export interface ReadAttributeParagraph { readonly mirrored?: boolean; } +/** A color of a color book: the book's name and the color's, such as `RAL CLASSIC` and `RAL 5005`. */ +export interface ReadColorBook { + readonly book: string; + readonly name: string; +} + /** * What every entity keeps: its handle, its layer, and the pen it sets for itself. Each part of * the pen is left out when it is the default, ByLayer. @@ -305,6 +311,8 @@ export interface ReadEntityBase { readonly color?: number; /** Group 420: a true color as 0xRRGGBB. */ readonly trueColor?: number; + /** Group 430: a color of a color book, which `trueColor` holds as well. */ + readonly colorBook?: ReadColorBook; /** Group 6: a linetype's name, or `ByBlock`. */ readonly linetype?: string; /** Group 370: hundredths of a millimeter, or -2 for ByBlock and -3 for the default. */ diff --git a/src/rules.ts b/src/rules.ts index bef8d8e..6f6ae01 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -4,7 +4,7 @@ // // That app discards the whole drawing over most names that break the name rules. import type { XrefProblem } from "./blocks.ts"; -import type { DxfVersion, HatchGradient, Point, Rgb, Units } from "./drawing.ts"; +import type { DxfVersion, EntityColor, HatchGradient, Point, Rgb, Units } from "./drawing.ts"; import { clamped, fitSpline, type FittedSpline } from "./curves.ts"; import type { PaperUnit } from "./paper.ts"; import { paperInfo, PLOT_STYLE_TABLES, type Paper, type PlotStyleTable } from "./papers.ts"; @@ -160,6 +160,8 @@ const NAME_R12_CHARS = const NAME_R12_LENGTH = 'R12 layer names cannot be longer than 31 characters. Use DXF version "R2018" for longer names'; const COLOR = "A layer color must be a color index, an integer from 1 to 255"; +export const ENTITY_COLOR = + 'An entity\'s color is a color index, a whole number from 1 to 255, "ByLayer", "ByBlock", or a true color: its red, green and blue, each a whole number from 0 to 255'; const POSITIVE = "This value must be greater than 0"; const WRITTEN_AS_ZERO = "This value is written as 0, because tsdraft writes 6 decimals. Use 0.000001 or more"; @@ -177,6 +179,8 @@ const R12_LINETYPES = const R12_LINEWEIGHTS = 'R12 drawings have no lineweights. Use DXF version "R2018" for lineweights'; const R12_ENTITY_STYLE = 'R12 entities take no linetype or lineweight of their own. Use DXF version "R2018" for an entity linetype or lineweight'; +const R12_ENTITY_COLOR = + 'R12 entities take no color of their own. Use DXF version "R2018" for an entity color'; const R12_LAYER_STATES = 'tsdraft writes no layer states to R12 drawings. Use DXF version "R2018" for layers that are off, frozen, locked or not plotted'; const R12_BLOCKS = @@ -452,6 +456,33 @@ export type Aci = Exclude, 0>; /** Resolves to `C` when it is a valid layer color, and to the error message otherwise. */ export type LayerColor = number extends C ? C : C extends Aci ? C : typeof COLOR; +/** What an entity's color may be written as, which `EntityColorOf` then checks. */ +export type EntityColorGiven = EntityColor | readonly number[]; + +type ColorCheck = C extends "ByLayer" | "ByBlock" + ? C + : C extends number + ? number extends C + ? C + : C extends Aci + ? C + : typeof ENTITY_COLOR + : C extends readonly [infer R extends number, infer G extends number, infer B extends number] + ? [Channel, Channel, Channel] extends [true, true, true] + ? C + : typeof ENTITY_COLOR + : typeof ENTITY_COLOR; + +/** + * Resolves to `C` when it is a valid entity color, and to the error message otherwise: an index + * from 1 to 255, `"ByLayer"`, `"ByBlock"`, or three channels from 0 to 255. A `number` or an + * `Rgb` that is not a literal passes. The false branch is never taken: it keeps `const C` from + * widening a tuple, as in `LinetypeChoice`. + */ +export type EntityColorOf = [C] extends [EntityColorGiven] + ? ColorCheck + : C; + /** * True for a number the writers round to 0, given as the compiler prints it. * A number under 0.000001 prints in exponent form, such as `4e-7`, and those @@ -1107,6 +1138,7 @@ export type LineweightOf = number extends W export type R12Linetypes = typeof R12_LINETYPES; export type R12Lineweights = typeof R12_LINEWEIGHTS; export type R12EntityStyle = typeof R12_ENTITY_STYLE; +export type R12EntityColor = typeof R12_ENTITY_COLOR; export type R12LayerStates = typeof R12_LAYER_STATES; export type FrozenCurrent = typeof FROZEN_CURRENT; export type R12Text = typeof R12_TEXT; @@ -1174,7 +1206,7 @@ type ParagraphPercent = S extends `${string}%${infer R}` ? ["% type ParagraphPlainCode = "P" | "N" | "~" | "\\" | "{" | "}" | "o"; /** The codes that set what the characters after them are and end with a `;`. */ -type ParagraphEndedCode = "H" | "W" | "Q" | "A" | "C"; +type ParagraphEndedCode = "H" | "W" | "Q" | "A" | "C" | "c"; /** True for all zeros. */ type AllZeros = S extends `0${infer R}` @@ -1260,9 +1292,15 @@ type CodeArgument = C extends "H ? S extends "0" | "1" | "2" ? true : false - : S extends Below258 - ? true - : false; + : C extends "c" + ? S extends `${bigint}` + ? S extends `${"-" | "+"}${string}` + ? false + : true + : false + : S extends Below258 + ? true + : false; /** * Whether the characters are underlined, `L`, struck through, `K`, both or neither, as the codes @@ -1391,7 +1429,7 @@ type ParagraphCode< [...N, 0] > : ReturnType> - : C extends "T" | "c" + : C extends "T" ? After extends `${string};${string}` ? ReturnType> : ReturnType> @@ -1938,6 +1976,7 @@ export const R12_ONLY = { lineweights: R12_LINEWEIGHTS, layerStates: R12_LAYER_STATES, entityStyle: R12_ENTITY_STYLE, + entityColor: R12_ENTITY_COLOR, text: R12_TEXT, blocks: R12_BLOCKS, xrefs: R12_XREFS, @@ -5006,6 +5045,9 @@ const STANDARD_TABLE_STYLE_DEFINED = "The table style \"Standard\" is the leading CAD app's own, which tsdraft writes beside a drawing's table styles, and cannot be defined. That app keeps the first style of a name and skips a second"; const STANDARD_TABLE_STYLE_USED = 'tsdraft draws no table in the table style "Standard", which is the leading CAD app\'s own. Define a style with tableStyle() and name it'; +/** What is wrong with a table given a color of its own. */ +export const TABLE_COLOR = + 'A table has no color of its own: its style and its cells give its colors. Leave out "color", or give "ByLayer"'; /** What is wrong with a table inside a block. */ export const TABLE_IN_BLOCK = "A table cannot be drawn in a block. Draw it in model space or on a layout, where the leading CAD app edits it"; diff --git a/src/shape.ts b/src/shape.ts index 8f314c4..390ddce 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -488,9 +488,18 @@ function shapes(all: boolean, typed = all): Shapes { }; const kind: Check = LEFT; + // An index or a name, or a true color's three numbers, which the rule of an entity's color reads. + const entityColor: Check = (value, at, problems) => { + if (typeof value === "number" || typeof value === "string") return; + // Only a list of three is read, so a long list costs no more than three. + if (!Array.isArray(value) || value.length !== 3) { + problems.push(`${at} must be a number, a string or a list of three numbers`); + } else list(number)(value, at, problems); + }; const loop = fields({ points: list(point) }, { bulges: list(number) }); const shared = { id: ruled(string), + color: ruled(entityColor), linetype: ruled(string), lineweight: ruled(numberOrName), } as const; @@ -561,20 +570,38 @@ function shapes(all: boolean, typed = all): Shapes { ), insert: fields( { kind, layer: string, block: ruled(string), at: point }, - { id: ruled(string), scale: ruled(scale), rotation: number, attributes: ruled(map(string)) }, + { + id: ruled(string), + color: ruled(entityColor), + scale: ruled(scale), + rotation: number, + attributes: ruled(map(string)), + }, ), "linear-dimension": fields( { kind, layer: string, style: ruled(string), from: point, to: point, line: point }, - { id: ruled(string), angle: number, text: ruled(string), textBelow: ruled(string) }, + { + id: ruled(string), + color: ruled(entityColor), + angle: number, + text: ruled(string), + textBelow: ruled(string), + }, ), "aligned-dimension": fields( { kind, layer: string, style: ruled(string), from: point, to: point, offset: number }, - { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + { + id: ruled(string), + color: ruled(entityColor), + text: ruled(string), + textBelow: ruled(string), + }, ), "radius-dimension": fields( { kind, layer: string, style: ruled(string), center: point, point }, { id: ruled(string), + color: ruled(entityColor), text: ruled(string), textBelow: ruled(string), textFromCenter: number, @@ -584,6 +611,7 @@ function shapes(all: boolean, typed = all): Shapes { { kind, layer: string, style: ruled(string), center: point, point }, { id: ruled(string), + color: ruled(entityColor), text: ruled(string), textBelow: ruled(string), textFromCenter: number, @@ -591,7 +619,12 @@ function shapes(all: boolean, typed = all): Shapes { ), "jogged-radius-dimension": fields( { kind, layer: string, style: ruled(string), center: point, point, start: point, jog: point }, - { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + { + id: ruled(string), + color: ruled(entityColor), + text: ruled(string), + textBelow: ruled(string), + }, ), "arc-length-dimension": fields( { @@ -604,7 +637,12 @@ function shapes(all: boolean, typed = all): Shapes { endAngle: number, at: point, }, - { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + { + id: ruled(string), + color: ruled(entityColor), + text: ruled(string), + textBelow: ruled(string), + }, ), "ordinate-dimension": fields( { @@ -616,7 +654,12 @@ function shapes(all: boolean, typed = all): Shapes { feature: point, leaderEnd: point, }, - { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + { + id: ruled(string), + color: ruled(entityColor), + text: ruled(string), + textBelow: ruled(string), + }, ), "angular-dimension": fields( { @@ -628,7 +671,12 @@ function shapes(all: boolean, typed = all): Shapes { to: point, at: point, }, - { id: ruled(string), text: ruled(string), textBelow: ruled(string) }, + { + id: ruled(string), + color: ruled(entityColor), + text: ruled(string), + textBelow: ruled(string), + }, ), // A rule of `lint` reports the note, the shafts and the leader's own fields, whatever their type. leader: fields( @@ -641,6 +689,7 @@ function shapes(all: boolean, typed = all): Shapes { }, { id: ruled(string), + color: ruled(entityColor), text: ruled(list(string)), block: ruled(string), attributes: ruled(map(string)), @@ -690,6 +739,7 @@ function shapes(all: boolean, typed = all): Shapes { { kind, layer: string, style: ruled(string), at: point, columns: LEFT, rows: LEFT }, { id: ruled(string), + color: ruled(entityColor), rotation: number, title: LEFT, titleHeight: ruled(number), diff --git a/src/svg.ts b/src/svg.ts index 4e6e807..ca21e07 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -1,9 +1,12 @@ +import { TRUE_COLOR } from "./paragraph-codes.ts"; +import { isRgb } from "./colors.ts"; import { blocksByKey, compose, eachDrawn, mapPoint, referencedByKey, + type BlockColor, type LayerRef, type Matrix, type Referenced, @@ -29,6 +32,7 @@ import { type Linetype, type LinetypeMark, type LinetypeShape, + type Rgb, type Paragraph, type Point, type Polyline, @@ -239,22 +243,6 @@ const VIRTUAL_PENS: readonly string[] = [ .join(" ") .split(" "); -/** - * The index nearest a true color, which a file holds beside it: index 7 counted as white, which - * the leading CAD app holds it as. The first of two as near. - */ -export function nearestColorIndex([r, g, b]: readonly [number, number, number]): number { - let best = 1; - let nearest = Infinity; - for (let i = 0; i < ACI.length; i++) { - const hex = i === 6 ? "ffffff" : ACI[i]!; - const [pr, pg, pb] = [0, 2, 4].map((k) => Number.parseInt(hex.slice(k, k + 2), 16)); - const distance = (pr! - r) ** 2 + (pg! - g) ** 2 + (pb! - b) ** 2; - if (distance < nearest) [best, nearest] = [i + 1, distance]; - } - return best; -} - /** * The color a plot style table plots an ACI index in, on paper, where index 7 is black. Under a * table that gives each pen a color of its own, an index outside 1 to 255 plots as 7 does. @@ -365,6 +353,10 @@ export interface SvgOptions { /** How an entity is drawn. */ interface Pen { readonly color: string; + /** The color of the entity's layer, which a paragraph's `\C256;` gives the characters after it. */ + readonly byLayer: string; + /** The color ByBlock takes where the entity is, which `\C0;` gives the characters after it. */ + readonly byBlock: string; /** Undefined for a solid line. */ readonly dashes: Dashes | undefined; /** In hundredths of a millimetre. */ @@ -1206,14 +1198,25 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): */ const pen = ( look: Look, - e: Pick, + e: Pick, on: LayerRef, where: () => string, insertLayer?: LayerRef, from?: Referenced, placed = 1, + byBlock?: BlockColor, ): Pen => { const layer: Layer | undefined = layerOf(on); + const byLayer = layer?.color ?? 7; + const blockShade = + byBlock === undefined + ? 7 + : "color" in byBlock + ? byBlock.color + : (layerOf(byBlock.layer)?.color ?? 7); + const own: unknown = e.color; + const shade = + own === "ByBlock" ? blockShade : typeof own === "number" || isRgb(own) ? own : byLayer; /** * The layer a linetype or a lineweight comes from, with the drawing whose layer it is, or * `"own"` for the entity's own. @@ -1242,7 +1245,9 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): : (weightFrom.layer?.lineweight ?? "Default"); const code = lineweightCode(weight); return { - color: look.color(layer?.color ?? 7), + color: drawnColor(look, shade), + byLayer: drawnColor(look, byLayer), + byBlock: drawnColor(look, blockShade), // 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: @@ -1294,7 +1299,9 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): if (style === undefined || leaderBlock(e, style) === undefined) return undefined; const named = e.textStyle ?? style.textStyle; const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); - return pictureOf(e, style, textStyle).block; + const block = pictureOf(e, style, textStyle).block; + // The multileader holds its block ByBlock, so what the block sets ByBlock takes the leader's color. + return block === undefined || e.color === undefined ? block : { ...block, color: e.color }; }; /** @@ -1351,6 +1358,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): at.insertLayer, at.from, m ? Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) : 1, + at.byBlock, ); const part = drawn(held, mark, heldPen, look, at.from, at.matrix); if (!write(part.length + line + 2)) return; @@ -1684,6 +1692,29 @@ function precise(value: number): string { return String(Number(value.toPrecision(12))); } +/** + * 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. + */ +function drawnColor(look: Look, shade: number | Rgb): string { + if (typeof shade === "number") return look.color(shade); + return `#${[shade[0], shade[1], shade[2]].map((v) => v.toString(16).padStart(2, "0")).join("")}`; +} + +/** + * The color of a paragraph's run that a `\C` or `\c` code colors: 0 the color ByBlock takes where + * the paragraph is, 256 its layer's, 257 its own, an index as a layer's, and a true color as it is. + */ +function runColor(color: number, pen: Pen, look: Look): string { + if (color >= TRUE_COLOR) { + const rgb = color - TRUE_COLOR; + return drawnColor(look, [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255]); + } + if (color === 0) return pen.byBlock; + if (color === 256) return pen.byLayer; + return color >= 1 && color <= 255 ? look.color(color) : pen.color; +} + /** How a space is drawn: on a screen, or as it plots on paper. */ interface Look { /** The color of an ACI index. */ @@ -1796,8 +1827,9 @@ type Drawn = Exclude; type Shape = Exclude; /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ -function styled(e: Drawn): Pick { - return isDimension(e) || e.kind === "leader" || e.kind === "table" ? {} : e; +function styled(e: Drawn): Pick { + if (!isDimension(e) && e.kind !== "leader" && e.kind !== "table") return e; + return e.color === undefined ? {} : { color: e.color }; } /** @@ -1840,7 +1872,7 @@ function leaderToSvg( // A mask hides what is drawn before the leader, and none of the leader's own parts. if (picture.mask) { const color = picture.mask.color; - const fill = color === undefined ? "#ffffff" : color === 256 ? pen.color : look.color(color); + const fill = color === undefined ? "#ffffff" : color === 256 ? pen.byLayer : look.color(color); // One in the drawing's background is marked, for a viewer whose background is not white. const background = color === undefined ? ` data-mask="background"` : ""; add( @@ -2022,10 +2054,8 @@ function paragraphToSvg( advance: run.advance, bold: run.bold, }; - // A run a `\C` code colors is drawn in that color, as a layer's is: by block, by layer and - // by entity leave it the entity's. - const own = run.color !== undefined && run.color >= 1 && run.color <= 255; - const runPen = own ? { ...pen, color: look.color(run.color!) } : pen; + const runPen = + run.color === undefined ? pen : { ...pen, color: runColor(run.color, pen, look) }; add(textToSvg(text, style, runPen, `data-part="text"`, matrix, false, drawn)); } } @@ -2052,7 +2082,7 @@ function maskToSvg( pen: Pen, look: Look, ): string { - const fill = color === undefined ? "#ffffff" : color === 256 ? pen.color : look.color(color); + const fill = color === undefined ? "#ffffff" : color === 256 ? pen.byLayer : look.color(color); // One in the drawing's background is marked, for a viewer whose background is not white. const background = color === undefined ? ` data-mask="background"` : ""; const points = corners.map(([x, y]) => `${fmt(x)},${fmt(y)}`).join(" "); diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index b2369bd..c1ffb17 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -109,7 +109,7 @@ test("what tsdraft does not lay out is refused, and named", () => { ["\\T2;A", /code \\T, which sets the spacing/], ["\\A3;A", /code \\A takes 0, 1 or 2/], ["\\C258;A", /code \\C takes a color number from 0 to 257/], - ["\\c255;A", /code \\c, which sets the true color/], + ["\\c16777216;A", /code \\c takes a true color/], ["\\ptr3;A", /aligns text by its right/], ["\\psa1.2;A", /at least a size apart/], ["\\pi-;A", /option "i-"/], diff --git a/test/read-agreement.ts b/test/read-agreement.ts index 0808fea..23624a6 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -22,6 +22,7 @@ import type { TextStyle, } from "../src/drawing.ts"; import { isFitSpline } from "../src/drawing.ts"; +import { storedColor } from "../src/colors.ts"; import { written, writtenAngle } from "../src/format.ts"; import { clamped } from "../src/curves.ts"; import { idHandle } from "../src/handles.ts"; @@ -318,8 +319,12 @@ export function readProblems( if (want.id !== undefined && got.handle !== idHandle(want.id)) { say(`${label}: handle ${got.handle}, expected ${idHandle(want.id)}`); } - if (got.color !== undefined || got.trueColor !== undefined) - say(`${label}: has a color of its own`); + const stored = storedColor(want.color); + if (got.color !== stored?.index || got.trueColor !== stored?.rgb) { + say( + `${label}: color ${got.color} and ${got.trueColor}, expected ${stored?.index} and ${stored?.rgb}`, + ); + } if ( want.kind !== "insert" && want.kind !== "leader" && diff --git a/test/rules.test.ts b/test/rules.test.ts index 9a85af2..cd2749d 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -650,6 +650,77 @@ test("linetype, lineweight and layer state mistakes are compile errors and runti assert.deepEqual(lint(built), []); }); +test("entity color mistakes are compile errors and runtime errors", () => { + const r12 = createDrawing({ dxf: "R12" }); + const d = createDrawing(); + d.block("B", {}, () => d.circle([0, 0], 1)); + d.dimensionStyle({ + name: "DIMS", + textHeight: 1, + arrowSize: 1, + extensionOffset: 0.5, + extensionBeyond: 1, + textGap: 0.5, + precision: 2, + }); + d.leaderStyle({ name: "NOTES", textHeight: 0.1, arrowSize: 0.12, landing: 0.2, gap: 0.05 }); + + // @ts-expect-error: no color has index 0. + assert.throws(() => d.line([0, 0], [1, 1], { color: 0 }), /An entity's color is/); + // @ts-expect-error: nor 256. + assert.throws(() => d.circle([0, 0], 1, { color: 256 }), /An entity's color is/); + // @ts-expect-error: an index is a whole number. + assert.throws(() => d.insert("B", [0, 0], { color: 1.5 }), /An entity's color is/); + // @ts-expect-error: a channel is at most 255. + assert.throws(() => d.line([0, 0], [1, 1], { color: [256, 0, 0] }), /An entity's color is/); + // @ts-expect-error: a true color has three channels. + assert.throws(() => d.line([0, 0], [1, 1], { color: [1, 2] }), /An entity's color is/); + // @ts-expect-error: an R12 entity takes its layer's color. + assert.throws(() => r12.line([0, 0], [1, 1], { color: 1 }), /R12 entities take no color/); + r12.line([0, 0], [1, 1], { color: "ByLayer" }); + const fit: Point[] = [ + [0, 0], + [1, 1], + [2, 0], + ]; + const control: Point[] = [ + [0, 0], + [1, 1], + [2, 0], + [3, 1], + ]; + // @ts-expect-error: a curve's color is checked as any entity's. + assert.throws(() => d.ellipse([0, 0], [2, 0], 0.5, { color: 0 }), /An entity's color is/); + // @ts-expect-error: a spline's too. + assert.throws(() => d.spline(fit, { color: [1, 2, 300] }), /An entity's color is/); + // @ts-expect-error: and one by control points. + assert.throws(() => d.controlSpline(control, { color: 256 }), /An entity's color is/); + const colored = createDrawing(); + colored.ellipse([0, 0], [2, 0], 0.5, { color: 3 }); + colored.spline(fit, { color: [1, 2, 3] }); + colored.controlSpline(control, { color: "ByBlock" }); + const curveColors = colored.build().entities.map((e) => e.color); + assert.deepEqual(curveColors, [3, [1, 2, 3], "ByBlock"]); + + d.line([0, 0], [1, 1], { color: 1 }); + d.line([0, 0], [1, 1], { color: "ByBlock" }); + d.line([0, 0], [1, 1], { color: "ByLayer" }); + d.line([0, 0], [1, 1], { color: [10, 200, 30] }); + d.insert("B", [0, 0], { color: 255 }); + d.linearDimension([0, 0], [10, 0], [5, 2], { style: "DIMS", color: [0, 0, 255] }); + d.leader("NOTE", { style: "NOTES", at: [4, 4], to: [2, 2], color: "ByBlock" }); + const ordinate = { style: "DIMS", axis: "x" } as const; + // @ts-expect-error: an ordinate dimension's color is checked as any dimension's. + assert.throws(() => d.ordinateDimension([1, 1], [1, 4], { ...ordinate, color: 0 }), /color is/); + d.ordinateDimension([1, 1], [1, 4], { ...ordinate, color: 4 }); + const built = d.build(); + assert.deepEqual( + built.entities.map((e) => e.color), + [1, "ByBlock", undefined, [10, 200, 30], 255, [0, 0, 255], "ByBlock", 4], + ); + assert.deepEqual(lint(built), []); +}); + test("linetype mistakes the compiler cannot see are checked when the code runs", () => { const d = createDrawing(); const weight: number = 0.33; @@ -1280,9 +1351,9 @@ test("a paragraph's height, width, line spacing and codes are checked twice", () assert.throws(() => d.paragraph("{\\LNOTE", { at }), /never closed/); // @ts-expect-error: a brace closes nothing. assert.throws(() => d.paragraph("NOTE}", { at }), /closes no \{/); - d.paragraph("\\H2x;NOTE\\W0.8;\\Q15;\\A1;\\C1;", { at }); - // @ts-expect-error: a true color is not drawn yet. - assert.throws(() => d.paragraph("\\c255;NOTE", { at }), /code \\c, which sets the true color/); + d.paragraph("\\H2x;NOTE\\W0.8;\\Q15;\\A1;\\C1;\\c255;", { at }); + // @ts-expect-error: a true color is a whole number. + assert.throws(() => d.paragraph("\\c-1;NOTE", { at }), /code \\c takes a true color/); assert.throws( () => // @ts-expect-error: more than 64 digits after the point. diff --git a/test/shape.test.ts b/test/shape.test.ts index 056b855..793a5b5 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -37,7 +37,7 @@ import { } from "../src/index.ts"; import { timeLimit } from "./time-limit.ts"; -const styled = { linetype: "DD", lineweight: 0.25 } as const; +const styled = { linetype: "DD", lineweight: 0.25, color: [10, 200, 30] } as const; const justified = { style: "NOTES", align: "center", valign: "middle" } as const; /** @@ -117,6 +117,7 @@ const kinds: { }, insert: { kind: "insert", + color: "ByBlock", layer: "0", block: "TREE", at: [20, 0], @@ -127,6 +128,7 @@ const kinds: { }, "linear-dimension": { kind: "linear-dimension", + color: 1, layer: "0", style: "DIMS", from: [0, 0], @@ -139,6 +141,7 @@ const kinds: { }, "aligned-dimension": { kind: "aligned-dimension", + color: [200, 100, 50], layer: "0", style: "DIMS", from: [0, 0], @@ -150,6 +153,7 @@ const kinds: { }, leader: { kind: "leader", + color: 255, layer: "0", style: "NOTE", text: ["NOTE", "SECOND LINE"], @@ -251,6 +255,7 @@ const kinds: { }, "radius-dimension": { kind: "radius-dimension", + color: 7, layer: "0", style: "ARCH", center: [0, 0], @@ -262,6 +267,7 @@ const kinds: { }, "diameter-dimension": { kind: "diameter-dimension", + color: [0, 0, 0], layer: "0", style: "ARCH", center: [0, 0], @@ -273,6 +279,7 @@ const kinds: { }, "jogged-radius-dimension": { kind: "jogged-radius-dimension", + color: 8, layer: "0", style: "ARCH", center: [0, 0], @@ -285,6 +292,7 @@ const kinds: { }, "arc-length-dimension": { kind: "arc-length-dimension", + color: "ByLayer", layer: "0", style: "ARCH", center: [0, 0], @@ -298,6 +306,7 @@ const kinds: { }, "angular-dimension": { kind: "angular-dimension", + color: 250, layer: "0", style: "ARCH", vertex: [0, 0], @@ -310,6 +319,7 @@ const kinds: { }, table: { kind: "table", + color: "ByLayer", layer: "0", style: "SCHEDULE", at: [100, 20], @@ -331,6 +341,7 @@ const kinds: { }, "ordinate-dimension": { kind: "ordinate-dimension", + color: [40, 160, 220], layer: "0", style: "ARCH", axis: "x", @@ -419,6 +430,7 @@ const keyed: Required< > > = { kind: "leader", + color: "ByBlock", layer: "0", style: "NOTE", block: "TREE", diff --git a/test/tables.test.ts b/test/tables.test.ts index b890ba1..1d0d07a 100644 --- a/test/tables.test.ts +++ b/test/tables.test.ts @@ -14,6 +14,7 @@ import { } from "../src/index.ts"; import { referencedByKey } from "../src/blocks.ts"; import { extents } from "../src/extents.ts"; +import { TABLE_COLOR } from "../src/rules.ts"; import { tableCost, tableRepeats } from "../src/tables.ts"; import { timeLimit } from "./time-limit.ts"; @@ -231,3 +232,18 @@ test("a table whose style the drawing lacks draws nothing and throws nothing", ( assert.doesNotThrow(() => toSVG(drawing)); assert.doesNotThrow(() => inspectText(drawing)); }); + +test("a table takes no color of its own, from the builder or from lint", () => { + const d = createDrawing({ units: "in" }); + d.tableStyle({ name: "S", textHeight: 1 }); + const table = { style: "S", at: [0, 0], columns: [4], rows: [[{ text: "A" }]] } as const; + // @ts-expect-error: its style and its cells give its colors. + assert.throws(() => d.table({ ...table, color: 1 }), /A table has no color of its own/); + d.table({ ...table, color: "ByLayer" }); + const built = d.build(); + const colored = { ...built, entities: [{ ...built.entities[0]!, color: 3 }] } as Drawing; + assert.deepEqual( + lint(colored).map((p) => [p.rule, p.message]), + [["entity-color", `table #0: ${TABLE_COLOR}`]], + ); +}); From b1beba19ddc2f3655e1cbe63ba2454898001166b Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 17:54:02 -0500 Subject: [PATCH 25/35] The DWG reader reads the 2004, 2010 and 2013 formats - `readDWG` reads drawings saved in the 2004, 2010 and 2013 formats as well as 2018's, into the same read model, as CAD programs read each file when they open it: a 2004 file's text in its code page, each `\U+XXXX` in it as its character, and what a newer format holds that an older one cannot (attributes of paragraph text, paragraph text in columns, a strike-through, an image's inverted clip, a multileader's attachments) from the data the older save keeps for it. - A read names the file's `version`, and for a 2004 file its `codepage` and `encoding`. - Not yet: a drawing of the 2007 format is refused with a `ReadError` that names it, and a table in a 2004 file is counted under `unread.entities` as `ACAD_TABLE of the layout before R2010`; both come in the next pull request. - Known differences, follow-ups: an attribute of paragraph text in a mirrored insert of an older file reads its paragraph about half a unit from where CAD programs place it on opening; an invalid `\M+` code in 2004 text stays as written. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c738ea..43078e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- `readDWG` reads drawings saved in the 2004, 2010 and 2013 formats as well as 2018's, into the + same read model, as CAD programs read them when they open the file: a 2004 file's text in its + code page, each `\U+XXXX` in it as its character, and what a newer format holds that an older + one cannot, such as attributes of paragraph text, paragraph text in columns, a strike-through, + an image's inverted clip and a multileader's attachments, from the data an older save keeps for + it. A read names the file's `version`, and for 2004 its `codepage`. A table of the 2004 format + is counted under `unread.entities` and not read yet, and a drawing of the 2007 format is refused + with a `ReadError` that names it; both come next. + - Linetypes with shapes: a fence with its circles along it, and batt insulation. `parseShapes` reads a firm's compiled shape file (`.shx`) into each shape's outlines, and `toSVG`, `toPDF` and `lint` take the files' bytes as `shapes`, found by name as CAD programs find them, without From 0f7103c0952f000fe4bfd4a31ddfcc343aab8e33 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 18:23:17 -0500 Subject: [PATCH 26/35] Read a PDF page's size: pdfPageSize `pdfPageSize(bytes, page)` reads a PDF page's size in inches. It is the first part of PDF underlays, a PDF placed under a sheet; underlays themselves are coming. CAD programs place an underlay with the lower-left corner of the page's box at the insertion point, one drawing unit to an inch of the page at scale 1. So this is the size the drawing will hold of each underlay, as `rasterSize` reads an image's pixels. - `page` is the page's number from 1, as a number or a string such as `"2"`. Any other value, or a page past the file's last, gives undefined. - The size is the CropBox cut to the MediaBox, or the MediaBox when there is no CropBox. Each is inherited from the page tree when the page has none, and an entry that is null counts as none. Points are divided by 72 and multiplied by `/UserUnit`. Width and height swap where `/Rotate` is 90 or 270; `/Rotate` is also inherited, and negative values are allowed. - Pages are counted in the tree's order, whatever a stale `/Count` says. - It reads cross-reference tables and streams, hybrid files that have both, incremental updates (the newest wins) and objects in object streams. Boxes, their numbers, `/Kids` and `/Rotate` may be given by reference. Streams may use FlateDecode with or without a PNG predictor; any other filter on a stream it must read gives undefined. - A file whose cross-reference is broken is read by scanning for its objects' headers, as viewers do. An encrypted file reads when its pages are outside object streams. - It never throws, and its work stays in proportion to the file. Streams inflate to 64 MB in all, the scan finds 262,144 objects at most, and a page tree deeper than 256 or one that loops gives undefined. `docs/underlays.md` has the rules. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 7 + README.md | 2 + docs/underlays.md | 56 +++ src/index.ts | 1 + src/pdf-pages.ts | 995 +++++++++++++++++++++++++++++++++++++++++ src/raster.ts | 14 + test/pdf-pages.test.ts | 564 +++++++++++++++++++++++ 7 files changed, 1639 insertions(+) create mode 100644 docs/underlays.md create mode 100644 src/pdf-pages.ts create mode 100644 test/pdf-pages.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 43078e0..1acfff7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -212,6 +212,13 @@ coordinates, and lists the file's image definitions in `images`, with how many images name each, one that none names among them. The example sheet has a vicinity map above its key plan. [docs/images.md](docs/images.md) describes them. +- `pdfPageSize(bytes, page)` reads a PDF page's size in inches, the first part of PDF underlays, + which are coming: the page's CropBox cut to its MediaBox, from the page tree where the page has + none, times its `UserUnit`, and turned where its `Rotate` is 90 or 270. `page` is its number from + 1, as `"2"` or `2`. It reads cross-reference tables and streams, incremental updates, object + streams and FlateDecode with or without a predictor, scans a file whose cross-reference is broken, + and gives undefined for anything else, never a throw. [Underlays](docs/underlays.md) has the + rules. - Ordinate dimensions: `ordinateDimension(feature, leaderEnd, { axis, origin })` gives the X or the Y of a feature from an origin, `[0, 0]` unless given, without its sign, on a leader to `leaderEnd` with its text beyond, drawn as the leading CAD app draws it: the leader jogs where diff --git a/README.md b/README.md index a75581c..0dce381 100644 --- a/README.md +++ b/README.md @@ -427,6 +427,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, transparency, how the plot draws one, and what `lint` refuses. +- [Underlays](docs/underlays.md) covers `pdfPageSize`, which reads a PDF page's size for an + underlay. Underlays themselves are coming. - [Fills, wipeouts and masks](docs/fills.md) covers hatches with holes, solid, of a pattern file's patterns or of a gradient, wipeouts, the masks of paragraphs, leaders and dimensions, the draw order, and what `lint` refuses. diff --git a/docs/underlays.md b/docs/underlays.md new file mode 100644 index 0000000..8f262f2 --- /dev/null +++ b/docs/underlays.md @@ -0,0 +1,56 @@ +# Underlays + +An underlay is a PDF placed under a sheet: an architect's floor plan under an engineer's, or a +survey under a site plan. CAD programs draw the page from the file each time they open the +drawing, as they draw an image's file. Underlays themselves are coming. The first part is here: +`pdfPageSize`, which reads the size the drawing will hold of each, as `rasterSize` reads an image's +pixels. + +## A page's size + +`pdfPageSize(bytes, page)` gives a page's width and height in inches, across and down as a viewer +shows the page, or undefined: + +```ts +import { readFileSync } from "node:fs"; +import { pdfPageSize } from "tsdraft"; + +const size = pdfPageSize(readFileSync("A-101.pdf"), 2); // [36, 24] +``` + +CAD programs place an underlay with the lower-left corner of the page's box at the insertion +point, so at scale 1 a page is that many drawing units across and up, one to an inch of the page. + +`page` is the page's number from 1, as a number or as a string such as `"2"`, the way a drawing +file names the page. Any other value, and a page past the file's last, gives undefined. + +The size is the page's box as a viewer shows it: + +- The CropBox, cut to the MediaBox. With no CropBox, or one that misses the MediaBox, the + MediaBox. +- A page that has no box of its own takes it from the page tree above it, the nearest first, as + a PDF reader does. So does `/Rotate`. +- Points over 72, times the page's `/UserUnit` where it has one. A `/UserUnit` that is not a + positive number counts as 1. +- A `/Rotate` of 90 or 270, or -90, turns the page a quarter turn, so the width and the height + change places. One that is not a multiple of 90 counts as 0. + +## The files it reads + +It reads a PDF's cross-reference tables and its cross-reference streams, the updates a program +appends to a file it saves, the newest winning, and objects packed inside object streams. A box, +each number in it, a page tree's `/Kids` and `/Count`, and `/Rotate` may each be given by +reference. A stream it must read, such as a cross-reference stream, may be compressed with +FlateDecode, with or without a PNG predictor; one in any other filter gives undefined. + +Where the cross-reference is broken, as when a file was edited by hand or cut short, it finds the +objects by scanning the file for their headers, as viewers do. + +An encrypted file reads when its pages are outside object streams, since encryption covers strings +and streams and leaves the numbers of a box as they are. One whose pages are packed in object +streams gives undefined. + +A file's bytes are untrusted, and `pdfPageSize` never throws. It returns undefined for anything it +cannot read, and its work stays in proportion to the file: the streams of one file inflate to 64 MB +at most, a broken file's scan finds 262,144 objects at most, and a page tree deeper than 256 or one +that loops back on itself gives undefined. diff --git a/src/index.ts b/src/index.ts index 33cc7e3..55eb612 100644 --- a/src/index.ts +++ b/src/index.ts @@ -180,6 +180,7 @@ export { heldColor, storedColor } from "./colors.ts"; export { toDXF, type DxfOptions } from "./dxf.ts"; export { parsePatterns, PATTERN_FILE_LENGTH } from "./patterns.ts"; export { fifteenDigits } from "./format.ts"; +export { pdfPageSize } from "./pdf-pages.ts"; export { rasterSize } from "./raster.ts"; export { drawingImages, diff --git a/src/pdf-pages.ts b/src/pdf-pages.ts new file mode 100644 index 0000000..cb91d30 --- /dev/null +++ b/src/pdf-pages.ts @@ -0,0 +1,995 @@ +// Reads a page's size from a PDF's bytes, for an underlay. A PDF is untrusted input: every offset +// and count is held to the bytes before it is read, the work is held to a budget in proportion to +// them, and nothing here recurses. +import { inflateCounted } from "./raster.ts"; + +/** The most bytes the streams of one file inflate to, all together. */ +const INFLATE_LIMIT = 64 * 2 ** 20; +/** The most objects one call reads. */ +const OBJECTS = 1_000_000; +/** The deepest page tree, and the deepest nesting of arrays and dictionaries, read. */ +const DEPTH = 256; +/** The most objects the scan for `N G obj` finds when the cross-reference is broken. */ +const SCANNED = 2 ** 18; +/** How far a chain of references to references, or of streams' lengths, is followed. */ +const HOPS = 8; + +/** + * A PDF page's size in inches, across and down as a viewer shows it: what the drawing holds of an + * underlay of the page, as `rasterSize` reads an image's pixels. `page` is the page's number from + * 1, as a string such as `"2"` or a number. Undefined for any other `page`, a page past the + * file's last, and a file it cannot read. + * + * The size is the page's CropBox cut to its MediaBox, or the MediaBox where the page has no + * CropBox or one that misses it, each inherited from the page tree when the page has none. It is + * in points over 72, times the page's `/UserUnit`, turned a quarter turn where the page's + * `/Rotate`, also inherited, is 90 or 270. A `/Rotate` that is not a multiple of 90 counts as 0, + * and a `/UserUnit` that is not a positive number as 1, as viewers read them. + * + * It reads cross-reference tables and streams, incremental updates, objects in object streams, + * and streams compressed with FlateDecode, with or without a PNG predictor; a stream it must read + * in any other filter gives undefined. Where the cross-reference is broken it scans the file for + * its objects, as viewers do. An encrypted file reads where its pages and boxes are outside + * object streams. The work is in proportion to the bytes: the streams inflate to 64 MB at most, + * the scan finds 262,144 objects at most, and a page tree deeper than 256 or one that loops + * gives undefined. It never throws. + */ +export function pdfPageSize( + bytes: Uint8Array, + page: string | number, +): readonly [width: number, height: number] | undefined { + const wanted = + typeof page === "number" + ? page + : typeof page === "string" && /^[1-9][0-9]{0,14}$/.test(page) + ? Number(page) + : NaN; + if (!Number.isSafeInteger(wanted) || wanted < 1 || !(bytes instanceof Uint8Array)) { + return undefined; + } + if (indexOf(bytes, PDF_HEADER, 0, Math.min(bytes.length, 1024)) < 0) return undefined; + const fromTable = attempt(bytes, wanted, false); + if (fromTable.size !== undefined || !fromTable.broken) return fromTable.size; + return attempt(bytes, wanted, true).size; +} + +function attempt( + bytes: Uint8Array, + wanted: number, + scan: boolean, +): { size: readonly [number, number] | undefined; broken: boolean } { + const file = new PdfFile(bytes); + try { + if (scan ? file.scan() : file.readTable()) { + return { size: pageSize(file, wanted), broken: file.broken }; + } + } catch (stop) { + if (stop !== STOP) throw stop; + } + return { size: undefined, broken: file.broken }; +} + +/** Thrown inside to end a read that ran out of its budget; caught by `attempt`. */ +const STOP: unique symbol = Symbol("stop"); + +// The values of a file. A string's content is never needed, so a string is `TEXT`. +interface Name { + readonly name: string; +} +interface Ref { + readonly ref: number; + readonly gen: number; +} +interface Dict { + readonly dict: Partial>; +} +const TEXT = { text: true } as const; +type Value = number | boolean | null | Name | Ref | Dict | typeof TEXT | Value[]; + +/** The keys this reader reads. A dictionary keeps no other, so no key of the file is hashed. */ +const KEYS = [ + "BitsPerComponent", + "Colors", + "Columns", + "Count", + "CropBox", + "DecodeParms", + "Encrypt", + "Filter", + "First", + "Index", + "Kids", + "Length", + "MediaBox", + "N", + "Pages", + "Predictor", + "Prev", + "Root", + "Rotate", + "Size", + "Type", + "UserUnit", + "W", + "XRefStm", +] as const; +type Key = (typeof KEYS)[number]; + +const isName = (v: Value | undefined): v is Name => + typeof v === "object" && v !== null && "name" in v; +const isRef = (v: Value | undefined): v is Ref => typeof v === "object" && v !== null && "ref" in v; +const isDict = (v: Value | undefined): v is Dict => + typeof v === "object" && v !== null && "dict" in v; +const isInt = (v: Value | undefined): v is number => + typeof v === "number" && Number.isSafeInteger(v) && v >= 0; + +/** An object as the file holds it: its value, and where its stream's bytes start if it has one. */ +interface Obj { + readonly value: Value; + readonly stream?: { readonly data: Uint8Array; readonly at: number }; + /** Its generation, from the cross-reference; unknown for one the scan found. */ + readonly gen?: number; +} + +/** Where an object is, and its generation; `free` where the newest section marks it free. */ +type Entry = + | { readonly at: number; readonly gen: number } + | { readonly within: number; readonly index: number; readonly gen: 0 } + | { readonly free: true }; + +interface ObjectStream { + readonly data: Uint8Array; + readonly first: number; + readonly numbers: number[]; + readonly offsets: number[]; +} + +const PDF_HEADER = bytesOf("%PDF-"); +const STARTXREF = bytesOf("startxref"); +const ENDSTREAM = bytesOf("endstream"); + +function bytesOf(text: string): Uint8Array { + return Uint8Array.from(text, (c) => c.charCodeAt(0)); +} + +function indexOf(bytes: Uint8Array, word: Uint8Array, from: number, to: number): number { + outer: for (let i = from; i + word.length <= to; i++) { + for (let k = 0; k < word.length; k++) if (bytes[i + k] !== word[k]) continue outer; + return i; + } + return -1; +} + +const WHITE = (c: number): boolean => + c === 32 || c === 10 || c === 13 || c === 9 || c === 12 || c === 0; +const DELIMITER = (c: number): boolean => + c === 0x28 || + c === 0x29 || + c === 0x3c || + c === 0x3e || + c === 0x5b || + c === 0x5d || + c === 0x7b || + c === 0x7d || + c === 0x2f || + c === 0x25; +const REGULAR = (c: number): boolean => !WHITE(c) && !DELIMITER(c); +const DIGIT = (c: number): boolean => c >= 0x30 && c <= 0x39; + +/** What a token is. */ +const TOKEN = { + end: 0, + number: 1, + name: 2, + word: 3, + open: 4, + close: 5, + dict: 6, + undict: 7, + text: 8, +} as const; + +/** Spends the work of a read. Every byte a token or a scan passes costs one. */ +class Budget { + spent = 0; + inflated = 0; + readonly #base: number; + constructor(length: number) { + this.#base = length; + } + spend(n: number): void { + this.spent += n; + if (this.spent > 4 * (this.#base + this.inflated) + 2 ** 20) throw STOP; + } +} + +/** Reads the tokens of `data` from `at`, charging `budget`. */ +class Lexer { + readonly data: Uint8Array; + readonly budget: Budget; + at: number; + kind: number = TOKEN.end; + start = 0; + number = 0; + constructor(data: Uint8Array, at: number, budget: Budget) { + this.data = data; + this.at = at; + this.budget = budget; + } + + next(): number { + const { data } = this; + const from = Math.min(this.at, data.length); + let at = from; + for (;;) { + while (at < data.length && WHITE(data[at]!)) at++; + if (data[at] !== 0x25) break; + while (at < data.length && data[at] !== 10 && data[at] !== 13) at++; + } + this.start = at; + const c = data[at]; + let kind: number; + if (c === undefined) kind = TOKEN.end; + else if (c === 0x2f) { + at++; + while (at < data.length && REGULAR(data[at]!)) at++; + kind = TOKEN.name; + } else if (c === 0x5b || c === 0x5d) { + at++; + kind = c === 0x5b ? TOKEN.open : TOKEN.close; + } else if ((c === 0x3c || c === 0x3e) && data[at + 1] === c) { + at += 2; + kind = c === 0x3c ? TOKEN.dict : TOKEN.undict; + } else if (c === 0x3c) { + while (at < data.length && data[at] !== 0x3e) at++; + kind = at < data.length ? TOKEN.text : TOKEN.end; + at++; + } else if (c === 0x28) { + let depth = 0; + for (; at < data.length; at++) { + const b = data[at]; + if (b === 0x5c) at++; + else if (b === 0x28) depth++; + else if (b === 0x29 && --depth === 0) break; + } + kind = at < data.length ? TOKEN.text : TOKEN.end; + at++; + } else if (DIGIT(c) || c === 0x2b || c === 0x2d || c === 0x2e) { + while (at < data.length && REGULAR(data[at]!)) at++; + this.number = at - this.start <= 64 ? Number(latin1(data, this.start, at)) : NaN; + kind = Number.isFinite(this.number) ? TOKEN.number : TOKEN.word; + } else { + at++; + while (at < data.length && REGULAR(data[at]!)) at++; + kind = TOKEN.word; + } + this.at = Math.min(at, data.length); + this.budget.spend(this.at - from + 1); + this.kind = kind; + return kind; + } + + /** Whether the token just read is the keyword `word`. */ + is(word: string): boolean { + if (this.kind !== TOKEN.word || this.at - this.start !== word.length) return false; + for (let i = 0; i < word.length; i++) { + if (this.data[this.start + i] !== word.charCodeAt(i)) return false; + } + return true; + } + + /** The name just read, with its `#xx` codes, or "" for one longer than a PDF name may be. */ + name(): string { + const { data } = this; + if (this.at - this.start > 128) return ""; + let name = ""; + for (let i = this.start + 1; i < this.at; i++) { + const hex = data[i] === 0x23 ? Number.parseInt(latin1(data, i + 1, i + 3), 16) : NaN; + if (Number.isInteger(hex) && i + 2 < this.at) { + name += String.fromCharCode(hex); + i += 2; + } else name += String.fromCharCode(data[i]!); + } + return name; + } + + /** + * The value that starts at the next token, read without recursion, or undefined where the + * bytes hold none. A number followed by another and `R` is a reference. + */ + value(): Value | undefined { + const stack: { items: Value[]; dict: boolean }[] = []; + for (;;) { + let value: Value; + const kind = this.next(); + if (kind === TOKEN.number) { + value = this.number; + if (stack.length === 0 && isInt(value)) { + const back = this.at; + const gen = this.next() === TOKEN.number ? this.number : -1; + if (isInt(gen) && this.next() === TOKEN.word && this.is("R")) { + value = { ref: value, gen }; + } else this.at = back; + } + } else if (kind === TOKEN.name) value = { name: this.name() }; + else if (kind === TOKEN.text) value = TEXT; + else if (kind === TOKEN.open || kind === TOKEN.dict) { + if (stack.length >= DEPTH) return undefined; + stack.push({ items: [], dict: kind === TOKEN.dict }); + continue; + } else if (kind === TOKEN.close || kind === TOKEN.undict) { + const top = stack.pop(); + if (top === undefined || top.dict !== (kind === TOKEN.undict)) return undefined; + if (top.dict) { + if (top.items.length % 2 !== 0) return undefined; + const dict: Partial> = {}; + for (let i = 0; i < top.items.length; i += 2) { + const key = top.items[i]; + if (!isName(key)) return undefined; + if ((KEYS as readonly string[]).includes(key.name)) + dict[key.name as Key] = top.items[i + 1]!; + } + value = { dict }; + } else value = top.items; + } else if (kind === TOKEN.word && this.is("R") && stack.length > 0) { + const items = stack[stack.length - 1]!.items; + const [n, g] = items.slice(-2); + if (items.length < 2 || !isInt(n) || !isInt(g)) return undefined; + items.length -= 2; + value = { ref: n, gen: g }; + } else if (kind === TOKEN.word && this.is("true")) value = true; + else if (kind === TOKEN.word && this.is("false")) value = false; + else if (kind === TOKEN.word && this.is("null")) value = null; + else return undefined; + if (stack.length === 0) return value; + stack[stack.length - 1]!.items.push(value); + } + } +} + +function latin1(data: Uint8Array, from: number, to: number): string { + let text = ""; + for (let i = from; i < to && i < data.length; i++) text += String.fromCharCode(data[i]!); + return text; +} + +/** A section of the cross-reference: a table's rows in the file, or a stream's rows. */ +interface Section { + /** + * Each run of rows, by its first object's number: that number, its count and its first row. + * Where runs overlap, an object is looked for in the last that starts at or before it. + */ + readonly runs: number[]; + /** A table's rows lie in the file; a stream's in its bytes, `widths` wide. */ + readonly rows: Uint8Array | undefined; + readonly widths: readonly [number, number, number]; + /** Whether only its entries of objects in object streams count, as in a scan. */ + readonly streamsOnly: boolean; + /** A hybrid file's `/XRefStm`, read before its table, whose free rows leave the table's. */ + readonly hybrid?: boolean; +} + +/** A PDF's objects, found through its cross-reference or by a scan of its bytes. */ +class PdfFile { + readonly bytes: Uint8Array; + readonly budget: Budget; + /** Set when an object the file points to is not where it says, or the table cannot be read. */ + broken = false; + encrypted = false; + root: Value | undefined; + readonly #sections: Section[] = []; + readonly #scanned = new Map(); + readonly #objects = new Map(); + readonly #streams = new Map(); + #ends: number[] | undefined; + #read = 0; + #depth = 0; + + constructor(bytes: Uint8Array) { + this.bytes = bytes; + this.budget = new Budget(bytes.length); + } + + lexer(at: number, data: Uint8Array = this.bytes): Lexer { + return new Lexer(data, at, this.budget); + } + + /** Reads the cross-reference from `startxref` back through each `/Prev`. */ + readTable(): boolean { + const { bytes } = this; + const from = Math.max(0, bytes.length - 4096); + this.budget.spend(bytes.length - from); + let found = -1; + for (let i = bytes.length - STARTXREF.length; i >= from && found < 0; i--) { + if (indexOf(bytes, STARTXREF, i, i + STARTXREF.length) === i) found = i; + } + const lexer = this.lexer(found + STARTXREF.length); + if (found < 0 || lexer.next() !== TOKEN.number || !isInt(lexer.number)) { + this.broken = true; + return false; + } + const seen: number[] = []; + let at: number | undefined = lexer.number; + while (at !== undefined) { + if (seen.includes(at) || seen.length >= 1024) break; + seen.push(at); + const trailer = this.#section(at); + if (trailer === undefined) { + this.broken = true; + return false; + } + this.root ??= trailer.Root; + if (trailer.Encrypt !== undefined) this.encrypted = true; + const hybrid = trailer.XRefStm; + if (isInt(hybrid) && !seen.includes(hybrid)) { + seen.push(hybrid); + if (this.#section(hybrid) === undefined) this.broken = true; + else { + // A hybrid table marks free what its stream puts in object streams, so the stream + // comes first. + const stream = this.#sections.pop()!; + this.#sections.splice(this.#sections.length - 1, 0, { ...stream, hybrid: true }); + } + } + at = isInt(trailer.Prev) ? trailer.Prev : undefined; + } + if (this.root === undefined) this.broken = true; + return this.root !== undefined; + } + + /** Reads the section at `at`, a table or a stream, and gives its trailer. */ + #section(at: number): Partial> | undefined { + if (at >= this.bytes.length) return undefined; + const lexer = this.lexer(at); + lexer.next(); + if (lexer.is("xref")) { + const runs: number[] = []; + for (;;) { + const kind = lexer.next(); + if (kind === TOKEN.word && lexer.is("trailer")) break; + const start = lexer.number; + if (kind !== TOKEN.number || !isInt(start) || lexer.next() !== TOKEN.number) + return undefined; + const count = lexer.number; + if (!isInt(count)) return undefined; + let row = lexer.at; + while (row < this.bytes.length && WHITE(this.bytes[row]!)) row++; + runs.push(start, count, row); + this.budget.spend(3); + lexer.at = row + 20 * count; + } + const trailer = lexer.value(); + if (!isDict(trailer)) return undefined; + this.#sections.push({ + runs: this.#sorted(runs), + rows: undefined, + widths: [0, 0, 0], + streamsOnly: false, + }); + return trailer.dict; + } + const obj = this.#parse(at, undefined); + const section = obj === undefined ? undefined : this.#streamSection(obj, false); + if (section === undefined || !isDict(obj?.value)) return undefined; + this.#sections.push(section); + return obj.value.dict; + } + + /** A cross-reference stream's rows, read from its dictionary's direct values. */ + #streamSection(obj: Obj, streamsOnly: boolean): Section | undefined { + if (!isDict(obj.value) || obj.stream === undefined) return undefined; + const d = obj.value.dict; + if (!isName(d.Type) || d.Type.name !== "XRef" || !Array.isArray(d.W) || d.W.length !== 3) { + return undefined; + } + const widths = d.W.map((w) => (isInt(w) && w <= 8 ? w : -1)); + if (widths.includes(-1) || widths[0]! + widths[1]! + widths[2]! === 0) return undefined; + const index = d.Index ?? (isInt(d.Size) ? [0, d.Size] : undefined); + if (!Array.isArray(index) || index.length % 2 !== 0) return undefined; + const rows = this.streamBytes(obj, true); + if (rows === undefined) return undefined; + const runs: number[] = []; + let row = 0; + for (let i = 0; i < index.length; i += 2) { + const [start, count] = [index[i], index[i + 1]]; + if (!isInt(start) || !isInt(count)) return undefined; + runs.push(start, count, row); + row += count; + } + this.budget.spend(index.length); + return { + runs: this.#sorted(runs), + rows, + widths: widths as [number, number, number], + streamsOnly, + }; + } + + /** Runs of three numbers, sorted by the first. */ + #sorted(runs: number[]): number[] { + const order = Array.from({ length: runs.length / 3 }, (_, i) => i); + this.budget.spend(order.length * (1 + Math.log2(1 + order.length))); + order.sort((a, b) => runs[3 * a]! - runs[3 * b]!); + return order.flatMap((i) => [runs[3 * i]!, runs[3 * i + 1]!, runs[3 * i + 2]!]); + } + + /** + * Finds the objects by their `N G obj` headers, the last of each number winning, when the + * cross-reference cannot be read. Objects in object streams are found through the + * cross-reference streams the scan finds, and the catalog through the last trailer, the last + * cross-reference stream or the last catalog that names one. + */ + scan(): boolean { + const { bytes } = this; + this.budget.spend(bytes.length); + const trailers: number[] = []; + const xrefs: number[] = []; + const catalogs: number[] = []; + let header = -1; + for (let i = 0; i < bytes.length; i++) { + const c = bytes[i]!; + if (c === 0x6f && this.#word(i, "obj") && i > 0 && WHITE(bytes[i - 1]!)) { + const at = headerAt(bytes, i); + if (at === undefined) continue; + header = at.start; + if (this.#scanned.has(at.number) || this.#scanned.size < SCANNED) { + this.#scanned.set(at.number, at.start); + } + } else if (c === 0x74 && this.#word(i, "trailer")) trailers.push(i + 7); + else if (c === 0x2f && this.#word(i + 1, "XRef")) once(xrefs, header); + else if (c === 0x2f && this.#word(i + 1, "Catalog")) once(catalogs, header); + else if (c === 0x2f && this.#word(i + 1, "Encrypt")) this.encrypted = true; + } + for (const at of xrefs.reverse()) { + const obj = this.#parse(at, undefined); + const section = obj === undefined ? undefined : this.#streamSection(obj, true); + if (section === undefined || !isDict(obj?.value)) continue; + this.#sections.push(section); + this.root ??= obj.value.dict.Root; + } + for (const at of trailers.reverse()) { + if (this.root !== undefined) break; + const trailer = this.lexer(at).value(); + if (isDict(trailer) && trailer.dict.Root !== undefined) this.root = trailer.dict.Root; + } + for (const at of catalogs.reverse()) { + if (this.root !== undefined) break; + const obj = this.#parse(at, undefined); + if (isDict(obj?.value) && obj.value.dict.Pages !== undefined) this.root = obj.value; + } + return this.root !== undefined; + } + + /** Whether the bytes at `i` are `word`, with no regular character after it. */ + #word(i: number, word: string): boolean { + const { bytes } = this; + for (let k = 0; k < word.length; k++) if (bytes[i + k] !== word.charCodeAt(k)) return false; + const after = bytes[i + word.length]; + return after === undefined || !REGULAR(after); + } + + /** Where object `n` is, from the newest section that has it. */ + #entry(n: number): Entry | undefined { + const scanned = this.#scanned.get(n); + if (scanned !== undefined) return { at: scanned, gen: -1 }; + for (const section of this.#sections) { + const { runs, rows, widths } = section; + let [lo, hi] = [0, runs.length / 3]; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (runs[3 * mid]! <= n) lo = mid + 1; + else hi = mid; + } + this.budget.spend(1 + Math.log2(1 + lo)); + for (let i = 3 * (lo - 1); i >= 0; i = -1) { + const [start, count, first] = [runs[i]!, runs[i + 1]!, runs[i + 2]!]; + if (n >= start + count) break; + if (rows === undefined) { + const lexer = this.lexer(first + 20 * (n - start)); + const at = lexer.next() === TOKEN.number ? lexer.number : -1; + const gen = lexer.next() === TOKEN.number ? lexer.number : -1; + const ok = isInt(gen) && lexer.next() === TOKEN.word; + if (!ok || !isInt(at) || !(lexer.is("n") || lexer.is("f"))) { + this.broken = true; + return undefined; + } + // A free entry hides what older sections held of the number. + return lexer.is("n") ? { at, gen } : { free: true }; + } + const width = widths[0] + widths[1] + widths[2]; + const row = (first + n - start) * width; + if (row + width > rows.length) break; + const field = (from: number, w: number): number => { + let v = 0; + for (let k = 0; k < w; k++) v = v * 256 + rows[row + from + k]!; + return v; + }; + const type = widths[0] === 0 ? 1 : field(0, widths[0]); + const [a, b] = [field(widths[0], widths[1]), field(widths[0] + widths[1], widths[2])]; + if (type === 0 && !section.streamsOnly && !section.hybrid) return { free: true }; + if (type === 1 && !section.streamsOnly) return { at: a, gen: b }; + if (type === 2) return { within: a, index: b, gen: 0 }; + break; + } + } + return undefined; + } + + /** + * Object `n` of generation `gen`, or undefined where the file has none it can read, where the + * newest section marks it free, or where it is of another generation: a reference to any of + * those is null. + */ + object(n: number, gen = 0): Obj | undefined { + let cached = this.#objects.get(n); + if (cached === undefined) { + if (++this.#read > OBJECTS) throw STOP; + this.#objects.set(n, null); + const entry = this.#entry(n); + let obj: Obj | undefined; + if (entry === undefined) this.broken = true; + // A free entry or one of another generation is null, and a sign of a table off by a row, + // which the scan reads past if the page is not found. + else if ("free" in entry) this.broken = true; + else if ("at" in entry) { + obj = this.#parse(entry.at, n); + if (obj !== undefined && entry.gen >= 0) obj = { ...obj, gen: entry.gen }; + } else if (!this.encrypted) obj = this.#fromStream(n, entry.within, entry.index); + cached = obj ?? null; + this.#objects.set(n, cached); + } + if (cached === null) return undefined; + if (cached.gen === undefined || cached.gen === gen) return cached; + this.broken = true; + return undefined; + } + + /** The object whose `N G obj` header is at `at`, which must be object `n` when it is given. */ + #parse(at: number, n: number | undefined): Obj | undefined { + const lexer = this.lexer(at); + const number = lexer.next() === TOKEN.number ? lexer.number : -1; + if ( + at >= this.bytes.length || + !isInt(number) || + (n !== undefined && number !== n) || + lexer.next() !== TOKEN.number || + lexer.next() !== TOKEN.word || + !lexer.is("obj") + ) { + this.broken = true; + return undefined; + } + const value = lexer.value(); + if (value === undefined) { + this.broken = true; + return undefined; + } + const after = lexer.at; + if (!isDict(value) || lexer.next() !== TOKEN.word || !lexer.is("stream")) { + lexer.at = after; + return { value }; + } + let start = lexer.at; + if (this.bytes[start] === 13) start++; + if (this.bytes[start] === 10) start++; + return { value, stream: { data: this.bytes, at: start } }; + } + + /** Object `n` at `index` of the object stream `within`. */ + #fromStream(n: number, within: number, index: number): Obj | undefined { + let stream = this.#streams.get(within); + if (stream === undefined) { + this.#streams.set(within, null); + const entry = this.#entry(within); + const obj = entry !== undefined && "at" in entry ? this.#parse(entry.at, within) : undefined; + const d: Partial> = + obj !== undefined && isDict(obj.value) ? obj.value.dict : {}; + // Each stream's numbers may be references into other streams: a chain is followed as far + // as a chain of references is. + if (this.#depth >= HOPS) return undefined; + this.#depth++; + let count: Value | undefined; + let first: Value | undefined; + try { + [count, first] = [this.resolve(d.N), this.resolve(d.First)]; + } finally { + this.#depth--; + } + const type = d.Type; + const isStream = isName(type) && type.name === "ObjStm"; + const data = obj !== undefined && isStream ? this.streamBytes(obj) : undefined; + if (data === undefined || !isInt(count) || !isInt(first) || first > data.length) { + return undefined; + } + const lexer = this.lexer(0, data.subarray(0, first)); + const numbers: number[] = []; + const offsets: number[] = []; + while (numbers.length < count) { + if (lexer.next() !== TOKEN.number || !isInt(lexer.number)) break; + const number = lexer.number; + if (lexer.next() !== TOKEN.number || !isInt(lexer.number)) break; + numbers.push(number); + offsets.push(lexer.number); + } + stream = { data, first, numbers, offsets }; + this.#streams.set(within, stream); + } + if (stream === null || stream === undefined) return undefined; + let i = stream.numbers[index] === n ? index : -1; + if (i < 0) { + this.budget.spend(stream.numbers.length); + i = stream.numbers.indexOf(n); + } + if (i < 0) return undefined; + const value = this.lexer(stream.first + stream.offsets[i]!, stream.data).value(); + return value === undefined ? undefined : { value }; + } + + /** + * A stream's bytes, decoded, or undefined for a filter other than FlateDecode. A + * cross-reference stream's dictionary is read `direct`, by its own values only, since the + * objects its references name are found through it. + */ + streamBytes(obj: Obj, direct = false): Uint8Array | undefined { + if (obj.stream === undefined || !isDict(obj.value) || this.#depth >= HOPS) return undefined; + const d = obj.value.dict; + const { data, at } = obj.stream; + this.#depth++; + try { + return this.#decode(d, data, at, direct); + } finally { + this.#depth--; + } + } + + #decode( + d: Partial>, + data: Uint8Array, + at: number, + direct: boolean, + ): Uint8Array | undefined { + const get = (v: Value | undefined): Value | undefined => + direct ? (isRef(v) ? undefined : v) : this.resolve(v); + const length = get(d.Length); + let end = isInt(length) ? at + length : -1; + if (end < 0 || end > data.length || !this.#endsStream(end)) { + end = this.#endstream(at); + if (end < 0) return undefined; + if (data[end - 1] === 10) end--; + if (data[end - 1] === 13) end--; + } + const raw = data.subarray(at, Math.max(at, end)); + const filters = single(get(d.Filter)); + if (filters === null) return raw; + const filter = get(filters); + if (!isName(filter) || filter.name !== "FlateDecode") return undefined; + const limit = INFLATE_LIMIT - this.budget.inflated; + if (limit <= 0) return undefined; + // Inflating reads its input, which streams that overlap would read again for nothing. + this.budget.spend(raw.length); + const { bytes: out, written } = inflateCounted(raw, limit); + this.budget.inflated += written; + if (out === undefined) return undefined; + const parms = get(single(get(d.DecodeParms)) ?? undefined); + const p = isDict(parms) ? parms.dict : {}; + const predictor = get(p.Predictor) ?? 1; + if (predictor === 1) return out; + if (typeof predictor !== "number" || predictor < 10 || predictor > 15) return undefined; + const [colors, bits, columns] = [ + get(p.Colors) ?? 1, + get(p.BitsPerComponent) ?? 8, + get(p.Columns) ?? 1, + ]; + return unpredict(out, colors, bits, columns); + } + + /** Whether `endstream` follows `at`, after the line's end. */ + #endsStream(at: number): boolean { + const lexer = this.lexer(at); + return lexer.next() === TOKEN.word && lexer.is("endstream"); + } + + /** Where the first `endstream` at or after `at` starts, found from one scan of the file. */ + #endstream(at: number): number { + if (this.#ends === undefined) { + this.budget.spend(this.bytes.length); + this.#ends = []; + for (let i = indexOf(this.bytes, ENDSTREAM, 0, this.bytes.length); i >= 0;) { + this.#ends.push(i); + i = indexOf(this.bytes, ENDSTREAM, i + 1, this.bytes.length); + } + } + const ends = this.#ends; + let [lo, hi] = [0, ends.length]; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (ends[mid]! < at) lo = mid + 1; + else hi = mid; + } + return ends[lo] ?? -1; + } + + /** The value `v` refers to, following a chain of references a few deep. */ + resolve(v: Value | undefined): Value | undefined { + for (let hops = 0; isRef(v); hops++) { + if (hops >= HOPS) return undefined; + v = this.object(v.ref, v.gen)?.value; + } + return v; + } +} + +/** Adds the object at `at` to `list` unless it ends the list already. */ +function once(list: number[], at: number): void { + if (at >= 0 && list[list.length - 1] !== at) list.push(at); +} + +/** The one element of a one-element array, the value itself, or null for none. */ +function single(v: Value | undefined): Value | undefined { + if (v === undefined || v === null) return null; + if (!Array.isArray(v)) return v; + return v.length === 0 ? null : v.length === 1 ? v[0] : undefined; +} + +/** The header `N G obj` whose `obj` is at `i`: the object's number and where the header starts. */ +function headerAt(bytes: Uint8Array, i: number): { number: number; start: number } | undefined { + let j = i - 1; + const skip = (test: (c: number) => boolean, most: number): number => { + const from = j; + while (j >= 0 && from - j < most && test(bytes[j]!)) j--; + return from - j; + }; + if (skip(WHITE, 8) === 0 || skip(DIGIT, 6) === 0 || skip(WHITE, 8) === 0) return undefined; + const end = j + 1; + if (skip(DIGIT, 11) === 0 || (j >= 0 && REGULAR(bytes[j]!))) return undefined; + const number = Number(latin1(bytes, j + 1, end)); + return Number.isSafeInteger(number) ? { number, start: j + 1 } : undefined; +} + +/** A stream's bytes with its PNG predictor undone, row by row. */ +function unpredict( + data: Uint8Array, + colors: Value | undefined, + bits: Value | undefined, + columns: Value | undefined, +): Uint8Array | undefined { + if (!isInt(colors) || colors < 1 || colors > 32 || !isInt(columns) || columns < 1) + return undefined; + if (bits !== 1 && bits !== 2 && bits !== 4 && bits !== 8 && bits !== 16) return undefined; + const pixel = Math.max(1, Math.ceil((colors * bits) / 8)); + const width = Math.ceil((colors * bits * columns) / 8); + if (width + 1 > data.length) return new Uint8Array(0); + const rows = Math.floor(data.length / (width + 1)); + const out = new Uint8Array(rows * width); + for (let r = 0; r < rows; r++) { + const filter = data[r * (width + 1)]!; + const from = r * (width + 1) + 1; + const at = r * width; + for (let x = 0; x < width; x++) { + const raw = data[from + x]!; + const left = x >= pixel ? out[at + x - pixel]! : 0; + const up = r > 0 ? out[at - width + x]! : 0; + const corner = r > 0 && x >= pixel ? out[at - width + x - pixel]! : 0; + let v: number; + if (filter === 0) v = raw; + else if (filter === 1) v = raw + left; + else if (filter === 2) v = raw + up; + else if (filter === 3) v = raw + ((left + up) >>> 1); + else if (filter === 4) { + const p = left + up - corner; + const [pa, pb, pc] = [Math.abs(p - left), Math.abs(p - up), Math.abs(p - corner)]; + v = raw + (pa <= pb && pa <= pc ? left : pb <= pc ? up : corner); + } else return undefined; + out[at + x] = v & 255; + } + } + return out; +} + +/** A box `[x0 y0 x1 y1]` in points, put in order, or undefined where it is not four numbers. */ +function boxOf(file: PdfFile, v: Value | undefined): [number, number, number, number] | undefined { + const box = file.resolve(v); + if (!Array.isArray(box) || box.length !== 4) return undefined; + const [a, b, c, d] = box.map((x) => file.resolve(x)); + const finite = (x: Value | undefined): x is number => typeof x === "number" && Number.isFinite(x); + if (!finite(a) || !finite(b) || !finite(c) || !finite(d)) return undefined; + return [Math.min(a, c), Math.min(b, d), Math.max(a, c), Math.max(b, d)]; +} + +/** + * Walks the page tree in order, counting its pages, to page `wanted`, and carries down the boxes + * and the turn each node on the way gives its pages. It trusts no `/Count`, which a file edited in + * place may hold stale, follows no `/Parent`, and enters no node twice. An entry that is null is + * none, so a page takes its parent's. + */ +function pageSize(file: PdfFile, wanted: number): readonly [number, number] | undefined { + const catalog = file.resolve(file.root); + if (!isDict(catalog)) return undefined; + type Inherited = { media?: Value; crop?: Value; rotate?: Value }; + const given = (v: Value | undefined): boolean => v !== undefined && file.resolve(v) != null; + const entered = new Set(); + const rootRef = catalog.dict.Pages; + if (isRef(rootRef)) entered.add(rootRef.ref); + // A frame for each node on the way down: its kids and the next to enter, so the walk holds no + // more than the depth of the tree and reads a kid only when it comes to it. + const frames: { kids: Value[]; next: number; inherited: Inherited }[] = []; + let left = wanted; + let node: Value | undefined = file.resolve(rootRef); + let above: Inherited = {}; + for (;;) { + if (node !== undefined) { + if (!isDict(node)) { + file.broken = true; + return undefined; + } + const d: Partial> = node.dict; + const inherited: Inherited = { + ...above, + ...(given(d.MediaBox) ? { media: d.MediaBox } : {}), + ...(given(d.CropBox) ? { crop: d.CropBox } : {}), + ...(given(d.Rotate) ? { rotate: d.Rotate } : {}), + }; + const kind = file.resolve(d.Type); + const isNode = isName(kind) ? kind.name === "Pages" : d.Kids !== undefined; + if (!isNode) { + if (--left === 0) return sizeOf(file, d, inherited); + } else { + const kids = file.resolve(d.Kids); + if (!Array.isArray(kids)) { + file.broken = true; + return undefined; + } + if (frames.length >= DEPTH) return undefined; + file.budget.spend(kids.length); + frames.push({ kids, next: 0, inherited }); + } + node = undefined; + } + const top = frames[frames.length - 1]; + if (top === undefined) return undefined; + if (top.next >= top.kids.length) { + frames.pop(); + continue; + } + const kid = top.kids[top.next++]; + if (isRef(kid)) { + if (entered.has(kid.ref)) return undefined; + entered.add(kid.ref); + } + node = file.resolve(kid); + if (node === undefined || node === null) { + file.broken = true; + return undefined; + } + above = top.inherited; + } +} + +function sizeOf( + file: PdfFile, + page: Partial>, + inherited: { media?: Value; crop?: Value; rotate?: Value }, +): readonly [number, number] | undefined { + const media = boxOf(file, inherited.media); + if (media === undefined) return undefined; + const crop = boxOf(file, inherited.crop); + let [x0, y0, x1, y1] = media; + if (crop !== undefined) { + const cut = [ + Math.max(x0, crop[0]), + Math.max(y0, crop[1]), + Math.min(x1, crop[2]), + Math.min(y1, crop[3]), + ]; + if (cut[2]! > cut[0]! && cut[3]! > cut[1]!) + [x0, y0, x1, y1] = cut as [number, number, number, number]; + } + const unit = file.resolve(page.UserUnit); + const scale = typeof unit === "number" && Number.isFinite(unit) && unit > 0 ? unit : 1; + const rotate = file.resolve(inherited.rotate); + const turn = + typeof rotate === "number" && Number.isInteger(rotate) && rotate % 90 === 0 ? rotate : 0; + const [w, h] = [((x1 - x0) / 72) * scale, ((y1 - y0) / 72) * scale]; + const size: [number, number] = Math.abs(turn % 180) === 90 ? [h, w] : [w, h]; + return size.every((x) => Number.isFinite(x) && x > 0) ? size : undefined; +} diff --git a/src/raster.ts b/src/raster.ts index 82aa92e..70e93da 100644 --- a/src/raster.ts +++ b/src/raster.ts @@ -220,6 +220,10 @@ class Inflater { this.#out = new Uint8Array(Math.min(limit, Math.max(1024, input.length * 4))); } + get written(): number { + return this.#length; + } + bits(n: number): number { while (this.#bits < n) { if (this.#at >= this.input.length) { @@ -375,6 +379,16 @@ export function inflate(bytes: Uint8Array, limit: number): Uint8Array | undefine return new Inflater(bytes, limit).run(); } +/** As `inflate`, with the count of bytes it wrote before it ended, broken or not. */ +export function inflateCounted( + bytes: Uint8Array, + limit: number, +): { readonly bytes: Uint8Array | undefined; readonly written: number } { + const inflater = new Inflater(bytes, limit); + const out = inflater.run(); + return { bytes: out, written: inflater.written }; +} + /** A PNG's pixels at 8 bits a sample, rows from the top, in its own samples: gray, RGB and alpha. */ export interface PngPixels { readonly width: number; diff --git a/test/pdf-pages.test.ts b/test/pdf-pages.test.ts new file mode 100644 index 0000000..12a91ce --- /dev/null +++ b/test/pdf-pages.test.ts @@ -0,0 +1,564 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { runInNewContext } from "node:vm"; +import { deflateSync } from "node:zlib"; +import { createDrawing, pdfPageSize, toPDF } from "../src/index.ts"; +import { timeLimit } from "./time-limit.ts"; + +const latin1 = (text: string): Uint8Array => Uint8Array.from(text, (c) => c.charCodeAt(0) & 255); +const text = (bytes: Uint8Array): string => String.fromCharCode(...bytes); + +/** An object of a PDF being built: its number and its body, with a stream's bytes if any. */ +interface Part { + readonly n: number; + readonly body: string; + readonly stream?: Uint8Array; +} + +function objectBytes({ n, body, stream }: Part): string { + if (stream === undefined) return `${n} 0 obj\n${body}\nendobj\n`; + return `${n} 0 obj\n${body}\nstream\n${text(stream)}\nendstream\nendobj\n`; +} + +/** A PDF with a classic cross-reference table, and the offset of its table. */ +function classic(parts: readonly Part[], trailer = "/Root 1 0 R", prefix = ""): string { + let pdf = prefix || "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n"; + const at = new Map(); + for (const part of parts) { + at.set(part.n, pdf.length); + pdf += objectBytes(part); + } + const numbers = [...at.keys()].sort((a, b) => a - b); + const xref = pdf.length; + pdf += "xref\n"; + if (prefix === "") pdf += "0 1\n0000000000 65535 f \n"; + for (const n of numbers) { + pdf += `${n} 1\n${String(at.get(n)).padStart(10, "0")} 00000 n \n`; + } + const size = Math.max(0, ...numbers) + 1; + return `${pdf}trailer\n<< /Size ${size} ${trailer} >>\nstartxref\n${xref}\n%%EOF\n`; +} + +/** Big-endian bytes of `v` in `w` bytes. */ +const be = (v: number, w: number): number[] => + Array.from({ length: w }, (_, i) => Math.floor(v / 256 ** (w - 1 - i)) & 255); + +/** Rows with PNG predictor 12 (up) applied, a 0 or 2 before each row. */ +function predicted(rows: number[][]): Uint8Array { + const out: number[] = []; + rows.forEach((row, r) => { + out.push(2, ...row.map((b, i) => (b - (r > 0 ? rows[r - 1]![i]! : 0)) & 255)); + }); + return new Uint8Array(out); +} + +/** + * A PDF 1.5 file with a cross-reference stream compressed with a PNG predictor, and `packed` + * objects inside one object stream. + */ +function modern(loose: readonly Part[], packed: readonly Part[], trailer = "/Root 1 0 R"): string { + let pdf = "%PDF-1.5\n"; + const rows = new Map(); + for (const part of loose) { + rows.set(part.n, [1, ...be(pdf.length, 3), 0]); + pdf += objectBytes(part); + } + const all = [...loose.map((p) => p.n), ...packed.map((p) => p.n)]; + const top = Math.max(0, ...all) + 1; + if (packed.length > 0) { + const stm = top; + let header = ""; + let bodies = ""; + packed.forEach((part, i) => { + header += `${part.n} ${bodies.length} `; + bodies += `${part.body}\n`; + rows.set(part.n, [2, ...be(stm, 3), i]); + }); + const data = deflateSync(latin1(header + bodies)); + rows.set(stm, [1, ...be(pdf.length, 3), 0]); + pdf += objectBytes({ + n: stm, + body: `<< /Type /ObjStm /N ${packed.length} /First ${header.length} /Filter /FlateDecode /Length ${data.length} >>`, + stream: data, + }); + } + const xrefN = top + 1; + rows.set(xrefN, [1, ...be(pdf.length, 3), 0]); + const table: number[][] = []; + for (let n = 0; n <= xrefN; n++) table.push(rows.get(n) ?? [0, 0, 0, 0, 0]); + const data = deflateSync(predicted(table)); + const xref = pdf.length; + pdf += objectBytes({ + n: xrefN, + body: `<< /Type /XRef /Size ${xrefN + 1} /W [1 3 1] ${trailer} /Filter /FlateDecode /DecodeParms << /Predictor 12 /Columns 5 >> /Length ${data.length} >>`, + stream: data, + }); + return `${pdf}startxref\n${xref}\n%%EOF\n`; +} + +/** The catalog, a page tree of one page, and the page with `page` in its dictionary. */ +const onePage = (page: string, tree = ""): Part[] => [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: `<< /Type /Pages /Kids [3 0 R] /Count 1 ${tree} >>` }, + { n: 3, body: `<< /Type /Page /Parent 2 0 R ${page} >>` }, +]; + +const size = (pdf: string | Uint8Array, page: string | number = 1) => + pdfPageSize(typeof pdf === "string" ? latin1(pdf) : pdf, page); + +test("a page's MediaBox, in inches", () => { + assert.deepEqual(size(classic(onePage("/MediaBox [0 0 612 792]"))), [8.5, 11]); + // Corners in either order, off the origin. + assert.deepEqual(size(classic(onePage("/MediaBox [72 792 684 0]"))), [8.5, 11]); + // Reals, and a box that is no box. + assert.deepEqual(size(classic(onePage("/MediaBox [0.0 0 1224.0 792.]"))), [17, 11]); + assert.equal(size(classic(onePage("/MediaBox [0 0 612]"))), undefined); + assert.equal(size(classic(onePage("/MediaBox [0 0 0 792]"))), undefined); + assert.equal(size(classic(onePage(""))), undefined); +}); + +test("the CropBox cut to the MediaBox", () => { + const crop = (box: string) => size(classic(onePage(`/MediaBox [0 0 1224 792] /CropBox ${box}`))); + assert.deepEqual(crop("[36 36 1188 756]"), [16, 10]); + assert.deepEqual(crop("[-100 -100 612 2000]"), [8.5, 11]); + // A CropBox that misses the MediaBox, or is broken, leaves the MediaBox. + assert.deepEqual(crop("[2000 2000 3000 3000]"), [17, 11]); + assert.deepEqual(crop("[1 2 3]"), [17, 11]); +}); + +test("boxes and the turn are inherited from the page tree", () => { + const tree = "/MediaBox [0 0 2592 1728] /CropBox [0 0 1728 1728] /Rotate 90"; + assert.deepEqual(size(classic(onePage("", tree))), [24, 24]); + assert.deepEqual(size(classic(onePage("", "/MediaBox [0 0 2592 1728] /Rotate 90"))), [24, 36]); + // The page's own box and turn win over the tree's. + assert.deepEqual(size(classic(onePage("/MediaBox [0 0 612 792] /Rotate 0", tree))), [8.5, 11]); + // Through two levels of the tree. + const deep: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: "<< /Type /Pages /Kids [4 0 R] /Count 1 /MediaBox [0 0 1224 792] >>" }, + { n: 4, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 /Parent 2 0 R /Rotate 270 >>" }, + { n: 3, body: "<< /Type /Page /Parent 4 0 R >>" }, + ]; + assert.deepEqual(size(classic(deep)), [11, 17]); +}); + +test("a turn of 90 or 270 swaps width and height", () => { + const turned = (rotate: string) => + size(classic(onePage(`/MediaBox [0 0 1224 792] /Rotate ${rotate}`))); + assert.deepEqual(turned("0"), [17, 11]); + assert.deepEqual(turned("90"), [11, 17]); + assert.deepEqual(turned("180"), [17, 11]); + assert.deepEqual(turned("270"), [11, 17]); + assert.deepEqual(turned("-90"), [11, 17]); + assert.deepEqual(turned("-180"), [17, 11]); + assert.deepEqual(turned("450"), [11, 17]); + // A turn that is not a multiple of 90 counts as none. + assert.deepEqual(turned("45"), [17, 11]); + assert.deepEqual(turned("/East"), [17, 11]); +}); + +test("UserUnit scales the page", () => { + assert.deepEqual(size(classic(onePage("/MediaBox [0 0 144 72] /UserUnit 10"))), [20, 10]); + assert.deepEqual(size(classic(onePage("/MediaBox [0 0 144 72] /UserUnit 0"))), [2, 1]); + assert.deepEqual(size(classic(onePage("/MediaBox [0 0 144 72] /UserUnit -3"))), [2, 1]); +}); + +test("numbers, boxes, counts, kids and turns given by reference", () => { + const parts: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: "<< /Type /Pages /Kids 7 0 R /Count 8 0 R /Rotate 9 0 R >>" }, + { n: 3, body: "<< /Type /Page /Parent 2 0 R /MediaBox 4 0 R /UserUnit 10 0 R >>" }, + { n: 4, body: "[0 0 5 0 R 6 0 R]" }, + { n: 5, body: "1224" }, + { n: 6, body: "792" }, + { n: 7, body: "[3 0 R]" }, + { n: 8, body: "1" }, + { n: 9, body: "-270" }, + { n: 10, body: "2" }, + ]; + assert.deepEqual(size(classic(parts)), [22, 34]); +}); + +test("pages are numbered from 1, as a string or a number", () => { + const parts: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 4 >>" }, + { n: 3, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>" }, + { n: 4, body: "<< /Type /Pages /Parent 2 0 R /Kids [6 0 R 7 0 R] /Count 2 >>" }, + { n: 5, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 2592 1728] >>" }, + { n: 6, body: "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 1224 792] >>" }, + { n: 7, body: "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 1728 1224] >>" }, + ]; + const pdf = classic(parts); + assert.deepEqual(size(pdf, 1), [8.5, 11]); + assert.deepEqual(size(pdf, "1"), [8.5, 11]); + assert.deepEqual(size(pdf, 2), [17, 11]); + assert.deepEqual(size(pdf, "3"), [24, 17]); + assert.deepEqual(size(pdf, 4), [36, 24]); + for (const page of [0, 5, -1, 1.5, NaN, Infinity, "0", "01", " 1", "1 ", "+1", "1.0", "", "a"]) { + assert.equal(size(pdf, page), undefined, String(page)); + } + assert.equal(size(pdf, null as unknown as number), undefined); +}); + +test("a cross-reference stream with a predictor, and objects in an object stream", () => { + const [catalog, tree, page] = onePage("/MediaBox [0 0 1224 792] /Rotate 90"); + assert.deepEqual(size(modern([catalog!, tree!, page!], [])), [11, 17]); + assert.deepEqual(size(modern([], [catalog!, tree!, page!])), [11, 17]); + assert.deepEqual(size(modern([catalog!], [tree!, page!])), [11, 17]); + // The predictor is needed: without it the rows are read wrong. + const plain = text(latin1(modern([catalog!], [tree!, page!]))); + assert.equal(size(plain.replace("/Predictor 12", "/Predictor 01")), undefined); + // A filter it does not read. + assert.equal( + size(plain.replace("/Filter /FlateDecode /Length", "/Filter /LZWDecode /Length")), + undefined, + ); +}); + +test("an incremental update changes a box, the newest winning", () => { + const first = classic(onePage("/MediaBox [0 0 612 792]")); + const prev = Number(/startxref\n(\d+)/.exec(first)![1]); + const page = { n: 3, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 1224 792] >>" }; + const update = classic([page], `/Root 1 0 R /Prev ${prev}`, first); + assert.deepEqual(size(update), [17, 11]); + assert.deepEqual(size(first), [8.5, 11]); + // A /Prev that points at itself ends. + const looped = update.replace( + `/Prev ${prev}`, + `/Prev ${Number(/startxref\n(\d+)\n%%EOF\n$/.exec(update)![1])}`, + ); + assert.deepEqual(size(looped), [17, 11]); +}); + +test("a broken cross-reference is read by scanning for the objects", () => { + const pdf = classic(onePage("/MediaBox [0 0 612 792]")); + // Every offset off by 3. + const moved = pdf.replace( + /^(\d{10}) 00000 n $/gm, + (_, at) => `${String(Number(at) + 3).padStart(10, "0")} 00000 n `, + ); + assert.deepEqual(size(moved), [8.5, 11]); + assert.deepEqual(size(pdf.replace(/startxref\n\d+/, "startxref\n999999")), [8.5, 11]); + assert.deepEqual(size(pdf.slice(0, pdf.indexOf("xref\n"))), [8.5, 11]); + // Object streams found through a cross-reference stream the scan finds. + const [catalog, tree, page] = onePage("/MediaBox [0 0 1224 792]"); + const modernPdf = modern([catalog!], [tree!, page!]); + assert.deepEqual(size(modernPdf.replace(/startxref\n\d+/, "startxref\n5")), [17, 11]); +}); + +test("an encrypted file reads where its pages are outside object streams", () => { + const encrypt = "/Root 1 0 R /Encrypt 9 0 R"; + const parts = [ + ...onePage("/MediaBox [0 0 612 792]"), + { n: 9, body: "<< /Filter /Standard /V 2 >>" }, + ]; + assert.deepEqual(size(classic(parts, encrypt)), [8.5, 11]); + const [catalog, tree, page] = onePage("/MediaBox [0 0 612 792]"); + assert.equal(size(modern([catalog!, parts[3]!], [tree!, page!], encrypt)), undefined); +}); + +test("a page tree that loops, or is too deep, gives undefined", () => { + const cycle: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: "<< /Type /Pages /Kids [4 0 R] /Count 1 /MediaBox [0 0 612 792] >>" }, + { n: 4, body: "<< /Type /Pages /Kids [2 0 R] /Count 1 /Parent 4 0 R >>" }, + ]; + assert.equal(size(classic(cycle)), undefined); + const self: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: "<< /Type /Pages /Kids [2 0 R] /Count 1 >>" }, + ]; + assert.equal(size(classic(self)), undefined); + const chain: Part[] = [{ n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }]; + for (let n = 2; n < 400; n++) { + chain.push({ n, body: `<< /Type /Pages /Kids [${n + 1} 0 R] /Count 1 >>` }); + } + chain.push({ n: 400, body: "<< /Type /Page /MediaBox [0 0 612 792] >>" }); + assert.equal(size(classic(chain)), undefined); + assert.deepEqual( + size( + classic( + chain + .slice(0, 1) + .concat(chain.slice(300)) + .map((p, i) => (i === 0 ? { n: 1, body: "<< /Type /Catalog /Pages 301 0 R >>" } : p)), + ), + ), + [8.5, 11], + ); + // A reference to a reference to itself. + assert.equal(size(classic([...onePage("/MediaBox 4 0 R"), { n: 4, body: "4 0 R" }])), undefined); +}); + +test("garbage and truncated files give undefined", () => { + for (const bytes of [ + "", + "%PDF-", + "%PDF-1.7\n", + "hello", + "%PDF-1.4\n1 0 obj << /Pages", + "<<<<<<<<", + ]) { + assert.equal(size(bytes), undefined, bytes); + } + const pdf = classic(onePage("/MediaBox [0 0 612 792]")); + assert.equal(size(pdf.replace("%PDF-", "%XYZ-")), undefined); + for (let cut = 0; cut < pdf.length; cut += 7) { + const found = size(pdf.slice(0, cut)); + assert.ok(found === undefined || (found[0] === 8.5 && found[1] === 11), String(cut)); + } + assert.equal(pdfPageSize("%PDF-1.4" as unknown as Uint8Array, 1), undefined); +}); + +test("the size of each page of a PDF toPDF writes", () => { + const d = createDrawing({ units: "ft" }); + d.layout("A", { paper: "ANSI B" }, () => {}); + d.layout("B", { paper: "ARCH E" }, () => {}); + d.layout("C", { paper: "ARCH D" }, () => {}); + const drawing = d.build(); + for (const pdf of [toPDF(drawing), toPDF(drawing, { deflate: (b) => deflateSync(b) })]) { + assert.deepEqual(pdfPageSize(pdf, 1), [17, 11]); + assert.deepEqual(pdfPageSize(pdf, "2"), [48, 36]); + assert.deepEqual(pdfPageSize(pdf, 3), [36, 24]); + assert.equal(pdfPageSize(pdf, 4), undefined); + } +}); + +/** A seeded generator of whole numbers below `n`. */ +function seeded(seed: number): (n: number) => number { + return (n) => { + seed = (seed * 1103515245 + 12345) >>> 0; + return Math.floor((seed / 2 ** 32) * n); + }; +} + +test("mutated PDFs give a size or undefined, never a throw, within the time limit", () => { + const d = createDrawing({ units: "ft" }); + d.layout("A", { paper: "ANSI B" }, () => {}); + d.layout("B", { paper: "ARCH E" }, () => {}); + const [catalog, tree, page] = onePage( + "/MediaBox [0 0 1224 792] /CropBox [0 0 600 700] /Rotate 90", + ); + const seeds = [ + toPDF(d.build()), + latin1( + classic( + onePage("/MediaBox 4 0 R /Rotate 5 0 R").concat([ + { n: 4, body: "[0 0 612 792]" }, + { n: 5, body: "90" }, + ]), + ), + ), + latin1(modern([catalog!], [tree!, page!])), + ]; + const big = [ + "99999999999", + "-1", + "1e308", + "4294967296", + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[", + "<<".repeat(400), + "(", + "1 0 R ".repeat(50), + ]; + const random = seeded(12); + const checked = (bytes: Uint8Array, page: number): void => { + const found = pdfPageSize(bytes, page); + if (found === undefined) return; + assert.equal(found.length, 2); + for (const x of found) assert.ok(Number.isFinite(x) && x > 0, String(found)); + }; + runInNewContext( + `for (let i = 0; i < 4000; i++) run(i);`, + { + run: (i: number) => { + const seed = seeds[i % seeds.length]!; + let bytes: Uint8Array; + const kind = random(4); + if (kind === 0) bytes = seed.slice(0, random(seed.length)); + else if (kind === 1) { + bytes = seed.slice(); + for (let k = 0; k < 1 + random(6); k++) bytes[random(bytes.length)] = random(256); + } else if (kind === 2) { + // A number or a token replaced by a huge one, a deep nesting or an open string. + const t = text(seed); + const spots = [...t.matchAll(/\d+|\[|< { + const parts: Part[] = [{ n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }]; + const kids: string[] = []; + for (let n = 3; n < 10_003; n++) { + kids.push(`${n} 0 R`); + parts.push({ n, body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${n} 72] >>` }); + } + parts.push({ n: 2, body: `<< /Type /Pages /Kids [${kids.join(" ")}] /Count ${kids.length} >>` }); + const pdf = classic(parts); + const broken = latin1(pdf.replace(/startxref\n\d+/, "startxref\n1")); + runInNewContext( + `check()`, + { + check: () => { + assert.deepEqual(pdfPageSize(latin1(pdf), 10_000), [10_002 / 72, 1]); + assert.deepEqual(pdfPageSize(broken, 10_000), [10_002 / 72, 1]); + }, + }, + { timeout: timeLimit(1500) }, + ); +}); + +test("a page whose entry is off is found by the scan, never taken for the next page", () => { + const parts: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>" }, + { n: 3, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 2592 1728] >>" }, + { n: 4, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 2592 1728] /Rotate 90 >>" }, + { n: 5, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>" }, + ]; + const pdf = classic(parts); + const at = pdf.indexOf("4 0 obj"); + const off = pdf.replace( + `${String(at).padStart(10, "0")} 00000 n `, + `${String(at + 7).padStart(10, "0")} 00000 n `, + ); + assert.deepEqual(size(off, 2), [24, 36]); + assert.deepEqual(size(off, 3), [8.5, 11]); +}); + +test("pages are counted in order, whatever a stale /Count says", () => { + const parts: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 2, body: "<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 3 >>" }, + { n: 3, body: "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 1 >>" }, + { n: 4, body: "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>" }, + { n: 5, body: "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 1224 792] >>" }, + { n: 6, body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 2592 1728] >>" }, + ]; + assert.deepEqual(size(classic(parts), 2), [17, 11]); + assert.deepEqual(size(classic(parts), 3), [36, 24]); +}); + +test("a null entry is none, so the page takes its parent's", () => { + const tree = "/MediaBox [0 0 1224 792] /CropBox [0 0 720 432] /Rotate 90"; + assert.deepEqual(size(classic(onePage("/CropBox null /Rotate null", tree))), [6, 10]); +}); + +test("a reference to a free object, or one of another generation, is null", () => { + const parts = [...onePage("/MediaBox [0 0 1224 792] /CropBox 4 0 R")]; + let pdf = classic([...parts, { n: 4, body: "[0 0 432 432]" }]); + assert.deepEqual(size(pdf), [6, 6]); + pdf = pdf.replace(/4 1\n(\d{10}) 00000 n /, "4 1\n$1 00001 n "); + assert.deepEqual(size(pdf), [17, 11]); + // Freed by a later update. + const first = classic([...parts, { n: 4, body: "[0 0 432 432]" }]); + const prev = Number(/startxref\n(\d+)/.exec(first)![1]); + const freed = `${first}xref\n4 1\n0000000000 00001 f \ntrailer\n<< /Size 5 /Root 1 0 R /Prev ${prev} >>\nstartxref\n${first.length}\n%%EOF\n`; + assert.deepEqual(size(freed), [17, 11]); +}); + +test("object streams whose counts lead through other object streams stop, without a throw", () => { + // Stream k's /N is a reference to an object packed in stream k + 1, thousands deep. + const depth = 3000; + let pdf = "%PDF-1.5\n"; + const offsets: number[] = []; + const put = (n: number, body: string, stream?: string) => { + offsets[n] = pdf.length; + pdf += + stream === undefined + ? `${n} 0 obj\n${body}\nendobj\n` + : `${n} 0 obj\n${body}\nstream\n${stream}\nendstream\nendobj\n`; + }; + // Objects 10 + k (k < depth) are object streams; object 10000 + k is packed in stream 10 + k + 1. + for (let k = 0; k < depth; k++) { + const data = `${10000 + k} 0 1\n`; + put( + 10 + k, + `<< /Type /ObjStm /N ${10000 + k} 0 R /First ${data.length - 2} /Length ${data.length} >>`, + data, + ); + } + const xref = pdf.length; + let table = "xref\n0 1\n0000000000 65535 f \n"; + for (let k = 0; k < depth; k++) + table += `${10 + k} 1\n${String(offsets[10 + k]).padStart(10, "0")} 00000 n \n`; + pdf += `${table}trailer\n<< /Size 20000 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; + const t = performance.now(); + assert.equal(size(pdf), undefined); + assert.ok(performance.now() - t < timeLimit(2000)); +}); + +test("a table off by a row, or of other generations than its objects, is read by the scan", () => { + const pdf = classic(onePage("/MediaBox [0 0 2592 1728]")); + // Numbered from 1, a writer's mistake: object 1 lands on the free row. + const fromOne = pdf.replace("xref\n0 1\n", "xref\n1 1\n"); + assert.deepEqual(size(fromOne), [36, 24]); + const generations = pdf.replace(/ 00000 n /g, " 00001 n "); + assert.deepEqual(size(generations), [36, 24]); +}); + +test("a hybrid file's objects in object streams, which its table marks free, are read", () => { + let pdf = "%PDF-1.5\n"; + const at: number[] = []; + const put = (part: Part): void => { + at[part.n] = pdf.length; + pdf += objectBytes(part); + }; + onePage("/MediaBox [0 0 432 720] /CropBox 4 0 R").forEach(put); + const packed = "4 0 [0 0 216 144]"; + put({ + n: 5, + body: `<< /Type /ObjStm /N 1 /First 4 /Length ${packed.length} >>`, + stream: latin1(packed), + }); + const rows = [2, ...be(5, 3), 0]; + put({ + n: 6, + body: `<< /Type /XRef /Size 7 /Index [4 1] /W [1 3 1] /Length ${rows.length} >>`, + stream: new Uint8Array(rows), + }); + const xref = pdf.length; + const row = (n: number) => `${String(at[n]).padStart(10, "0")} 00000 n \n`; + pdf += `xref\n0 7\n0000000000 65535 f \n${row(1)}${row(2)}${row(3)}0000000000 00000 f \n`; + pdf += `${row(5)}${row(6)}trailer\n<< /Size 7 /Root 1 0 R /XRefStm ${at[6]} >>\n`; + assert.deepEqual(size(`${pdf}startxref\n${xref}\n%%EOF\n`), [3, 2]); +}); + +test("an offset past the end of the file charges the budget, never refunds it", () => { + // The tree's root names an object whose row points past the file; each of its nodes names an + // object that opens a string and never closes it, so each read runs to the end of the file. + const nodes = 1000; + const parts: Part[] = [ + { n: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" }, + { n: 9, body: "0" }, + ]; + const kids: string[] = []; + for (let i = 0; i < nodes; i++) { + const n = 10 + 2 * i; + kids.push(`${n} 0 R`); + parts.push({ n, body: `<< /Type /Pages /Kids [] /Rotate ${n + 1} 0 R >>` }); + parts.push({ n: n + 1, body: "(" }); + } + parts.push({ n: 2, body: `<< /Type /Pages /Kids [${kids.join(" ")}] /Rotate 9 0 R >>` }); + parts.push({ n: 8, body: `<< /Pad <${"0".repeat(4_000_000)}> >>` }); + const pdf = classic(parts).replace(/^\d{10}( 00000 n \n)(?=10 1\n)/m, "9999999999$1"); + runInNewContext( + `check()`, + { check: () => assert.equal(size(pdf), undefined) }, + { timeout: timeLimit(1500) }, + ); +}); From 952032cbdc5facdbf5da3368c442532812b68956 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 19:58:53 -0500 Subject: [PATCH 27/35] An entity's own transparency: written, read and plotted as CAD programs hold it An entity's own transparency, in R2018 drawings. - Every entity but a table takes `transparency`: a whole percent from 0 to 90 (50 for half, not 0.5), `"ByLayer"`, the default, or `"ByBlock"`, which an entity of a block takes from its insert. The builder and `lint` refuse anything else under the rule `entity-transparency`. They also refuse a transparency on a table, one in an R12 drawing, and a percent on an entity of a block a leader places. - `toDXF` writes it in group 440 as CAD programs store it. A dimension's picture holds every part transparent ByBlock. A block a leader places holds every entity ByBlock, as CAD programs read it, and the leader draws it opaque. - `toSVG` and `toPDF` draw every entity opaque by default, as CAD programs plot the page setups tsdraft writes. With `plotTransparency: true`, each entity draws at its transparency. It is composed first, so its overlapping parts are no darker, and drawn as an SVG group with an `opacity` or a PDF transparency group. A dimension's or a leader's arrowhead drawn from a block plots opaque, as CAD programs plot it. - `readDXF` reads it as `alpha`, from 0 to 255, or `"ByBlock"`. - `docs/transparency.md` has the details. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 13 ++- GUIDE.md | 4 +- README.md | 6 +- docs/colors.md | 1 + docs/format.md | 2 + docs/plotting.md | 3 + docs/reading.md | 6 +- docs/transparency.md | 73 +++++++++++++ src/blocks.ts | 67 +++++++++++- src/drawing.ts | 67 +++++++++++- src/dxf-r2018.ts | 41 ++++++-- src/index.ts | 4 + src/leaders.ts | 57 ++++++++++ src/lint.ts | 22 ++++ src/pdf.ts | 234 ++++++++++++++++++++++++++++++++++++++--- src/read/check.ts | 8 ++ src/read/entities.ts | 3 + src/read/model.ts | 6 ++ src/rules.ts | 11 ++ src/shape.ts | 12 +++ src/svg.ts | 129 +++++++++++++++++++---- src/transparency.ts | 45 ++++++++ test/bounded.test.ts | 3 +- test/images.test.ts | 26 +++++ test/pdf.test.ts | 131 ++++++++++++++++++++++- test/read-agreement.ts | 10 +- test/rules.test.ts | 102 ++++++++++++++++++ test/shape.test.ts | 19 +++- 28 files changed, 1038 insertions(+), 67 deletions(-) create mode 100644 docs/transparency.md create mode 100644 src/transparency.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1acfff7..4a1daee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,18 @@ it. A read names the file's `version`, and for 2004 its `codepage`. A table of the 2004 format is counted under `unread.entities` and not read yet, and a drawing of the 2007 format is refused with a `ReadError` that names it; both come next. - +- An entity's own transparency, in R2018 drawings. Every entity but a table takes + `transparency`: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`, which + an entity of a block takes from its insert. `toDXF` writes it in group 440 as CAD programs store + it, and a dimension's picture holds every part transparent ByBlock. `toSVG` and `toPDF` draw + every entity opaque, as CAD programs plot the page setups tsdraft writes, and with + `plotTransparency: true` each entity at its transparency, composed first so its overlapping + parts are no darker, in a group with an `opacity` and a PDF transparency group. `lint` and the + builder refuse any other value under the rule `entity-transparency`, a transparency on a table, + a percent on an entity of a block a leader places, and one in an R12 drawing. `readDXF` and + `readDWG` read it as `alpha`, from 0 to 255, or `"ByBlock"`. A block a leader places holds + every entity ByBlock, as CAD programs read it, and the writers write it so; the leader draws + it opaque. - Linetypes with shapes: a fence with its circles along it, and batt insulation. `parseShapes` reads a firm's compiled shape file (`.shx`) into each shape's outlines, and `toSVG`, `toPDF` and `lint` take the files' bytes as `shapes`, found by name as CAD programs find them, without diff --git a/GUIDE.md b/GUIDE.md index b682060..ac48082 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -680,8 +680,8 @@ writeFileSync("plan.dxf", toDXF(drawing)); for another plotter. - The spacing of characters inside a paragraph, `\T`, and an overline, `\O`. - Ellipses and splines. -- Transparency on a single entity, and a color of a color book. A color of an entity is an index - or a true color: see [docs/colors.md](docs/colors.md). +- A color of a color book. A color of an entity is an index or a true color: see + [docs/colors.md](docs/colors.md), and an entity's transparency [docs/transparency.md](docs/transparency.md). - DWG files. tsdraft writes DXF. - An existing drawing as a background or a base to edit. `readDXF` reads a DXF's tables, blocks, layouts and a census of what it draws, and with `geometry` what each space draws, as diff --git a/README.md b/README.md index 0dce381..213369b 100644 --- a/README.md +++ b/README.md @@ -319,8 +319,8 @@ feet and inches with stacked fractions, words below the line and text on a leade layers or twist the view, and layers that are off, frozen, locked or not plotted. A firm's [standard](docs/standard.md) sets its layers, pens, text and sheets. It writes DXF, not DWG. -It does not yet have overlines in paragraph text, ellipses, splines or points, tables, transparency set on one -entity, PDF underlays, or the other kinds of dimension. +It does not yet have overlines in paragraph text, ellipses, splines or points, tables, PDF underlays, +or the other kinds of dimension. `readDXF` reads an ASCII DXF into a model to inspect, which is not a drawing tsdraft can edit and write again. [Reading drawing files](docs/reading.md) has what it reads. @@ -434,6 +434,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version what `lint` refuses. - [Colors](docs/colors.md) covers an entity's own color by index or as a true color, ByBlock in a block, how each plots under a plot style table, and the color codes of paragraph text. +- [Transparency](docs/transparency.md) covers an entity's own transparency, ByBlock in a block, + and how it plots when the plot asks for it. - [Dimensions](docs/dimensions.md) covers dimension styles, linear and aligned dimensions, how a measurement is written, and what `lint` refuses. - [Xrefs](docs/xrefs.md) covers references to DWG files: the path, units, a diff --git a/docs/colors.md b/docs/colors.md index 6a6398e..b2daf2a 100644 --- a/docs/colors.md +++ b/docs/colors.md @@ -24,6 +24,7 @@ arrowheads included, and so does a leader. A wipeout's color is its frame's; it behind it in the paper's color. Colors are R2018 only. The builder and `lint` refuse a color but `"ByLayer"` in an R12 drawing. +An entity's transparency is on a page of its own, [Transparency](transparency.md). ## How a color plots diff --git a/docs/format.md b/docs/format.md index 268af20..de71bf7 100644 --- a/docs/format.md +++ b/docs/format.md @@ -39,6 +39,8 @@ only where it is `true`, so a drawing with neither has the JSON it had before th Every entity but a table, an insert, a dimension and a leader included, has a `color` where it has one of its own: an index from 1 to 255, `"ByBlock"`, or a true color `[red, green, blue]`. A drawing whose entities draw ByLayer has the JSON it had before colors existed. [Colors](colors.md) describes them. +Every entity but a table has a `transparency` where it has one of its own: a whole percent from 0 to +90, or `"ByBlock"`, as [Transparency](transparency.md) describes. A drawing lists its blocks in `blocks`, and leaves the field out when it has none. A block has a `name`, its `entities`, and where they differ from their defaults a `base` point and its diff --git a/docs/plotting.md b/docs/plotting.md index ed084c7..e2552b1 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -24,6 +24,9 @@ writeFileSync("A-101.pdf", toPDF(drawing, { layouts: ["A-101"], xrefs, deflate } Node's `zlib.deflateSync`. The library imports nothing, so without it the pages are written as they are, and the file is several times larger. It is called as the PDF is written, so it cannot be an asynchronous one, such as a browser's `CompressionStream`. +- `plotTransparency` draws each entity at its transparency, as CAD programs plot it when told to + plot transparency always. Without it every entity plots opaque, as they plot the page setups + tsdraft writes. [Transparency](transparency.md) says how. - `fonts` gives the TrueType file of each font the texts are set in, by its name in `FONTS`, as [Text](#text) says. The PDF embeds each, cut to the letters it uses. - `missing` is told, for each sheet that has any, its layout's name, the characters of its texts diff --git a/docs/reading.md b/docs/reading.md index 2d5b2cf..56cd9a3 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -246,8 +246,10 @@ order of `entities`. Each keeps the pen it sets for itself, each part left out when it is ByLayer: `color`, an index with 0 for ByBlock, and with a true color the index CAD programs match it to; `trueColor` as `0xRRGGBB`; `colorBook`, the `book` and the `name` of a color of a color book, whose true color -`trueColor` holds; `linetype`, `lineweight` in hundredths of a millimeter with -2 for ByBlock and --3 for the default, and `linetypeScale`. +`trueColor` holds; `alpha`, how opaque it is from 0 to 255 with 255 opaque, or `"ByBlock"`, whose +percent of transparency is `Math.round(100 - alpha / 2.55)`; `linetype`, `lineweight` in hundredths +of a millimeter with -2 for ByBlock and -3 for the default, and `linetypeScale`. A file may hold an +alpha no percent gives, which is read as it is, and below 25 gives a percent over 90. A text, an attribute and an attribute definition say where they are and how they are justified: `align` and `valign` as a `Text` has them, or `aligned`, `fit` or `middle`; `alignAt`, the point diff --git a/docs/transparency.md b/docs/transparency.md new file mode 100644 index 0000000..e1676c0 --- /dev/null +++ b/docs/transparency.md @@ -0,0 +1,73 @@ +# Transparency + +An entity is opaque unless it has a transparency of its own. `transparency` takes three kinds of +value: + +- A whole percent from 0 to 90, as CAD programs set it: 50 for half, not 0.5. 0 is opaque, and is + kept apart from ByLayer. +- `"ByLayer"`, the default, which is left out of the drawing. A layer has no transparency in + tsdraft, so an entity ByLayer is opaque. +- `"ByBlock"`, the transparency of the insert that places the entity's block. + +```ts +const d = createDrawing({ units: "ft" }); +d.layer("L-PLNT", { color: 3 }, () => { + // The tree's canopy, half transparent over the walk beneath it. + d.hatch( + [ + [0, 0], + [20, 0], + [20, 20], + [0, 20], + ], + { transparency: 50 }, + ); +}); +``` + +Every entity but a table takes a transparency, as it takes a color. A table's grid plots opaque in +CAD programs, and the builder and `lint` refuse a transparency of its own. A wipeout fades, its +white and its frame alike. Transparencies are R2018 only: the builder and `lint` refuse one but +`"ByLayer"` in an R12 drawing, and anything else under the rule `entity-transparency`. + +## ByBlock + +An entity of a block set `"ByBlock"` takes the transparency of the insert that places the block, +and through an insert ByBlock inside another block the outer insert's. An insert's own transparency +fades only what its block sets ByBlock, as its color colors only that. An entity ByBlock outside +any block is opaque. + +## A block a leader places + +CAD programs hold every entity directly in a block a leader places in place of its note +transparent ByBlock, whatever it set, and drop a percent of its own. So the builder and `lint` +refuse a percent there, 0 too, under `entity-transparency`, and the writers write each of its +entities and attribute definitions ByBlock. An entity left ByLayer in such a block then fades +with any insert of the block, at the insert's transparency. The leader draws its block opaque, +whatever its own transparency. A block inserted inside it keeps what it sets, and its color is +untouched. + +## How it plots + +CAD programs plot transparency only where the page setup or the plot asks for it, and the page +setups tsdraft writes do not, so `toPDF` and `toSVG` draw every entity opaque by default, as those +programs plot the file. `plotTransparency: true` draws each entity at its transparency, as they plot +it when told to plot transparency always: + +```ts +const pdf = toPDF(d.build(), { plotTransparency: true, deflate }); +const svg = toSVG(d.build(), { layout: "L-101", plotTransparency: true }); +``` + +Each entity is composed first and then faded, so where its parts overlap, a wide polyline's corners +or a dimension's arrowheads on its line, it is no darker. An arrowhead CAD programs draw from a +block, a dimension's architectural tick or oblique stroke and a leader's open or dot arrowhead, +plots opaque in a faded dimension or leader, as those programs plot it. `toSVG` puts each faded entity in a group +with an `opacity`, and `toPDF` makes it a transparency group. + +## In the file + +DXF group 440 holds a transparency, after the color's groups: `0x02000000` and the entity's opacity +from 0 to 255, `floor(255 * (100 - percent) / 100)`, or `0x01000000` for ByBlock, and nothing for +ByLayer. A dimension's picture holds every part transparent ByBlock, as CAD programs save one. A +drawing read back gives the opacity as `alpha`, as [Reading](reading.md) says. diff --git a/src/blocks.ts b/src/blocks.ts index f10d310..3f3b952 100644 --- a/src/blocks.ts +++ b/src/blocks.ts @@ -1,5 +1,6 @@ // Where an insert puts its block: the matrix that places the block's entities, the text each // attribute of an insert is, and a walk over everything a drawing draws through its inserts. +import { alphaOf, entityTransparencyProblem } from "./transparency.ts"; import type { AttributeDefinition, Block, @@ -739,6 +740,18 @@ function insertColor( return { layer }; } +/** + * The opacity an insert gives what its block sets ByBlock: its own, that of the insert that holds + * it when it is ByBlock, and opaque when it is ByLayer, since a layer has no transparency. + */ +function insertAlpha(insert: Insert, outer: number | undefined): number | undefined { + const own: unknown = insert.transparency; + if (own === "ByBlock") return outer; + return entityTransparencyProblem(own) === undefined && typeof own === "number" + ? alphaOf(own) + : undefined; +} + /** Where one entity is drawn. */ export interface Placement { /** The matrix from the entity's coordinates to the drawing's, or undefined in model space. */ @@ -760,6 +773,16 @@ export interface Placement { * layer's where the insert is ByLayer. Undefined in model space, where ByBlock draws as index 7. */ readonly byBlock?: BlockColor | undefined; + /** + * The opacity, from 0 to 255, an entity set `"ByBlock"` takes: that of the insert that holds it. + * Undefined in model space, where ByBlock draws opaque. + */ + readonly byBlockAlpha?: number | undefined; + /** + * True in a block a leader places, which holds every entity ByBlock whatever it sets, as the + * leading CAD app reads it. + */ + readonly byBlockHeld?: boolean; /** For the text of an insert's attribute, the attribute's tag. */ readonly attribute?: string; /** @@ -781,8 +804,10 @@ interface Entered { /** The block's base point. */ readonly base: Point | undefined; readonly layer: LayerRef; - /** The color what the block sets ByBlock takes. */ + /** The color what the block sets ByBlock takes, and its opacity. */ readonly byBlock: BlockColor | undefined; + readonly byBlockAlpha: number | undefined; + readonly byBlockHeld: boolean; readonly inside: Referenced | undefined; /** The blocks its inserts find theirs among. */ readonly inner: ReadonlyMap; @@ -833,6 +858,7 @@ export function eachDrawn( spend: (cost: number) => boolean = () => true, key: (name: string) => string = layerKey, holding?: (entity: Exclude, placement: Placement) => readonly Insert[], + heldByBlock?: (from: Referenced | undefined) => ReadonlySet, ): boolean { if (entity.kind !== "insert") { draw(entity, { @@ -853,6 +879,8 @@ export function eachDrawn( outer: Matrix | undefined, layer: LayerRef, byBlock: BlockColor | undefined, + byBlockAlpha: number | undefined, + byBlockHeld = false, ): boolean => { if (isFrozen(layer)) return true; const name = key(insert.block); @@ -875,6 +903,9 @@ export function eachDrawn( base: block?.base, layer, byBlock: insertColor(insert, layer, byBlock), + // An insert in a block a leader places is ByBlock, whatever it sets. + byBlockAlpha: byBlockHeld ? byBlockAlpha : insertAlpha(insert, byBlockAlpha), + byBlockHeld: block !== undefined && heldByBlock?.(from).has(name) === true, // What the insert holds names the layers, linetypes and text styles of this drawing. inside: referenced ?? from, inner: referenced ? referenced.blocks : within, @@ -883,7 +914,9 @@ export function eachDrawn( }); return true; }; - if (!enter(entity, blocks, undefined, undefined, { name: entity.layer }, undefined)) return false; + if (!enter(entity, blocks, undefined, undefined, { name: entity.layer }, undefined, undefined)) { + return false; + } while (stack.length > 0) { const at = stack.at(-1)!; const { inside } = at; @@ -892,7 +925,18 @@ export function eachDrawn( // One at a time, so two that place one block do not find it open. if (at.queued !== undefined && at.queued.next < at.queued.inserts.length) { const insert = at.queued.inserts[at.queued.next++]!; - if (!enter(insert, at.inner, inside, at.matrix, layerOf(insert.layer), at.byBlock)) { + if ( + !enter( + insert, + at.inner, + inside, + at.matrix, + layerOf(insert.layer), + at.byBlock, + at.byBlockAlpha, + at.byBlockHeld, + ) + ) { return false; } continue; @@ -908,13 +952,26 @@ export function eachDrawn( insertLayer: at.layer, from: inside, byBlock: at.byBlock, + byBlockAlpha: at.byBlockAlpha, + ...(at.byBlockHeld ? { byBlockHeld: true } : {}), }; draw(item, placement); if (inside !== undefined && holding !== undefined) { const inserts = holding(item, placement); at.queued = inserts.length > 0 ? { inserts, next: 0 } : undefined; } - } else if (!enter(item, at.inner, inside, at.matrix, layerOf(item.layer), at.byBlock)) { + } else if ( + !enter( + item, + at.inner, + inside, + at.matrix, + layerOf(item.layer), + at.byBlock, + at.byBlockAlpha, + at.byBlockHeld, + ) + ) { return false; } continue; @@ -940,6 +997,7 @@ export function eachDrawn( insertLayer: at.layer, from: inside, byBlock: at.byBlock, + byBlockAlpha: at.byBlockAlpha, attribute: definition.tag, made: placed.paragraph!.uneven, }); @@ -951,6 +1009,7 @@ export function eachDrawn( insertLayer: at.layer, from: inside, byBlock: at.byBlock, + byBlockAlpha: at.byBlockAlpha, attribute: definition.tag, }); continue; diff --git a/src/drawing.ts b/src/drawing.ts index 2c2bcec..2bcb696 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -1,4 +1,5 @@ import { entityColorProblem } from "./colors.ts"; +import { entityTransparencyProblem } from "./transparency.ts"; import type { ParagraphColumns } from "./paragraphs.ts"; import { definitionHandle, @@ -113,6 +114,8 @@ import { leaderStyleTwinProblem, standardTableStyleProblem, TABLE_COLOR, + TABLE_TRANSPARENCY, + LEADER_BLOCK_TRANSPARENCY, TABLE_IN_BLOCK, tableColumnsProblem, tableTextsProblem, @@ -478,6 +481,9 @@ export type Rgb = readonly [red: number, green: number, blue: number]; */ export type EntityColor = number | "ByLayer" | "ByBlock" | Rgb; +/** An entity's own transparency: a whole percent from 0 to 90, `"ByLayer"` or `"ByBlock"`. */ +export type EntityTransparency = number | "ByLayer" | "ByBlock"; + interface Placed { /** * A name for this entity that stays the same when the drawing's code changes around it: 1 to @@ -492,6 +498,8 @@ interface Placed { readonly layer: string; /** Its own color. Defaults to `"ByLayer"`. R2018 only. */ readonly color?: EntityColor; + /** Its own transparency, in percent. Defaults to `"ByLayer"`. R2018 only. */ + readonly transparency?: EntityTransparency; } interface EntityBase extends Placed { @@ -1797,6 +1805,8 @@ export interface EntityOptions< readonly id?: EntityId; /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ readonly color?: V extends "R12" ? "ByLayer" | R12EntityColor : EntityColorOf; + /** Its own transparency: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`. R2018 only. */ + readonly transparency?: V extends "R12" ? "ByLayer" : EntityTransparency; /** * A linetype of the drawing, `"Continuous"`, `"ByBlock"` or `"ByLayer"`. R2018 only. Under a * standard, a linetype of the standard by name, which the drawing then has. @@ -2393,6 +2403,8 @@ interface InsertFields; /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ readonly color?: EntityColorOf; + /** Its own transparency: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`. R2018 only. */ + readonly transparency?: EntityTransparency; /** Degrees counterclockwise, about the insert's point. Defaults to 0. */ readonly rotation?: number; /** A value for each attribute to set, by its tag. The others have their default values. */ @@ -2546,6 +2558,8 @@ interface DimensionOptions< readonly id?: EntityId; /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ readonly color?: EntityColorOf; + /** Its own transparency: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`. R2018 only. */ + readonly transparency?: EntityTransparency; readonly view?: ViewWithoutStandard; } @@ -2660,6 +2674,8 @@ export interface StandardAlignedDimensionOptions< readonly id?: EntityId; /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ readonly color?: EntityColorOf; + /** Its own transparency: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`. R2018 only. */ + readonly transparency?: EntityTransparency; } /** The options of `radiusDimension()` and `diameterDimension()` under the standard `Z`. */ @@ -2826,6 +2842,8 @@ export interface LeaderOptions< readonly id?: EntityId; /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ readonly color?: EntityColorOf; + /** Its own transparency: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`. R2018 only. */ + readonly transparency?: EntityTransparency; readonly view?: ViewWithoutStandard; readonly role?: RoleWithoutStandard; } @@ -2868,15 +2886,19 @@ export interface StandardLeaderOptions< readonly id?: EntityId; /** Its own color: an index from 1 to 255, `"ByLayer"`, the default, `"ByBlock"`, or a true color. R2018 only. */ readonly color?: EntityColorOf; + /** Its own transparency: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`. R2018 only. */ + readonly transparency?: EntityTransparency; readonly textStyle?: LeaderRoleAndText; readonly textHeight?: LeaderRoleAndText; } /** What `layout()` sets on a layout. */ /** The options of `table()`: the table, but for its kind and its layer, which is the current one. */ -export type TableOptions = Omit & { +export type TableOptions = Omit & { /** A table has no color of its own: its style and its cells give its colors. */ readonly color?: "ByLayer"; + /** A table has no transparency of its own: CAD programs plot its grid opaque. */ + readonly transparency?: "ByLayer"; }; export interface LayoutOptions

{ @@ -3227,6 +3249,8 @@ export class DrawingBuilder< readonly #arrowheadBlocks = new Set(); /** Keyed by `layerKey`: leader style names are compared as dimension style names are. */ readonly #leaderStyles = new Map(); + /** Whether each block a leader places holds a percent of its own, looked through once. */ + readonly #leaderPlaced = new Map(); readonly #leaderStylesAudited = new Map(); readonly #tableStyles = new Map(); readonly #tableStylesAudited = new Map(); @@ -5611,6 +5635,8 @@ export class DrawingBuilder< if (this.#open) refuse("table", TABLE_IN_BLOCK); const o = (typeof given === "object" && given !== null ? given : {}) as Record; if (o.color !== undefined && o.color !== "ByLayer") refuse("entity-color", TABLE_COLOR); + if (o.transparency !== undefined && o.transparency !== "ByLayer") + refuse("entity-transparency", TABLE_TRANSPARENCY); const named = o.style; const nameProblem = tableStyleNameProblem(named); if (nameProblem) refuse("undefined-table-style", nameProblem); @@ -5721,6 +5747,13 @@ export class DrawingBuilder< } const problem = leaderBlockContentProblem({ ...o, attributes: content.attributes }); if (problem) refuse("leader", problem); + // Each block is looked through once, however many leaders place it. + let percent = this.#leaderPlaced.get(placed!); + if (percent === undefined) { + percent = placed!.entities.some((e) => typeof e.transparency === "number"); + this.#leaderPlaced.set(placed!, percent); + } + if (percent) refuse("entity-transparency", LEADER_BLOCK_TRANSPARENCY); // Each value names an attribute of the block, as an insert's does. const tags = new Set((placed!.attributes ?? []).map((d) => d.tag)); for (const tag of Object.keys((content.attributes as object | undefined) ?? {})) { @@ -6729,7 +6762,8 @@ export class DrawingBuilder< const named = id === undefined ? {} : { id: id as string }; // Before `make`, which takes a dimension's handles. const color = this.#color(o); - const made = { ...make(), ...named, ...this.#style(o), ...color } as Entity; + const transparency = this.#transparency(o); + const made = { ...make(), ...named, ...this.#style(o), ...color, ...transparency } as Entity; (this.#open ?? this.#sheet ?? { entities: this.#entities }).entities.push(made); if (this.#open && this.#drawsRoles(made, o)) this.#open.roles = true; if (key !== undefined) { @@ -6824,6 +6858,17 @@ export class DrawingBuilder< }; } + /** The transparency an entity is stored with: none for ByLayer. */ + #transparency(options: object): { readonly transparency?: EntityTransparency } { + const transparency: unknown = (options as { readonly transparency?: unknown }).transparency; + if (transparency === undefined) return {}; + const problem = entityTransparencyProblem(transparency); + if (problem) refuse("entity-transparency", problem); + if (transparency === "ByLayer") return {}; + if (this.dxf === "R12") refuse("entity-transparency", R12_ONLY.entityTransparency); + return { transparency: transparency as EntityTransparency }; + } + /** The linetype and lineweight an entity is stored with. */ #style(options: EntityOptions): EntityStyle { const style: { -readonly [K in keyof EntityStyle]: EntityStyle[K] } = {}; @@ -7173,9 +7218,21 @@ function titleBlockValues( } /** The id and the color among the options of a dimension, which have no linetype or lineweight to take. */ -function idOf(options: unknown): { readonly id?: unknown; readonly color?: unknown } { - const { id, color } = (options ?? {}) as { id?: unknown; color?: unknown }; - return { ...(id === undefined ? {} : { id }), ...(color === undefined ? {} : { color }) }; +function idOf(options: unknown): { + readonly id?: unknown; + readonly color?: unknown; + readonly transparency?: unknown; +} { + const { id, color, transparency } = (options ?? {}) as { + id?: unknown; + color?: unknown; + transparency?: unknown; + }; + return { + ...(id === undefined ? {} : { id }), + ...(color === undefined ? {} : { color }), + ...(transparency === undefined ? {} : { transparency }), + }; } /** diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index c61b7fc..f2ca2f9 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -1,4 +1,5 @@ import { heldColor, matchedIndex, storedColor } from "./colors.ts"; +import { storedTransparency } from "./transparency.ts"; import { attributeTextStart, definitionHandle, @@ -46,6 +47,7 @@ import type { Drawing, Entity, EntityColor, + EntityTransparency, Image, Insert, Layout, @@ -172,6 +174,8 @@ import { verticalAttachmentCode, STANDARD_LEADER_STYLE_SIZES, validLeaderStyleHandle, + heldByBlock, + leaderPlacesBlock, } from "./leaders.ts"; import { entityLinetype, layerLinetype, lineweightCode, patternLength } from "./linetypes.ts"; import { idKey, isStandardTextStyle, shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; @@ -813,20 +817,24 @@ export function toDXFR2018( ...(index === 0 ? {} : { contents: () => writeSheet(sheet, index + 1) }), }); }); + const placedByLeader = leaderPlacesBlock(drawing); for (const block of blocks) { const handles = blockHandles(block.name); + // A block a leader places holds all it draws ByBlock, as the leading CAD app reads it. + const byBlock = placedByLeader(block.name); writeBlock(g, handles.begin, handles.end, block.name, handles.record, { paper: false, base: block.base, hasAttributes: (block.attributes ?? []).length > 0, contents: () => { - writeEntities(block.entities, handles.record); + writeEntities(byBlock ? heldByBlock(block.entities) : block.entities, handles.record); for (const definition of block.attributes ?? []) { g(0, "ATTDEF"); g(5, definitionHandle(block.name, definition.tag)); g(330, handles.record); g(100, "AcDbEntity"); g(8, definition.layer); + if (byBlock) writeColor(g, undefined, "ByBlock"); g(100, "AcDbText"); if (definition.kind === "paragraph") { const prompt = definition.prompt ?? definition.tag; @@ -1259,7 +1267,7 @@ function writeInsert( g(100, "AcDbEntity"); if (paper) g(67, 1); g(8, e.layer); - writeColor(g, e.color); + writeColor(g, e.color, e.transparency); g(100, "AcDbBlockReference"); if (hasAttributes) g(66, 1); // attributes follow g(2, e.block); @@ -1467,12 +1475,22 @@ function writeSpline(g: Group, e: Spline, begin: () => void): void { /** The vertical justification of the text a paragraph attribute would be as a line. */ const TEXT_VALIGN_OF = { top: "top", middle: "middle", bottom: "bottom" } as const; -/** An entity's own color, after its linetype: group 62, and 420 for a true color. */ -function writeColor(g: Group, color: EntityColor | undefined): void { +/** + * An entity's own color, after its linetype: group 62, and 420 for a true color; and its + * transparency, group 440, which follows them. + */ +function writeColor( + g: Group, + color: EntityColor | undefined, + transparency: EntityTransparency | undefined, +): void { const stored = storedColor(color); - if (stored === undefined) return; - g(62, stored.index); - if (stored.rgb !== undefined) g(420, stored.rgb); + if (stored !== undefined) { + g(62, stored.index); + if (stored.rgb !== undefined) g(420, stored.rgb); + } + const value = storedTransparency(transparency); + if (value !== undefined) g(440, value); } /** @@ -1497,7 +1515,7 @@ function writeEntity( g(8, e.layer); const linetype = entityLinetype(e); if (linetype !== undefined) g(6, linetype); - writeColor(g, e.color); + writeColor(g, e.color, e.transparency); if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { g(370, lineweightCode(e.lineweight)); } @@ -1837,7 +1855,7 @@ function writeDimension( g(100, "AcDbEntity"); if (paper) g(67, 1); g(8, e.layer); - writeColor(g, e.color); + writeColor(g, e.color, e.transparency); g(100, "AcDbDimension"); if (block !== undefined) g(2, block); point(g, 10, ...picture.definitionPoint); @@ -1989,6 +2007,7 @@ function writePicture(g: Group, { name, picture, handles, layer, textStyle, mask g(100, "AcDbEntity"); g(8, layer); g(62, 0); // by block + g(440, 0x01000000); // transparent by block, as the leading CAD app saves a picture if (lineweight !== undefined) g(370, lineweight); g(100, subclass); }; @@ -2484,7 +2503,7 @@ function writeImage(g: Group, e: Image, place: ImagePlace): void { g(8, e.layer); const linetype = entityLinetype(e); if (linetype !== undefined) g(6, linetype); - writeColor(g, e.color); + writeColor(g, e.color, e.transparency); if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { g(370, lineweightCode(e.lineweight)); } @@ -2740,7 +2759,7 @@ function writeLeader( g(100, "AcDbEntity"); if (where.paper) g(67, 1); g(8, e.layer); - writeColor(g, e.color); + writeColor(g, e.color, e.transparency); g(100, "AcDbMLeader"); g(270, 2); // version g(300, "CONTEXT_DATA{"); diff --git a/src/index.ts b/src/index.ts index 55eb612..cc49d41 100644 --- a/src/index.ts +++ b/src/index.ts @@ -148,6 +148,7 @@ export { type Rgb, type Polyline, type EntityColor, + type EntityTransparency, type PolylineOptions, type RadiusDimension, type RadiusDimensionOptions, @@ -177,6 +178,7 @@ export { type Zone, } from "./drawing.ts"; export { heldColor, storedColor } from "./colors.ts"; +export { readAlpha, storedTransparency } from "./transparency.ts"; export { toDXF, type DxfOptions } from "./dxf.ts"; export { parsePatterns, PATTERN_FILE_LENGTH } from "./patterns.ts"; export { fifteenDigits } from "./format.ts"; @@ -262,11 +264,13 @@ export { layoutHandles, viewportView, type LayoutHandles, type ViewportView } fr export { attachmentCode, findLeaderStyle, + heldByBlock, leaderArrowheadHandles, leaderAttachment, leaderCount, leaderOwnFlags, leaderPicture, + leaderPlacesBlock, leaderSide, leaderSizes, leaderStyleDictionaryHandle, diff --git a/src/leaders.ts b/src/leaders.ts index 9f78e74..2035ad7 100644 --- a/src/leaders.ts +++ b/src/leaders.ts @@ -786,6 +786,63 @@ export function leaderBlock( return leader.block ?? (leader.text === undefined ? style?.block : undefined); } +/** The longest name a block may have: no longer name finds one. */ +const BLOCK_NAME_MOST = 255; + +/** + * Whether a block, by its name, is placed by a leader of the drawing in place of its note. As the + * leading CAD app reads a file, it makes every entity directly in such a block transparent + * ByBlock, whatever it held, and draws the leader's block opaque. A leader is refused inside a + * block, so this reads model space and the layouts, each list up to its first empty slot, and + * keys each name once. + */ +export function leaderPlacesBlock(drawing: unknown): (block: string) => boolean { + const placed = leaderBlockKeys(drawing); + return (block) => + placed.size > 0 && block.length <= BLOCK_NAME_MOST && placed.has(layerKey(block)); +} + +/** The `layerKey` of each block a leader of the drawing places, as `leaderPlacesBlock` finds them. */ +export function leaderBlockKeys(drawing: unknown): ReadonlySet { + const d = drawing as { entities?: unknown; layouts?: unknown; leaderStyles?: unknown } | null; + const each = (list: unknown, at: (item: Record) => void): void => { + if (!Array.isArray(list)) return; + for (let i = 0; i < list.length; i++) { + const item: unknown = list[i]; + if (item === undefined) break; + if (typeof item === "object" && item !== null) at(item as Record); + } + }; + const named = (name: unknown): string | undefined => + typeof name === "string" && name.length <= BLOCK_NAME_MOST ? layerKey(name) : undefined; + const styles = new Map>(); + each(d?.leaderStyles, (style) => { + const key = named(style.name); + if (key !== undefined && !styles.has(key)) styles.set(key, style); + }); + const placed = new Set(); + // A list many layouts share is read once. + const seen = new Set(); + const read = (entities: unknown): void => { + if (seen.has(entities)) return; + seen.add(entities); + each(entities, (e) => { + if (e.kind !== "leader") return; + const style = styles.get(named(e.style) ?? ""); + const key = named(leaderBlock(e as Pick, style)); + if (key !== undefined) placed.add(key); + }); + }; + read(d?.entities); + each(d?.layouts, (layout) => read(layout.entities)); + return placed; +} + +/** The entities of a block a leader places, as the leading CAD app holds them: all ByBlock. */ +export function heldByBlock(entities: readonly Entity[]): readonly Entity[] { + return entities.map((e) => (e.kind === "table" ? e : { ...e, transparency: "ByBlock" })); +} + /** The note of a leader as the paragraph it is laid out as, before it is placed. */ export function leaderNote( leader: Pick, diff --git a/src/lint.ts b/src/lint.ts index d9e7bbd..7d82e05 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -1,4 +1,5 @@ import { entityColorProblem } from "./colors.ts"; +import { entityTransparencyProblem } from "./transparency.ts"; import { definitionHandle, insertAttributeHandle, @@ -68,6 +69,7 @@ import { leaderRepeats, leaderStyleDictionaryHandle, validLeaderStyleHandle, + leaderPlacesBlock, } from "./leaders.ts"; import { paperInfo } from "./papers.ts"; import { isUnits } from "./units.ts"; @@ -146,6 +148,8 @@ import { isStandardTableStyle, standardTableStyleProblem, TABLE_COLOR, + TABLE_TRANSPARENCY, + LEADER_BLOCK_TRANSPARENCY, TABLE_IN_BLOCK, tableColumnsProblem, tableTextsProblem, @@ -253,6 +257,7 @@ export type LintRule = | "undefined-linetype" | "lineweight" | "entity-color" + | "entity-transparency" | "layer-state" | "geometry" | "text" @@ -814,6 +819,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } const r12 = version === "R12"; + const leaderPlaces = leaderPlacesBlock(drawing); const scale = drawing.linetypeScale; if (scale !== undefined && (r12 ? scale !== 1 : linetypeScaleProblem(scale))) { const problem = r12 ? R12_ONLY.linetypes : linetypeScaleProblem(scale); @@ -2108,6 +2114,9 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) ? `${sheet.at}.entities` : "entities"; const inBlock = block ? { block: block.name } : sheet ? { layout: sheet.name } : {}; + // A block a leader places holds every entity ByBlock in CAD programs, which drop a percent. + const placedByLeader = + block !== undefined && typeof block.name === "string" && leaderPlaces(block.name); const space = block ? `block ${shown(block.name)}` : sheet @@ -2206,6 +2215,19 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) (entity.kind === "table" && color !== "ByLayer" ? TABLE_COLOR : undefined); if (problem) add("entity-color", "error", problem); } + const transparency: unknown = entity.transparency; + if (transparency !== undefined) { + const problem = + entityTransparencyProblem(transparency) ?? + (r12 && transparency !== "ByLayer" ? R12_ONLY.entityTransparency : undefined) ?? + (entity.kind === "table" && transparency !== "ByLayer" + ? TABLE_TRANSPARENCY + : undefined) ?? + (placedByLeader && typeof transparency === "number" + ? LEADER_BLOCK_TRANSPARENCY + : undefined); + if (problem) add("entity-transparency", "error", problem); + } if ( r12 && entity.kind === "polyline" && diff --git a/src/pdf.ts b/src/pdf.ts index 08bbffa..36d5e12 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -23,6 +23,11 @@ export interface PdfOptions { * drawing given plots nothing. */ readonly xrefs?: XrefDrawings; + /** + * Plots each entity's transparency, as CAD programs plot it when told to plot transparency + * always. Left out, every entity plots opaque, as they plot the page setups tsdraft writes. + */ + readonly plotTransparency?: boolean; /** * Compresses each page's content: a function that gives the zlib form of its bytes, such as * Node's `zlib.deflateSync`. Without it the content is written as it is. @@ -126,6 +131,7 @@ export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions ...(xrefs ? { xrefs } : {}), ...(own ? { images: own } : {}), ...(options.shapes ? { shapes: options.shapes } : {}), + ...(options.plotTransparency === true ? { plotTransparency: true } : {}), }), ); } @@ -302,6 +308,7 @@ const ATTRIBUTES = new Set([ "xml:space", "font-weight", "href", + "opacity", "preserveAspectRatio", "clip-rule", "fill-rule", @@ -756,6 +763,8 @@ interface Inherited { readonly layer: string | undefined; /** True when the group around it opened a `q` that its end closes. */ readonly saved: boolean; + /** For a group with an opacity: the content around it, and the opacity it is painted at. */ + readonly faded?: { readonly outer: Content; readonly opacity: string }; } /** A color as `#rrggbb`, as three parts from 0 to 1, or undefined for `none`. */ @@ -1203,7 +1212,51 @@ class PdfWriter { /** Adds a page drawn from a picture `toSVG` made of a layout. */ page(svg: string): void { - const content = new Content(); + let content = new Content(); + /** The forms of the groups with an opacity, and the graphics states that paint them. */ + const forms = new Map(); + const opacities = new Map(); + let formBytes = 0; + /** + * The box, in points, of what each transparency group open has painted, the innermost last: + * its form's `/BBox`, so a reader composes no more of the page than the group paints. + */ + const boxes: [number, number, number, number][] = []; + /** The box of each clip open, in points, each within the one before: nothing paints past it. */ + const clipBoxes: (readonly [number, number, number, number])[] = []; + const grow = (x: number, y: number, pad = 0): void => { + const box = boxes.at(-1); + if (box === undefined) return; + const [cx0, cy0, cx1, cy1] = clipBoxes.at(-1) ?? [-Infinity, -Infinity, Infinity, Infinity]; + const within = (v: number, low: number, high: number) => Math.min(Math.max(v, low), high); + box[0] = Math.min(box[0], within(x - pad, cx0, cx1)); + box[1] = Math.min(box[1], within(y - pad, cy0, cy1)); + box[2] = Math.max(box[2], within(x + pad, cx0, cx1)); + box[3] = Math.max(box[3], within(y + pad, cy0, cy1)); + }; + /** Opens a clip whose outline passes through these points, or within them for a curve's. */ + const openClip = (points: readonly (readonly [number, number])[]): void => { + const box = [Infinity, Infinity, -Infinity, -Infinity]; + for (const [x, y] of points) { + box[0] = Math.min(box[0]!, x); + box[1] = Math.min(box[1]!, y); + box[2] = Math.max(box[2]!, x); + box[3] = Math.max(box[3]!, y); + } + const outer = clipBoxes.at(-1) ?? [-Infinity, -Infinity, Infinity, Infinity]; + // A side that is NaN leaves the clip as wide as the one outside, and a point past each side + // holds what the outline, written to three decimals, lets through. + const [x0, y0, x1, y1] = box.map((v, i) => + Number.isNaN(v) ? outer[i]! : v + (i < 2 ? -1 : 1), + ); + clipBoxes.push([ + Math.max(x0!, outer[0]), + Math.max(y0!, outer[1]), + Math.min(x1!, outer[2]), + Math.min(y1!, outer[3]), + ]); + }; + const resourcesObject = this.reserve(); const fonts = new Map(); const missing = new Set(); const marks = new Map(); @@ -1276,9 +1329,14 @@ class PdfWriter { pen.width = width; } if (pieces.length === 0) return; + // Half the pen and a point more, for its joins and caps. + const pad = state.stroke === undefined ? 1 : state.width / 2 + 1; // Each piece is a line of its own, so no string grows with the path. - const p = (point: readonly [number, number]) => - apply(m, point[0], point[1]).map(num).join(" "); + const p = (point: readonly [number, number]) => { + const [x, y] = apply(m, point[0], point[1]); + grow(x, y, pad); + return [x, y].map(num).join(" "); + }; for (const piece of pieces) { if (piece.kind === "move") content.add(`${p(piece.to)} m`); else if (piece.kind === "line") content.add(`${p(piece.to)} l`); @@ -1343,6 +1401,24 @@ class PdfWriter { where(tag), ); if (set) { + // The box of a text, in the coordinates it is set in: the length it is set at, with + // the font's box around every glyph, stretched as its letters are, past each end, and + // that box above and below its baseline, which is Y down. + const { size, length, stretch, ink } = set; + const [left, right] = [ + stretch * size * Math.min(ink[0], 0), + length + stretch * size * Math.max(ink[2], 0), + ]; + const [top, bottom] = [-size * Math.max(ink[3], 0), -size * Math.min(ink[1], 0)]; + for (const [cx, cy] of [ + [left, top], + [right, top], + [left, bottom], + [right, bottom], + ] as const) { + const [x, y] = apply(text.inherited.matrix, cx, cy); + grow(x, y, 1); + } mark(text.inherited.layer); if (set.fill !== pen.fill) { content.add(`${set.fill} rg`); @@ -1370,10 +1446,56 @@ class PdfWriter { else if (tag === "g" || tag === "svg") { names.pop(); ended = names.length === 0; - if (stack.pop()?.saved) { + const group = stack.pop(); + if (group?.saved) { close(); content.add("Q"); pen = pens.pop() ?? {}; + clipBoxes.pop(); + } + if (group?.faded) { + // A group with an opacity is a transparency group: its content is drawn whole, then + // painted at its opacity, so where its parts overlap it is no darker. + close(); + const raw = content.bytes(); + formBytes += raw.length; + // The page's limit holds its forms and its content together, as each form is made. + if (formBytes + group.faded.outer.length + group.faded.outer.pending > MAX_PAGE) { + throw new RangeError( + `The page of picture ${page} would be longer than svgToPDF writes, ${MAX_PAGE} bytes`, + ); + } + content = group.faded.outer; + const key = `Fm${forms.size + 1}`; + const object = this.reserve(); + forms.set(key, object); + const stream = this.deflate ? this.deflate(raw) : raw; + // What it painted, cut to the page: an empty box for a group that painted nothing. + const [w, h] = paper?.size ?? [0, 0]; + const painted = boxes.pop()!; + const box = [ + Math.max(painted[0], 0), + Math.max(painted[1], 0), + Math.min(painted[2], w), + Math.min(painted[3], h), + ]; + const bbox = box[0]! < box[2]! && box[1]! < box[3]! ? box : [0, 0, 0, 0]; + // A group inside another paints inside its box too. + if (bbox[2]! > bbox[0]!) { + grow(bbox[0]!, bbox[1]!); + grow(bbox[2]!, bbox[3]!); + } + this.object( + object, + `<< /Type /XObject /Subtype /Form /BBox [${bbox.map(num).join(" ")}] /Group << /S /Transparency >> /Resources ${resourcesObject} 0 R /Length ${stream.length}${this.deflate ? " /Filter /FlateDecode" : ""} >>`, + stream, + ); + let state = opacities.get(group.faded.opacity); + if (state === undefined) { + opacities.set(group.faded.opacity, (state = `Gs${opacities.size + 1}`)); + } + content.add(`q\n/${state} gs\n/${key} Do\nQ`); + pen = pens.pop() ?? {}; } } continue; @@ -1385,6 +1507,10 @@ class PdfWriter { } element[name!] = unescape(value!, where(tag)); } + // Only a group is drawn at an opacity: `toSVG` puts a faded entity in one. + if (element.opacity !== undefined && tag !== "g") { + throw refuse(`the opacity of <${tag}>`, where(tag)); + } const number = (name: string): number => { const value = Number(element[name]); if (element[name] === undefined || !Number.isFinite(value)) { @@ -1571,6 +1697,10 @@ class PdfWriter { if (selfClosing) continue; let saved = false; const clip = element["clip-path"]; + // `toSVG` fades an entity in a group of its own, which is never a clip's. + if (clip !== undefined && element.opacity !== undefined) { + throw refuse("a group with both a clip and an opacity", where(tag)); + } if (clip !== undefined) { const id = /^url\(#([^)]+)\)$/.exec(clip)?.[1]; const rect = id === undefined ? undefined : clips.get(id); @@ -1581,8 +1711,12 @@ class PdfWriter { if ("pieces" in rect) { // An image's clip: its outline, or the image's with the hole inside it. content.add("q"); - const p = (point: readonly [number, number]) => - apply(matrix, point[0], point[1]).map(num).join(" "); + const outline: (readonly [number, number])[] = []; + const p = (point: readonly [number, number]) => { + const placed = apply(matrix, point[0], point[1]); + outline.push(placed); + return placed.map(num).join(" "); + }; for (const piece of rect.pieces) { if (piece.kind === "move") content.add(`${p(piece.to)} m`); else if (piece.kind === "line") content.add(`${p(piece.to)} l`); @@ -1591,19 +1725,39 @@ class PdfWriter { else content.add("h"); } content.add(rect.evenOdd ? "W* n" : "W n"); + openClip(outline); } else { - const corners = [ + const placed = [ [rect.x, rect.y], [rect.x + rect.width, rect.y], [rect.x + rect.width, rect.y + rect.height], [rect.x, rect.y + rect.height], - ].map(([cx, cy]) => apply(matrix, cx!, cy!).map(num).join(" ")); + ].map(([cx, cy]) => apply(matrix, cx!, cy!)); + openClip(placed); + const corners = placed.map((corner) => corner.map(num).join(" ")); content.add( `q\n${corners[0]} m\n${corners[1]} l\n${corners[2]} l\n${corners[3]} l\nh W n`, ); } saved = true; } + const opacity = element.opacity; + if (opacity !== undefined) { + const value = Number(opacity); + if (!(value >= 0 && value <= 1) || !/^(?:0|1|0?\.\d{1,5})$/.test(opacity)) { + throw refuse(`the opacity ${JSON.stringify(opacity)}`, where(tag)); + } + close(); + pens.push(pen); + // A form sets its own pen: some readers carry no width, cap or join into one. + pen = {}; + stack.push({ ...inherited, saved, faded: { outer: content, opacity } }); + content = new Content(); + content.add("1 J\n1 j"); + boxes.push([Infinity, Infinity, -Infinity, -Infinity]); + names.push("g"); + continue; + } stack.push({ ...inherited, saved }); names.push("g"); continue; @@ -1624,7 +1778,17 @@ class PdfWriter { mark(inherited.layer); images.add(key); // The picture's image holds its top row at y 0, and a PDF's at y 1. - const m = compose(matrix, [1, 0, 0, -1, 0, 1]).map(num).join(" "); + const placed = compose(matrix, [1, 0, 0, -1, 0, 1]); + for (const [cx, cy] of [ + [0, 0], + [1, 0], + [0, 1], + [1, 1], + ] as const) { + const [x, y] = apply(placed, cx, cy); + grow(x, y, 1); + } + const m = placed.map(num).join(" "); content.add(`q\n${m} cm\n/${key} Do\nQ`); continue; } @@ -1656,8 +1820,11 @@ class PdfWriter { } mark(inherited.layer); content.add("q"); - const p = (point: readonly [number, number]) => - apply(inherited.matrix, point[0], point[1]).map(num).join(" "); + const p = (point: readonly [number, number]) => { + const [x, y] = apply(inherited.matrix, point[0], point[1]); + grow(x, y, 1); + return [x, y].map(num).join(" "); + }; for (const piece of pathPieces(element.d ?? "", where(tag), stretchOf(inherited.matrix))) { if (piece.kind === "move") content.add(`${p(piece.to)} m`); else if (piece.kind === "line") content.add(`${p(piece.to)} l`); @@ -1744,7 +1911,7 @@ class PdfWriter { throw refuse("a picture that ends before its last element closes", `picture ${page}`); } close(); - if (content.length + content.pending > MAX_PAGE) { + if (content.length + content.pending + formBytes > MAX_PAGE) { throw new RangeError( `The page of picture ${page} would be longer than svgToPDF writes, ${MAX_PAGE} bytes`, ); @@ -1762,19 +1929,30 @@ class PdfWriter { ([face, key]) => `/${key} ${"codes" in face ? face.object : this.faceObject(face)} 0 R`, ); const layerList = [...marks].map(([layer, key]) => `/${key} ${this.layers.get(layer)} 0 R`); - const imageList = [...images].map((key) => `/${key} ${this.images.get(key)!.object} 0 R`); + const imageList = [ + ...[...images].map((key) => `/${key} ${this.images.get(key)!.object} 0 R`), + ...[...forms].map(([key, object]) => `/${key} ${object} 0 R`), + ]; const shadingList = [...shadings].map(([key, object]) => `/${key} ${object} 0 R`); + const stateList = [...opacities].map(([opacity, key]) => { + const object = this.reserve(); + this.object(object, `<< /Type /ExtGState /CA ${opacity} /ca ${opacity} >>`); + return `/${key} ${object} 0 R`; + }); const resources = [ fontList.length > 0 ? `/Font << ${fontList.join(" ")} >>` : "", layerList.length > 0 ? `/Properties << ${layerList.join(" ")} >>` : "", imageList.length > 0 ? `/XObject << ${imageList.join(" ")} >>` : "", shadingList.length > 0 ? `/Shading << ${shadingList.join(" ")} >>` : "", + stateList.length > 0 ? `/ExtGState << ${stateList.join(" ")} >>` : "", ] .filter(Boolean) .join(" "); + // One dictionary of resources, which the page and each of its forms name. + this.object(resourcesObject, `<< ${resources} >>`); this.object( pageObject, - `<< /Type /Page /Parent ${this.tree} 0 R /MediaBox [0 0 ${num(paper.size[0])} ${num(paper.size[1])}]${paper.rotate ? " /Rotate 270" : ""} /Resources << ${resources} >> /Contents ${contentObject} 0 R >>`, + `<< /Type /Page /Parent ${this.tree} 0 R /MediaBox [0 0 ${num(paper.size[0])} ${num(paper.size[1])}]${paper.rotate ? " /Rotate 270" : ""} /Resources ${resourcesObject} 0 R /Contents ${contentObject} 0 R >>`, ); this.pages.push({ object: pageObject, name: paper.layout }); if (missing.size > 0) this.missing?.(paper.layout, [...missing].join(""), page - 1); @@ -1782,7 +1960,8 @@ class PdfWriter { /** * The operators that set a text: its face and size, its place and turn, and the stretch that - * holds it to its length. Undefined for a text that shows nothing. + * holds it to its length, and the size, length, stretch and font box it is set with. + * Undefined for a text that shows nothing. */ private text( element: Record, @@ -1791,7 +1970,16 @@ class PdfWriter { fonts: Map, missing: Set, where: string, - ): { fill: string; operators: readonly string[] } | undefined { + ): + | { + fill: string; + operators: readonly string[]; + size: number; + length: number; + stretch: number; + ink: readonly [number, number, number, number]; + } + | undefined { const fill = colorOf(inherited.fill, where); if (fill === undefined) return undefined; const font = element["data-font"]; @@ -1869,7 +2057,19 @@ class PdfWriter { ...shown, "ET", ]; - return { fill, operators }; + // The box around every glyph of the font, as a share of the size. + const [x0, y0, x1, y1] = embedded + ? embedded.font.box.map((value) => value / embedded.font.unitsPerEm) + : face.box.split(" ").map((value) => Number(value) / 1000); + const ink = [x0!, y0!, x1!, y1!] as const; + return { + fill, + operators, + size, + length: (natural * stretch) / 100, + stretch: stretch / 100, + ink, + }; } /** Writes the fonts, the layers, the bookmarks, the page tree and the catalog. */ diff --git a/src/read/check.ts b/src/read/check.ts index e702d30..80f7f19 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -11,6 +11,8 @@ type Type = | "boolean" | "point" | "count" + /** An entity's opacity: a whole number from 0 to 255, or `"ByBlock"`. */ + | "alpha" | "entity" | { readonly fields: Fields } | { readonly list: Type } @@ -88,6 +90,7 @@ const BASE = { "color?": "number", "trueColor?": "number", "colorBook?": { fields: { book: "string", name: "string" } }, + "alpha?": "alpha", "linetype?": "string", "lineweight?": "number", "linetypeScale?": "number", @@ -740,6 +743,11 @@ export function checkDrawingRead(value: unknown): string[] { say(at, "must be a whole number, 0 or more"); } return; + case "alpha": + if (v !== "ByBlock" && (!Number.isInteger(v) || (v as number) < 0 || (v as number) > 255)) { + say(at, 'must be a whole number from 0 to 255, or "ByBlock"'); + } + return; case "point": { const xy = plainList(v); if ( diff --git a/src/read/entities.ts b/src/read/entities.ts index ac8677c..6b04e2a 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -3,6 +3,7 @@ import type { ParagraphColumns } from "../paragraphs.ts"; import type { Point } from "../drawing.ts"; import { textOnce, textTwice } from "./groups.ts"; +import { readAlpha } from "../transparency.ts"; import { wholeImageClip } from "../images.ts"; import type { ReadAttribute, @@ -76,6 +77,7 @@ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadE const color = num(r, 62); const trueColor = num(r, 420); const book = colorBookOf(name(r, 430)); + const alpha = readAlpha(num(r, 440)); const linetype = name(r, 6); const lineweight = num(r, 370); const linetypeScale = num(r, 48); @@ -85,6 +87,7 @@ export function baseOf(r: Rec, layer: string, handle: string | undefined): ReadE ...(color !== undefined && color !== 256 && { color }), ...(trueColor !== undefined && { trueColor }), ...(book !== undefined && { colorBook: book }), + ...(alpha !== undefined && { alpha }), ...(linetype !== undefined && !/^bylayer$/i.test(linetype.trim()) && { linetype }), ...(lineweight !== undefined && lineweight !== -1 && { lineweight }), ...(linetypeScale !== undefined && linetypeScale !== 1 && { linetypeScale }), diff --git a/src/read/model.ts b/src/read/model.ts index 78f4a9c..f42ee29 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -313,6 +313,12 @@ export interface ReadEntityBase { readonly trueColor?: number; /** Group 430: a color of a color book, which `trueColor` holds as well. */ readonly colorBook?: ReadColorBook; + /** + * Group 440: how opaque the entity is, from 0 to 255 with 255 opaque, or `"ByBlock"`. A percent + * of transparency is `Math.round(100 - alpha / 2.55)`, from 0 to 90 for every alpha CAD + * programs' own commands make; a file may hold another, which gives more than 90 below 25. + */ + readonly alpha?: number | "ByBlock"; /** Group 6: a linetype's name, or `ByBlock`. */ readonly linetype?: string; /** Group 370: hundredths of a millimeter, or -2 for ByBlock and -3 for the default. */ diff --git a/src/rules.ts b/src/rules.ts index 6f6ae01..9185a56 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -160,6 +160,8 @@ const NAME_R12_CHARS = const NAME_R12_LENGTH = 'R12 layer names cannot be longer than 31 characters. Use DXF version "R2018" for longer names'; const COLOR = "A layer color must be a color index, an integer from 1 to 255"; +export const ENTITY_TRANSPARENCY = + 'An entity\'s transparency is a whole percent from 0 to 90, "ByLayer" or "ByBlock": 50 for half, not 0.5'; export const ENTITY_COLOR = 'An entity\'s color is a color index, a whole number from 1 to 255, "ByLayer", "ByBlock", or a true color: its red, green and blue, each a whole number from 0 to 255'; const POSITIVE = "This value must be greater than 0"; @@ -179,6 +181,8 @@ const R12_LINETYPES = const R12_LINEWEIGHTS = 'R12 drawings have no lineweights. Use DXF version "R2018" for lineweights'; const R12_ENTITY_STYLE = 'R12 entities take no linetype or lineweight of their own. Use DXF version "R2018" for an entity linetype or lineweight'; +const R12_ENTITY_TRANSPARENCY = + 'R12 entities take no transparency of their own. Use DXF version "R2018" for an entity transparency'; const R12_ENTITY_COLOR = 'R12 entities take no color of their own. Use DXF version "R2018" for an entity color'; const R12_LAYER_STATES = @@ -1977,6 +1981,7 @@ export const R12_ONLY = { layerStates: R12_LAYER_STATES, entityStyle: R12_ENTITY_STYLE, entityColor: R12_ENTITY_COLOR, + entityTransparency: R12_ENTITY_TRANSPARENCY, text: R12_TEXT, blocks: R12_BLOCKS, xrefs: R12_XREFS, @@ -5048,6 +5053,12 @@ const STANDARD_TABLE_STYLE_USED = /** What is wrong with a table given a color of its own. */ export const TABLE_COLOR = 'A table has no color of its own: its style and its cells give its colors. Leave out "color", or give "ByLayer"'; +/** What is wrong with a table given a transparency of its own. */ +export const TABLE_TRANSPARENCY = + 'A table has no transparency of its own: CAD programs plot its grid opaque. Leave out "transparency", or give "ByLayer"'; +/** What is wrong with a percent on an entity of a block a leader places. */ +export const LEADER_BLOCK_TRANSPARENCY = + 'CAD programs make every entity of a block a leader places transparent ByBlock, and drop a percent of its own. Give "ByBlock" or "ByLayer", or leave out "transparency"'; /** What is wrong with a table inside a block. */ export const TABLE_IN_BLOCK = "A table cannot be drawn in a block. Draw it in model space or on a layout, where the leading CAD app edits it"; diff --git a/src/shape.ts b/src/shape.ts index 390ddce..ba1aeca 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -500,6 +500,7 @@ function shapes(all: boolean, typed = all): Shapes { const shared = { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), linetype: ruled(string), lineweight: ruled(numberOrName), } as const; @@ -573,6 +574,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), scale: ruled(scale), rotation: number, attributes: ruled(map(string)), @@ -583,6 +585,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), angle: number, text: ruled(string), textBelow: ruled(string), @@ -593,6 +596,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(string), textBelow: ruled(string), }, @@ -602,6 +606,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(string), textBelow: ruled(string), textFromCenter: number, @@ -612,6 +617,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(string), textBelow: ruled(string), textFromCenter: number, @@ -622,6 +628,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(string), textBelow: ruled(string), }, @@ -640,6 +647,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(string), textBelow: ruled(string), }, @@ -657,6 +665,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(string), textBelow: ruled(string), }, @@ -674,6 +683,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(string), textBelow: ruled(string), }, @@ -690,6 +700,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), text: ruled(list(string)), block: ruled(string), attributes: ruled(map(string)), @@ -740,6 +751,7 @@ function shapes(all: boolean, typed = all): Shapes { { id: ruled(string), color: ruled(entityColor), + transparency: ruled(numberOrName), rotation: number, title: LEFT, titleHeight: ruled(number), diff --git a/src/svg.ts b/src/svg.ts index ca21e07..1e44f1f 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -1,3 +1,4 @@ +import { alphaOf, entityTransparencyProblem } from "./transparency.ts"; import { TRUE_COLOR } from "./paragraph-codes.ts"; import { isRgb } from "./colors.ts"; import { @@ -108,7 +109,7 @@ import { fontInfo, STANDARD_FONT, capHeightOf } from "./fonts.ts"; import { fifteenDigits, fmt, written } from "./format.ts"; import { layerKey, layerKeys } from "./layers.ts"; import { findLayout, validViewportView } from "./layouts.ts"; -import { leaderBlock, leaderPicture, type LeaderPicture } from "./leaders.ts"; +import { leaderBlock, leaderBlockKeys, leaderPicture, type LeaderPicture } from "./leaders.ts"; import { tableCost, tableInserts, @@ -300,7 +301,7 @@ const JOINED = 1024; * The format of a picture of a layout, which `svgToPDF` reads: it goes up whenever an element or * an attribute of such a picture changes what it means. */ -export const SHEET_PICTURE = 2; +export const SHEET_PICTURE = 3; /** The mark of a line drawn as the thinnest the printer draws: a lineweight of 0, or a border. */ const THINNEST = ` data-thinnest=""`; @@ -348,6 +349,11 @@ export interface SvgOptions { * The drawing's xrefs find their shapes here too. */ readonly shapes?: ShapeFiles; + /** + * Draws each entity's transparency, as CAD programs plot it when told to plot transparency + * always. Left out, every entity draws opaque, as they plot the page setups tsdraft writes. + */ + readonly plotTransparency?: boolean; } /** How an entity is drawn. */ @@ -361,6 +367,19 @@ interface Pen { readonly dashes: Dashes | undefined; /** In hundredths of a millimetre. */ readonly lineweight: number; + /** + * The opacity, from 0 to 255, a dimension or a leader draws its picture at, which it fades in a + * group of its own: the arrowheads of a block stay opaque, as CAD programs plot them. + */ + readonly alpha?: number; +} + +/** + * Parts of an entity at an opacity from 0 to 255: in a group, so that where they overlap they are + * no darker, as CAD programs compose a transparent entity before they fade it. + */ +function fadedGroup(parts: string, alpha: number): string { + return alpha >= 255 ? parts : `${parts}`; } /** A dash pattern scaled for a space, worked out once for each entity drawn with it. */ @@ -1131,6 +1150,43 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): /** Each pattern scaled for each space, worked out when first drawn with. */ const scaled = new Map>(); const findShape = shapeFinder(options.shapes); + const fading = options.plotTransparency === true; + /** + * The blocks a leader places, of the drawing and of each it references, worked out once each: + * they hold all they draw ByBlock, as CAD programs read them. + */ + const leaderKeys = new Map>(); + const leaderHeld = fading + ? (from: Referenced | undefined): ReadonlySet => { + const of = from?.drawing ?? drawing; + let keys = leaderKeys.get(of); + if (keys === undefined) leaderKeys.set(of, (keys = leaderBlockKeys(of))); + return keys; + } + : undefined; + /** + * The opacity an entity draws at, from 0 to 255: its own, the insert's that holds it for + * ByBlock, and opaque for ByLayer, since a layer has no transparency. Opaque unless asked. + */ + const alphaFor = (own: unknown, byBlock: number | undefined, kind?: string): number => { + // CAD programs plot a table's grid opaque, and the writers write it none. + if (!fading || kind === "table") return 255; + if (own === "ByBlock") return byBlock ?? 255; + return typeof own === "number" && entityTransparencyProblem(own) === undefined + ? alphaOf(own) + : 255; + }; + /** + * An entity's element at its opacity: in a group, so that where its parts overlap it is no + * darker, as CAD programs compose a transparent entity before they fade it. + */ + const faded = (element: string, alpha: number): string => fadedGroup(element, alpha); + /** The pen of an entity at `alpha`: a dimension and a leader fade their own pictures. */ + const fadedPen = (e: Entity, pen: Pen, alpha: number): Pen => + alpha < 255 && (isDimension(e) || e.kind === "leader") ? { ...pen, alpha } : pen; + /** The opacity of the group around an entity: none for one that fades its own picture. */ + const groupAlpha = (e: Entity, alpha: number): number => + isDimension(e) || e.kind === "leader" ? 255 : alpha; /** Each pattern's marks scaled for a space, by its scale and size. */ const marked = new Map>(); const dashesOf = ( @@ -1300,8 +1356,10 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): const named = e.textStyle ?? style.textStyle; const textStyle = named === undefined ? undefined : tables.textStyles.get(key(named)); const block = pictureOf(e, style, textStyle).block; - // The multileader holds its block ByBlock, so what the block sets ByBlock takes the leader's color. - return block === undefined || e.color === undefined ? block : { ...block, color: e.color }; + // The multileader holds its block ByBlock, so what the block sets ByBlock takes the leader's + // color. CAD programs draw the block opaque whatever the leader's transparency. + if (block === undefined) return block; + return e.color === undefined ? block : { ...block, color: e.color }; }; /** @@ -1327,7 +1385,9 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): if (isDimension(e)) { if (!write((e.text?.length ?? 0) + (e.textBelow?.length ?? 0))) refuse(where()); } - const element = drawn(e, marks(e, i), pen(look, styled(e), { name: e.layer }, where), look); + const alpha = alphaFor(e.transparency, undefined, e.kind); + const own = fadedPen(e, pen(look, styled(e), { name: e.layer }, where), alpha); + const element = faded(drawn(e, marks(e, i), own, look), groupAlpha(e, alpha)); if (!write(element.length + line)) refuse(where()); return element; } @@ -1360,7 +1420,15 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): m ? Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) : 1, at.byBlock, ); - const part = drawn(held, mark, heldPen, look, at.from, at.matrix); + const alpha = alphaFor( + at.byBlockHeld ? "ByBlock" : held.transparency, + at.byBlockAlpha, + held.kind, + ); + const part = faded( + drawn(held, mark, fadedPen(held, heldPen, alpha), look, at.from, at.matrix), + groupAlpha(held, alpha), + ); if (!write(part.length + line + 2)) return; parts.push(part); if (parts.length === JOINED) { @@ -1382,6 +1450,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): if (!spend(picture.blocks.length)) refuse(where()); return tableInserts(held, picture); }, + leaderHeld, ); if (!walked || length > longest) refuse(where()); const xref = blocks.has(key(e.block)) ? undefined : xrefPaths.get(key(e.block)); @@ -1850,7 +1919,9 @@ function leaderToSvg( ): string { if (picture === undefined) return ``; const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); - const parts: string[] = []; + let parts: string[] = []; + /** The parts that stay opaque when the leader fades. */ + const solid: string[] = []; // The parts share the picture's room: one that passes what is left ends the leader there, // longer than the room, which `write` then refuses. let left = room; @@ -1894,6 +1965,9 @@ function leaderToSvg( ``, ); } + // An open or a dot arrowhead is a block's, which CAD programs plot opaque. + const fading = parts; + if (pen.alpha !== undefined) parts = solid; for (const [from, to] of arrowhead.lines) { shape("arrowhead", { kind: "line", layer: e.layer, from, to }); } @@ -1906,6 +1980,7 @@ function leaderToSvg( ), ); } + parts = fading; } for (const [from, to] of picture.underlines) { shape("underline", { kind: "line", layer: e.layer, from, to }); @@ -1914,7 +1989,12 @@ function leaderToSvg( shape("frame", { kind: "polyline", layer: e.layer, points: picture.frame, closed: true }); } add((left) => paragraphToSvg(picture.note, layOut, `data-part="text"`, pen, look, matrix, left)); - return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; + const between = `\n${look.indent} `; + const drawnParts = + pen.alpha === undefined + ? [...parts, ...solid] + : [fadedGroup(parts.join(between), pen.alpha), ...solid]; + return `${between}${drawnParts.join(between)}\n${look.indent}`; } /** @@ -2314,14 +2394,21 @@ function dimensionToSvg( ), ), ...picture.leader.map((ends) => line("leader", ends, dimension)), - ...picture.arrowheads.map((corners) => { - if (thin) return line("arrowhead", [corners[0]!, corners[1]!], dimension); - const points = corners - .map(at) - .map(([x, y]) => `${fmt(x)},${fmt(y)}`) - .join(" "); - return ``; - }), + ]; + // A tick or an oblique stroke is a block's, which CAD programs plot opaque. + const blocked = arrowheadInfo(style.arrowhead ?? DEFAULT_ARROWHEAD)?.block !== undefined; + const heads = picture.arrowheads.map((corners) => { + if (thin) return line("arrowhead", [corners[0]!, corners[1]!], dimension); + const points = corners + .map(at) + .map(([x, y]) => `${fmt(x)},${fmt(y)}`) + .join(" "); + return ``; + }); + // Moved out of the faded group only when the dimension fades, so an opaque one is as it was. + const apart = blocked && pen.alpha !== undefined; + parts.push( + ...(apart ? [] : heads), ...pictureTexts(picture, textStyle).map((text) => paragraphToSvg( { @@ -2343,8 +2430,14 @@ function dimensionToSvg( room, ), ), - ]; - return `\n${look.indent} ${parts.join(`\n${look.indent} `)}\n${look.indent}`; + ); + const between = `\n${look.indent} `; + const solid = apart ? heads : []; + const drawnParts = + pen.alpha === undefined + ? [...parts, ...solid] + : [fadedGroup(parts.join(between), pen.alpha), ...solid]; + return `${between}${drawnParts.join(between)}\n${look.indent}`; } /** diff --git a/src/transparency.ts b/src/transparency.ts new file mode 100644 index 0000000..12cafa2 --- /dev/null +++ b/src/transparency.ts @@ -0,0 +1,45 @@ +// An entity's own transparency: a percent from 0 to 90 as CAD programs set it, or ByBlock, and +// how it is written and plotted. +import type { EntityTransparency } from "./drawing.ts"; +import { ENTITY_TRANSPARENCY } from "./rules.ts"; + +/** The most a transparency may be, in percent, as CAD programs allow. */ +export const TRANSPARENCY_MOST = 90; + +/** What is wrong with an entity's transparency, or undefined when it is one. */ +export function entityTransparencyProblem(transparency: unknown): string | undefined { + if (transparency === "ByLayer" || transparency === "ByBlock") return undefined; + return Number.isInteger(transparency) && + (transparency as number) >= 0 && + (transparency as number) <= TRANSPARENCY_MOST + ? undefined + : ENTITY_TRANSPARENCY; +} + +/** The opacity of a percent, from 0 to 255 with 255 opaque, as the leading CAD app stores it. */ +export const alphaOf = (percent: number): number => Math.floor((255 * (100 - percent)) / 100); + +/** + * What a file holds of an entity's transparency, DXF group 440 and the DWG's bit-long alike: + * `0x02000000` and its alpha, or `0x01000000` for ByBlock. Undefined for ByLayer, which a file + * leaves out. + */ +export function storedTransparency( + transparency: EntityTransparency | undefined, +): number | undefined { + if (transparency === undefined || transparency === "ByLayer") return undefined; + if (transparency === "ByBlock") return 0x01000000; + return 0x02000000 | alphaOf(transparency); +} + +/** + * What a reader keeps of the 32 bits a file holds, as the leading CAD app reads them: the alpha + * after `0x02`, from 0 to 255, `"ByBlock"` for `0x01` whatever follows, and nothing, ByLayer, for + * any other. + */ +export function readAlpha(value: number | undefined): number | "ByBlock" | undefined { + if (value === undefined) return undefined; + const kind = value >>> 24; + if (kind === 1) return "ByBlock"; + return kind === 2 ? value & 0xff : undefined; +} diff --git a/test/bounded.test.ts b/test/bounded.test.ts index b5b61d6..9f3775a 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -181,7 +181,8 @@ test("lint pays for what inserts repeat, and toDXF refuses what it stopped short id: `p${i}`, })), }; - const thrown = settled(2000, () => toDXF(points)); + // It takes about 1.8 s alone, so 4 s leaves a busy runner room and still stops a walk that grows. + const thrown = settled(4000, () => toDXF(points)); assert.ok(thrown instanceof DrawingError); assert.deepEqual( thrown.diagnostics.map((d) => [d.rule, d.severity]), diff --git a/test/images.test.ts b/test/images.test.ts index 9ac666d..b55e864 100644 --- a/test/images.test.ts +++ b/test/images.test.ts @@ -379,6 +379,32 @@ test("toPDF reads a file once however many times a sheet places it", () => { assert.equal(new TextDecoder("latin1").decode(pdf).match(/\/Subtype \/Image/g)?.length, 1); }); +test("a faded image's transparency group is as large as its clip, not its picture", () => { + const d = createDrawing({ units: "in", dxf: "R2018" }); + d.layout("S", { paper: "ARCH E" }, () => { + d.image("dot.png", [0, 0], { + pixels: [1, 1], + width: 48, + height: 36, + clip: [ + [10, 10], + [10.25, 10.25], + ], + transparency: 50, + }); + }); + const pdf = new TextDecoder("latin1").decode( + toPDF(d.build(), { + images: { "dot.png": png(1, 1, 2, () => [255, 0, 0]) }, + plotTransparency: true, + }), + ); + const [x0, y0, x1, y1] = /\/BBox \[([^\]]*)\]/.exec(pdf)![1]!.split(" ").map(Number); + // The clip is a quarter inch, 18 points, and a point wider each way for its rounding. + for (const side of [x1! - x0!, y1! - y0!]) + assert.ok(side >= 18 && side <= 21, `${[x0, y0, x1, y1]}`); +}); + test("an xref's images take their files from the xref's own, never the sheet's", () => { const sheetFile = png(4, 4, 2, () => [255, 0, 0]); const baseFile = png(8, 8, 2, () => [0, 0, 255]); diff --git a/test/pdf.test.ts b/test/pdf.test.ts index d988bc3..0b16af4 100644 --- a/test/pdf.test.ts +++ b/test/pdf.test.ts @@ -67,7 +67,7 @@ test("svgToPDF refuses what toSVG does not draw of a layout", () => { const d = createDrawing().line([0, 0], [1, 1]).build(); assert.throws( () => svgToPDF([toSVG(d)]), - /a picture of format null, where this copy of tsdraft reads format 2/, + /a picture of format null, where this copy of tsdraft reads format 3/, ); assert.throws(() => svgToPDF([]), RangeError); const sheet = toSVG(exampleSheet, { layout: exampleSheet.layouts![0]!.name }); @@ -330,3 +330,132 @@ test("a TrueType font given a file is embedded, cut to the characters set, each assert.equal(plot(), pdf); assert.ok(file.equals(before)); }); + +test("with plotTransparency an entity plots in a transparency group at its opacity, and opaque without", () => { + const d = createDrawing({ units: "in" }); + d.block("B", {}, () => d.line([0, 0], [1, 0], { transparency: "ByBlock" })); + d.layout("A-1", { paper: "ANSI B" }, () => { + d.line([1, 1], [5, 1], { transparency: 50 }); + d.insert("B", [1, 3], { transparency: 75 }); + }); + const drawing = d.build(); + const opaque = latin1(toPDF(drawing)); + assert.doesNotMatch(opaque, /\/Group|\/ExtGState/); + const pdf = latin1(toPDF(drawing, { plotTransparency: true })); + holdsTogether(pdf); + // The line at 127 of 255, and the block's line ByBlock at its insert's 63, each a form of its own. + assert.equal(pdf.match(/\/Subtype \/Form .*\/Group << \/S \/Transparency >>/g)?.length, 2); + assert.match(pdf, /<< \/Type \/ExtGState \/CA 0\.49804 \/ca 0\.49804 >>/); + assert.match(pdf, /<< \/Type \/ExtGState \/CA 0\.24706 \/ca 0\.24706 >>/); + assert.match(pdf, /^q\n\/Gs\d gs\n\/Fm\d Do\nQ$/m); + // Each form's box is what it paints, not the sheet, so a reader composes no more than that. + const boxes = [...pdf.matchAll(/\/BBox \[([^\]]*)\]/g)].map(([, b]) => b!.split(" ").map(Number)); + assert.equal(boxes.length, 2); + for (const [x0, y0, x1, y1] of boxes) assert.ok((x1! - x0!) * (y1! - y0!) < 1224 * 792 * 0.05); + const svg = toSVG(drawing, { layout: "A-1", plotTransparency: true }); + assert.match(svg, / tagged.line([0, 0], [0.1, 0], { transparency: 50 })); + tagged.block("TAG", {}, () => { + tagged.circle([0, 0], 0.2); + tagged.insert("INNER", [0, 0]); + }); + tagged.layout("A-1", { paper: "ANSI B" }, () => { + tagged.leader({ block: "TAG" }, { style: "S", at: [3, 5], to: [2, 4], transparency: 50 }); + tagged.insert("TAG", [6, 5], { transparency: 50 }); + }); + const plotted = toSVG(tagged.build(), { layout: "A-1", plotTransparency: true }); + assert.equal(plotted.match(/ base.circle([0, 0], 0.2)); + base.insert("TAG", [5, 5], { transparency: 50 }); + base.layout("A-1", { paper: "ANSI B" }, () => + base.leader({ block: "TAG" }, { style: "S", at: [3, 5], to: [2, 4] }), + ); + const host = createDrawing({ units: "in" }).xref("BASE", "base.dwg"); + host.insert("BASE", [0, 0]); + const through = toSVG(host.build(), { + xrefs: { BASE: { drawing: base.build() } }, + plotTransparency: true, + }); + assert.match(through, / { + pens.line([1, 1], [5, 1], { lineweight: 2.11 }); + pens.line([1, 2], [5, 2], { lineweight: 2.11, transparency: 50 }); + }); + const form = /\/Subtype \/Form [^]*?stream\n([^]*?)endstream/.exec( + latin1(toPDF(pens.build(), { plotTransparency: true })), + )![1]!; + for (const set of [/^1 J$/m, /^1 j$/m, / RG$/m, / w$/m]) assert.match(form, set); + // A faded text's box holds its letters at the size it is set, whatever its font-size says. + const lettered = createDrawing({ units: "in" }); + lettered.layout("A-1", { paper: "ANSI B" }, () => + lettered.text([1, 1], "WWWW", { height: 0.5, transparency: 50 }), + ); + const letters = toSVG(lettered.build(), { layout: "A-1", plotTransparency: true }); + for (const picture of [letters, letters.replace(/ font-size="[^"]*"/, "")]) { + const [x0, y0, x1, y1] = latin1(svgToPDF([picture])) + .match(/\/BBox \[([^\]]*)\]/)![1]! + .split(" ") + .map(Number); + // From the text's start at an inch to past four capitals of half an inch, cap to baseline. + assert.ok( + x0! <= 72 && x1! >= 72 + 4 * 36 && y0! <= 72 && y1! >= 72 + 36, + `${[x0, y0, x1, y1]}`, + ); + } + // In a font given a file and stretched to the length the text plots, the box holds the + // font's box around every glyph, stretched alike, past each end. + const file = readFileSync( + new URL("../cli/assets/fonts/JetBrainsMono-Regular.ttf", import.meta.url), + ); + const styled = createDrawing({ units: "in" }); + styled.textStyle({ name: "NOTE", font: "Arial" }); + styled.layout("A-1", { paper: "ANSI B" }, () => + styled.text([1, 1], "WW", { height: 0.5, style: "NOTE", transparency: 50 }), + ); + const set = latin1(toPDF(styled.build(), { fonts: { Arial: file }, plotTransparency: true })); + const numbers = (pattern: RegExp) => pattern.exec(set)![1]!.split(" ").map(Number); + const [bx0, by0, bx1, by1] = numbers(/\/BBox \[([^\]]*)\]/); + const [gx0, gy0, gx1, gy1] = numbers(/\/FontBBox \[([^\]]*)\] \/ItalicAngle/); + const [size] = numbers(/ ([\d.]+) Tf\n/); + const [stretch] = numbers(/\n([\d.]+) Tz\n/); + const s = stretch! / 100; + assert.ok(s > 1, "Arial's W is wider than the file's"); + const em = size! / 1000; + // The box is cut to the page, which this file's box reaches past on the left. + assert.ok(bx0! <= Math.max(0, 72 + s * em * gx0!), `${[bx0, by0, bx1, by1]}`); + assert.ok(by0! <= 72 + em * gy0! && by1! >= 72 + em * gy1!, `${[bx0, by0, bx1, by1]}`); + assert.ok(bx1! >= 72 + s * em * gx1!, `${[bx0, by0, bx1, by1]}`); + // A dimension's ticks are a block's, which CAD programs plot opaque: they are drawn after its + // faded group, outside it. + const ticked = createDrawing({ units: "in" }); + ticked.dimensionStyle({ + name: "TICKS", + textHeight: 0.125, + arrowSize: 0.125, + extensionOffset: 0.0625, + extensionBeyond: 0.125, + textGap: 0.0625, + precision: 2, + arrowhead: "architectural-tick", + }); + ticked.layout("A-1", { paper: "ANSI B" }, () => + ticked.linearDimension([1, 1], [4, 1], [2.5, 1.5], { style: "TICKS", transparency: 50 }), + ); + const ticks = toSVG(ticked.build(), { layout: "A-1", plotTransparency: true }); + assert.match(ticks, /[^]*?<\/g>\s*]*data-part="arrowhead"/); + assert.throws( + () => svgToPDF([svg.replace('opacity="0.49804"', 'opacity="half"')]), + /the opacity "half"/, + ); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index 23624a6..eec6467 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -23,10 +23,11 @@ import type { } from "../src/drawing.ts"; import { isFitSpline } from "../src/drawing.ts"; import { storedColor } from "../src/colors.ts"; +import { readAlpha, storedTransparency } from "../src/transparency.ts"; import { written, writtenAngle } from "../src/format.ts"; import { clamped } from "../src/curves.ts"; import { idHandle } from "../src/handles.ts"; -import { findLeaderStyle, leaderPicture } from "../src/leaders.ts"; +import { findLeaderStyle, heldByBlock, leaderPicture, leaderPlacesBlock } from "../src/leaders.ts"; import { fromImagePixels, imageClip, imageVectors, writtenImagePath } from "../src/images.ts"; import { layerKey } from "../src/layers.ts"; import { boxer } from "../src/extents.ts"; @@ -325,6 +326,8 @@ export function readProblems( `${label}: color ${got.color} and ${got.trueColor}, expected ${stored?.index} and ${stored?.rgb}`, ); } + const alpha = readAlpha(storedTransparency(want.transparency)); + if (got.alpha !== alpha) say(`${label}: alpha ${got.alpha}, expected ${alpha}`); if ( want.kind !== "insert" && want.kind !== "leader" && @@ -940,6 +943,8 @@ export function readProblems( `layout ${layout.name} #${i}`, ); }); + // A block a leader places is written with every entity ByBlock, as CAD programs hold it. + const placedByLeader = leaderPlacesBlock(drawing); for (const block of drawing.blocks ?? []) { const got = read.blocks.find((b) => sameName(b.name, block.name)); if (!got) { @@ -947,7 +952,8 @@ export function readProblems( continue; } const mine = own?.blocks.find((b) => sameName(b.name, block.name)); - entities(got.entities, mine?.entities, got.other, block.entities, `block ${block.name}`); + const held = placedByLeader(block.name) ? heldByBlock(block.entities) : block.entities; + entities(got.entities, mine?.entities, got.other, held, `block ${block.name}`); const definitions = block.attributes ?? []; if (got.attributeDefinitions.length !== definitions.length) { say(`block ${block.name}: ${got.attributeDefinitions.length} attribute definitions`); diff --git a/test/rules.test.ts b/test/rules.test.ts index cd2749d..a0117ea 100644 --- a/test/rules.test.ts +++ b/test/rules.test.ts @@ -26,6 +26,7 @@ import { import sheet, { sitePlan, type Box } from "../examples/site-plan.ts"; import { blocksByKey, eachDrawn, mapPoint } from "../src/blocks.ts"; import { extents } from "../src/extents.ts"; +import { leaderBlockKeys } from "../src/leaders.ts"; // Each `@ts-expect-error` below proves the compiler rejects the literal. The // `assert.throws` around it proves the same mistake is caught when the code runs. @@ -650,6 +651,107 @@ test("linetype, lineweight and layer state mistakes are compile errors and runti assert.deepEqual(lint(built), []); }); +test("an entity's transparency is a whole percent from 0 to 90, ByLayer or ByBlock", () => { + const d = createDrawing(); + const r12 = createDrawing({ dxf: "R12" }); + d.block("B", {}, () => d.circle([0, 0], 1, { transparency: "ByBlock" })); + d.tableStyle({ name: "S", textHeight: 1 }); + const table = { style: "S", at: [0, 0], columns: [4], rows: [[{ text: "A" }]] } as const; + assert.throws(() => d.line([0, 0], [1, 1], { transparency: 0.5 }), /50 for half, not 0\.5/); + assert.throws(() => d.line([0, 0], [1, 1], { transparency: 91 }), /from 0 to 90/); + assert.throws(() => d.line([0, 0], [1, 1], { transparency: -1 }), /from 0 to 90/); + // @ts-expect-error: a transparency is a number or one of two names. + assert.throws(() => d.line([0, 0], [1, 1], { transparency: "50%" }), /from 0 to 90/); + // @ts-expect-error: an R12 entity takes its layer's. + assert.throws(() => r12.line([0, 0], [1, 1], { transparency: 50 }), /R12 entities take no/); + r12.line([0, 0], [1, 1], { transparency: "ByLayer" }); + // @ts-expect-error: a table's grid plots opaque in CAD programs. + assert.throws(() => d.table({ ...table, transparency: 50 }), /A table has no transparency/); + d.table({ ...table, transparency: "ByLayer" }); + + d.line([0, 0], [1, 1], { transparency: 0 }); + d.line([0, 0], [1, 1], { transparency: 90 }); + d.line([0, 0], [1, 1], { transparency: "ByLayer" }); + d.insert("B", [0, 0], { transparency: "ByBlock" }); + d.hatch( + [ + { + points: [ + [0, 0], + [1, 0], + [1, 1], + ], + }, + ], + { transparency: 50 }, + ); + const built = d.build(); + assert.deepEqual( + built.entities.map((e) => e.transparency), + [undefined, 0, 90, undefined, "ByBlock", 50], + ); + assert.deepEqual(lint(built), []); + const faded = { ...built, entities: [{ ...built.entities[1]!, transparency: 0.5 }] }; + assert.deepEqual( + lint(faded as Drawing).map((p) => p.rule), + ["entity-transparency"], + ); +}); + +test("the blocks leaders place are found reading a list many layouts share once", () => { + let reads = 0; + const lines = new Proxy( + Array.from({ length: 1000 }, () => ({ kind: "line", layer: "0", from: [0, 0], to: [1, 1] })), + { + get: (target, key, receiver) => { + if (typeof key === "string" && /^\d+$/.test(key)) reads++; + return Reflect.get(target, key, receiver); + }, + }, + ); + const layouts = Array.from({ length: 1000 }, (_, i) => ({ name: `S${i}`, entities: lines })); + assert.equal(leaderBlockKeys({ entities: [], layouts }).size, 0); + assert.equal(reads, 1000); +}); + +test("a block a leader places takes no percent of its own, which CAD programs drop", () => { + const d = createDrawing({ units: "in" }); + d.leaderStyle({ name: "NOTES", textHeight: 0.1, arrowSize: 0.12, landing: 0.2, gap: 0.05 }); + d.block("FADED", {}, () => d.circle([0, 0], 1, { transparency: 0 })); + d.block("TAG", {}, () => { + d.circle([0, 0], 1, { transparency: "ByBlock" }); + d.line([0, 0], [1, 0], { transparency: "ByLayer" }); + d.insert("FADED", [0, 0]); + d.attribute("NO", [0, -1], { value: "1", height: 0.1 }); + }); + const leader = { style: "NOTES", at: [3, 3], to: [2, 2] } as const; + assert.throws( + () => d.leader({ block: "FADED" }, leader), + /CAD programs make every entity of a block a leader places transparent ByBlock/, + ); + // An insert in it may place a block with one: CAD programs keep that. + d.leader({ block: "TAG" }, leader); + d.insert("FADED", [5, 5]); + const built = d.build(); + assert.deepEqual(lint(built), []); + // Its file holds all it draws ByBlock, and its attribute definition, as CAD programs read it. + const dxf = toDXF(built); + const block = (name: string): string => { + const at = dxf.indexOf(`AcDbBlockBegin\r\n2\r\n${name}\r\n`); + return dxf.slice(at, dxf.indexOf("ENDBLK", at)); + }; + assert.equal(block("TAG").match(/\r\n440\r\n16777216\r\n/g)?.length, 4); + assert.match(block("FADED"), /\r\n440\r\n33554687\r\n/); + const placed = { + ...built, + entities: [...built.entities, { ...built.entities[0]!, block: "FADED" }], + }; + assert.deepEqual( + lint(placed as Drawing).map((p) => [p.rule, p.block]), + [["entity-transparency", "FADED"]], + ); +}); + test("entity color mistakes are compile errors and runtime errors", () => { const r12 = createDrawing({ dxf: "R12" }); const d = createDrawing(); diff --git a/test/shape.test.ts b/test/shape.test.ts index 793a5b5..994d1bd 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -37,7 +37,12 @@ import { } from "../src/index.ts"; import { timeLimit } from "./time-limit.ts"; -const styled = { linetype: "DD", lineweight: 0.25, color: [10, 200, 30] } as const; +const styled = { + linetype: "DD", + lineweight: 0.25, + color: [10, 200, 30], + transparency: 50, +} as const; const justified = { style: "NOTES", align: "center", valign: "middle" } as const; /** @@ -118,6 +123,7 @@ const kinds: { insert: { kind: "insert", color: "ByBlock", + transparency: "ByBlock", layer: "0", block: "TREE", at: [20, 0], @@ -129,6 +135,7 @@ const kinds: { "linear-dimension": { kind: "linear-dimension", color: 1, + transparency: 40, layer: "0", style: "DIMS", from: [0, 0], @@ -142,6 +149,7 @@ const kinds: { "aligned-dimension": { kind: "aligned-dimension", color: [200, 100, 50], + transparency: "ByLayer", layer: "0", style: "DIMS", from: [0, 0], @@ -154,6 +162,7 @@ const kinds: { leader: { kind: "leader", color: 255, + transparency: 0, layer: "0", style: "NOTE", text: ["NOTE", "SECOND LINE"], @@ -256,6 +265,7 @@ const kinds: { "radius-dimension": { kind: "radius-dimension", color: 7, + transparency: 90, layer: "0", style: "ARCH", center: [0, 0], @@ -268,6 +278,7 @@ const kinds: { "diameter-dimension": { kind: "diameter-dimension", color: [0, 0, 0], + transparency: 25, layer: "0", style: "ARCH", center: [0, 0], @@ -280,6 +291,7 @@ const kinds: { "jogged-radius-dimension": { kind: "jogged-radius-dimension", color: 8, + transparency: "ByBlock", layer: "0", style: "ARCH", center: [0, 0], @@ -293,6 +305,7 @@ const kinds: { "arc-length-dimension": { kind: "arc-length-dimension", color: "ByLayer", + transparency: 10, layer: "0", style: "ARCH", center: [0, 0], @@ -307,6 +320,7 @@ const kinds: { "angular-dimension": { kind: "angular-dimension", color: 250, + transparency: 75, layer: "0", style: "ARCH", vertex: [0, 0], @@ -320,6 +334,7 @@ const kinds: { table: { kind: "table", color: "ByLayer", + transparency: "ByLayer", layer: "0", style: "SCHEDULE", at: [100, 20], @@ -342,6 +357,7 @@ const kinds: { "ordinate-dimension": { kind: "ordinate-dimension", color: [40, 160, 220], + transparency: 50, layer: "0", style: "ARCH", axis: "x", @@ -431,6 +447,7 @@ const keyed: Required< > = { kind: "leader", color: "ByBlock", + transparency: 20, layer: "0", style: "NOTE", block: "TREE", From 600cef6e9b0f1d0f87fa6ee61d0e84f2739fce8f Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 20:31:03 -0500 Subject: [PATCH 28/35] The DWG reader reads the 2007 format, and tables before 2010 - `readDWG` reads drawings saved in the 2007 format, and tables saved in the 2004 and 2007 formats, as CAD programs read each when they open the file, into the same read model as the later formats. With this, `readDWG` reads every format from 2004 to 2018. - Known differences, follow-ups: an attribute of paragraph text in a mirrored insert of an older file reads its paragraph about half a unit from where CAD programs place it on opening; an invalid `\M+` code in 2004 text stays as written. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a1daee..2a33a85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,13 @@ ## Unreleased -- `readDWG` reads drawings saved in the 2004, 2010 and 2013 formats as well as 2018's, into the - same read model, as CAD programs read them when they open the file: a 2004 file's text in its - code page, each `\U+XXXX` in it as its character, and what a newer format holds that an older - one cannot, such as attributes of paragraph text, paragraph text in columns, a strike-through, - an image's inverted clip and a multileader's attachments, from the data an older save keeps for - it. A read names the file's `version`, and for 2004 its `codepage`. A table of the 2004 format - is counted under `unread.entities` and not read yet, and a drawing of the 2007 format is refused - with a `ReadError` that names it; both come next. +- `readDWG` reads drawings saved in the 2004, 2007, 2010 and 2013 formats as well as 2018's, into + the same read model, as CAD programs read them when they open the file: a 2004 file's text in its + code page, each `\U+XXXX` in it as its character, a table of the 2004 or 2007 format as one of + the later formats, and what a newer format holds that an older one cannot, such as attributes of + paragraph text, paragraph text in columns, a strike-through, an image's inverted clip and a + multileader's attachments, from the data an older save keeps for it. A read names the file's + `version`, and for 2004 its `codepage`. - An entity's own transparency, in R2018 drawings. Every entity but a table takes `transparency`: a whole percent from 0 to 90, `"ByLayer"`, the default, or `"ByBlock"`, which an entity of a block takes from its insert. `toDXF` writes it in group 440 as CAD programs store @@ -22,6 +21,7 @@ `readDWG` read it as `alpha`, from 0 to 255, or `"ByBlock"`. A block a leader places holds every entity ByBlock, as CAD programs read it, and the writers write it so; the leader draws it opaque. + - Linetypes with shapes: a fence with its circles along it, and batt insulation. `parseShapes` reads a firm's compiled shape file (`.shx`) into each shape's outlines, and `toSVG`, `toPDF` and `lint` take the files' bytes as `shapes`, found by name as CAD programs find them, without From 7338b7c23e58e089626905cc4d1f2b220fdf9c0c Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 20:59:28 -0500 Subject: [PATCH 29/35] PDF underlays: a page of a PDF under a sheet, written, read and plotted as CAD programs hold it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PDF underlays, in R2018 drawings: an architect's plan under an engineer's sheet, or a survey under a site plan. The drawing holds the PDF's path, the page and its size; CAD programs draw the page from the file each time they open the drawing. - `d.underlay(path, at, options)` places a page by its path from the drawing's folder, with its lower-left corner at `at`. At scale 1 the page is one drawing unit to an inch of the page, whatever the drawing's units, as CAD programs place it. - Options: `page` (a string, `"1"` by default), `pageSize` in inches (which `pdfPageSize` reads), `scale`, `rotation`, `clip` (a rectangle or a polygon), `invertClip`, `fade` (0–80), `contrast` (20–100), `monochrome` and `on`. - `underlayFrame` on the drawing: `true` shows and plots every underlay's frame, `false` hides it, and `"screen"` shows it but does not plot it. - Both writers write each page once as a definition that every underlay of it shares. They always write contrast and fade, because CAD programs read a DXF without the fade as no fade. - `readDXF` and `readDWG` read underlays back as `ReadUnderlay`, and list every definition of the file in `underlays`, unused ones included. They report `underlayFrame` when the frames do not plot. An underlay whose clip runs past the doubles is counted as malformed. - `toSVG` and `toPDF` draw an underlay from a PNG of its page, given as the `underlays` option by path and page: - The page is drawn in its fade, contrast and monochrome, clear where the page is unpainted, and in its own colors whatever the plot style. - A page that is not given is drawn as CAD programs draw a missing file: three lines of text at its insertion point, and no frame. - A picture fits its page when one resolution draws both of its sides within a pixel. One that does not throws a `RangeError`. - The `tsdraft` command reads each page's picture from `.page.png` beside its PDF, and warns of a missing one with the `pdftocairo` command that draws it. - Each placement's `pageSize` is checked against the PDF's page, and one that differs is an error. - A page the PDF does not have is drawn as missing. - `lint` and the builder refuse, under the rule `underlay`: - an absolute or unwritable path - a page that is not a number from 1 - a page size or scale that is not above 0 - a fade, contrast or clip out of range - `invertClip` without a clip - an underlay in an R12 drawing `docs/underlays.md` has the rules. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 9 + CHANGELOG.md | 14 + GUIDE.md | 6 + README.md | 9 +- cli/src/worker.ts | 194 +++++++++++- cli/test/fixtures/read/reader-a/read.js | 1 + cli/test/render.test.ts | 36 +++ docs/command.md | 7 + docs/format.md | 6 + docs/plotting.md | 3 + docs/reading.md | 12 + docs/rules.md | 4 + docs/underlays.md | 140 +++++++-- src/drawing.ts | 182 ++++++++++++ src/dxf-r2018.ts | 182 +++++++++++- src/extents.ts | 16 + src/index.ts | 26 ++ src/lint.ts | 96 +++++- src/pdf.ts | 10 + src/raster.ts | 27 +- src/read/check.ts | 33 ++- src/read/dxf.ts | 77 +++++ src/read/entities.ts | 71 +++++ src/read/model.ts | 60 ++++ src/rules.ts | 130 +++++++++ src/shape.ts | 26 ++ src/svg.ts | 185 +++++++++++- src/underlays.ts | 372 ++++++++++++++++++++++++ test/format.test.ts | 2 +- test/read-fuzz.ts | 31 ++ test/shape.test.ts | 25 +- test/underlays.test.ts | 267 +++++++++++++++++ 32 files changed, 2201 insertions(+), 58 deletions(-) create mode 100644 src/underlays.ts create mode 100644 test/underlays.test.ts diff --git a/AGENTS.md b/AGENTS.md index e367768..19d26b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -383,6 +383,15 @@ as it is and marks the `` `data-opaque`, which `toPDF` reads. That is the one place the preview and the plot part. A PNG the plot must decode and cannot is drawn by neither, as a file not given. +- `src/underlays.ts` is the one place of where an underlay's page goes, its clip as the file holds + it, its frame, its colors and its definitions: the writers, the plots, the extents and the + readers all take an underlay from it. A page is one drawing unit to an inch of it at scale 1, + whatever the units. `src/` draws no PDF: `toSVG` draws a page from the PNG the caller gives in + `underlays`, its colors changed by `underlayColor` and held again in stored deflate blocks, and + `pdfPageSize` in `src/pdf-pages.ts` reads only a page's size, from untrusted bytes. The DXF + leaves out a scale of 1, as the leading CAD app saves it, and always writes the contrast and the + fade: that app saves no contrast of 75 and no fade of 25, but reads a file without them as other + values, so a reader takes a file without them as 75 and 25 and the writers never leave them out. - `src/fills.ts` is the one place of what a hatch, a wipeout and a text's mask draw: a hatch's loops and their sides, filled by parity, which the writers make the leading CAD app's rule too by island style normal and polyline loops; a wipeout's square picture of one pixel and its clip; a mask's box diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a33a85..2806fb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,20 @@ fitted to its own first dash, which runs on from that last one, and a pattern of dashes alone draws its marks along a solid line, as CAD programs plot them. +- PDF underlays, in R2018 drawings: an architect's plan under a sheet. `d.underlay(path, at, + options)` places a page of a PDF by its path from the drawing's folder, its `page` and its + `pageSize` in inches, which `pdfPageSize` reads, at one drawing unit to an inch of the page + times `scale`, turned by `rotation`, with a `clip` of a rectangle or a polygon, `invertClip`, + `fade`, `contrast`, `monochrome` and `on`. `underlayFrame` on the drawing shows and plots every + underlay's frame, hides it, or with `"screen"` shows it and does not plot it. Both writers write + each page once as a definition every underlay of it shares, and `readDXF` and `readDWG` read + underlays back and list every definition in `underlays`, which every read now holds, so a reader + the command runs answers with it too. `toSVG` and `toPDF` draw an underlay from a picture of its + page given as `underlays`, in its fade, contrast and monochrome and in its own colors whatever + the plot style, and write that the file is missing where no picture is given, as CAD programs + do. The `tsdraft` command reads each page's picture from `.page.png` beside its PDF and + gives the `pdftocairo` command that draws one. `lint` and the builder refuse, under the rule + `underlay`, a path, page, page size, scale, fade, contrast or clip that cannot be written. - Tables, in R2018 drawings. `d.tableStyle(style)` defines a table style: the text style and height of its cells, its margins, and the cell style of its title, header and data rows, each with its own text style, height, alignment, text color, fill and border lineweight. diff --git a/GUIDE.md b/GUIDE.md index ac48082..c1e03a8 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -72,6 +72,12 @@ bank, a tree line or a contour, and `controlSpline` a spline by its control poin `rasterSize` reads, and an optional `clip`; the command reads the file from the drawing file's folder for the pictures, and warns of one that is missing. [docs/images.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/images.md) has them. +`underlay` places a page of a PDF, such as an architect's plan, by its path, its `page` and its +`pageSize` in inches, which `pdfPageSize` reads, at one drawing unit to an inch of the page times +`scale`; the command draws it from `.page.png` beside the PDF and gives the `pdftocairo` +command that draws one. +[docs/underlays.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/underlays.md) has +them. `hatch` fills one outline, or a list of loops `{ points, bulges? }` where a loop inside another is a hole, solid in the layer's color, or with `pattern` draws a pattern `patterns()` added from the firm's pattern file, or lines `spacing` apart, or with `gradient` runs from one color to another; `wipeout` hides what is drawn before it behind a polygon; and diff --git a/README.md b/README.md index 213369b..56764ae 100644 --- a/README.md +++ b/README.md @@ -214,6 +214,10 @@ toPDF(drawing, { images: { "aerial.png": readFileSync("aerial.png") } }); [Images](docs/images.md) has clips, frames and transparency, and what `lint` refuses. +An underlay places a page of a PDF under the sheet, such as an architect's plan, by its path, +its page and the page's size, which `pdfPageSize` reads. The plot draws it from a picture of the +page you give it, since tsdraft draws no PDF. [Underlays](docs/underlays.md) has the rest. + A hatch fills the area inside its loops solid, a loop inside another a hole, draws a pattern of the firm's pattern file there, or runs from one color to another as a gradient. A wipeout hides what is drawn before it, and a paragraph's mask hides it behind the text: @@ -427,8 +431,9 @@ lint(drawing, { version: "R12" }); // check a drawing against another version value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, transparency, how the plot draws one, and what `lint` refuses. -- [Underlays](docs/underlays.md) covers `pdfPageSize`, which reads a PDF page's size for an - underlay. Underlays themselves are coming. +- [Underlays](docs/underlays.md) covers PDF underlays: the path, the page and its size, scale, + clips, fade, contrast and monochrome, frames, the page's picture the plot draws, and what `lint` + refuses. - [Fills, wipeouts and masks](docs/fills.md) covers hatches with holes, solid, of a pattern file's patterns or of a gradient, wipeouts, the masks of paragraphs, leaders and dimensions, the draw order, and what `lint` refuses. diff --git a/cli/src/worker.ts b/cli/src/worker.ts index 9341bbd..79143ce 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -151,6 +151,7 @@ interface Library { standard?: unknown; xrefs?: GivenXrefs; shapes?: Readonly>; + underlays?: Readonly>>>; }, ) => Diagnostic[]; /** A copy of tsdraft from before standards has none, and its `lint` takes no standard. */ @@ -165,10 +166,18 @@ interface Library { view?: readonly [number, number, number, number]; images?: Readonly>; shapes?: Readonly>; + underlays?: Readonly>>>; }, ) => string; /** The key a shape file is found by. A copy of tsdraft from before shapes has none. */ readonly shapeFileKey?: (file: string) => string; + /** Where an underlay's page goes. A copy of tsdraft from before underlays has none. */ + readonly underlayCorners?: unknown; + /** A PDF page's size in inches. A copy of tsdraft from before it has none. */ + readonly pdfPageSize?: ( + bytes: Uint8Array, + page: string | number, + ) => readonly [number, number] | undefined; /** A raster file's pixels. A copy of tsdraft from before images has none. */ readonly rasterSize?: (bytes: Uint8Array) => [number, number] | undefined; /** What is wrong with the text as it plots. A copy of tsdraft from before it has none. */ @@ -628,7 +637,12 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise.page.png` beside the PDF, which `pdftocairo` draws, read + * from the folder of the drawing's file, with what is wrong with each. A page with no picture is + * drawn as the leading CAD app draws an underlay whose file it cannot find, and the warning gives + * the command that draws one. Where the library reads a PDF's page sizes, an underlay whose + * `pageSize` is not its page's is an error. Each file is tracked, so `tsdraft dev` builds again + * when one changes. Undefined for a copy of tsdraft from before underlays. + */ +function pageFiles( + library: Library, + drawing: Drawing, + file: string, + budget: { total: number }, +): { + underlays: Record> | undefined; + diagnostics: BuildDiagnostic[]; +} { + if (library.underlayCorners === undefined || typeof library.rasterSize !== "function") + return { underlays: undefined, diagnostics: [] }; + // Objects of no prototype, so a path or page such as `__proto__` is a key like any other. + const underlays: Record> = Object.create(null); + const diagnostics: BuildDiagnostic[] = []; + const pdfs = new Map(); + const lists: unknown[] = [ + drawing.entities, + ...(Array.isArray(drawing.layouts) ? drawing.layouts.map((l) => l?.entities) : []), + ...(Array.isArray(drawing.blocks) ? drawing.blocks.map((b) => b?.entities) : []), + ]; + const read = (at: string): Uint8Array | null => { + track(at, fileVersion(at)); + try { + const real = realpathSync(at); + if (real !== at) track(real, fileVersion(real)); + } catch { + // A missing file has no file behind it. + } + try { + return new Uint8Array(readFileSync(at)); + } catch { + return null; + } + }; + /** Each page's files, read once: its PDF's size of it, and its picture's pixels. */ + const pagesRead = new Map< + string, + { + pdfAt: string; + /** The page's size in the PDF; undefined where it cannot be read, null with no PDF. */ + size: readonly [number, number] | undefined | null; + /** Whether the PDF is read but has no such page. */ + absent: boolean; + picture: Uint8Array | null; + pixels: readonly [number, number] | undefined; + command: string; + } + >(); + /** The pages a placement was refused for: the pictures draw none of their placements. */ + const refused: [path: string, page: string][] = []; + /** Whether pdfPageSize reads each PDF's first page: if so, a page it cannot read is absent. */ + const firstPages = new Map(); + const said = new Set(); + const say = (severity: "warning" | "error", message: string): void => { + if (said.has(message)) return; + said.add(message); + diagnostics.push({ rule: "underlay", severity, message }); + }; + for (const list of lists) { + if (!Array.isArray(list)) continue; + for (const e of list) { + if (typeof e !== "object" || e === null || e.kind !== "underlay") continue; + const { + path, + page: given, + pageSize, + } = e as { + path?: unknown; + page?: unknown; + pageSize?: unknown; + }; + const page = given === undefined ? "1" : given; + if (typeof path !== "string" || typeof page !== "string") continue; + if (isAbsolute(path) || /^[A-Za-z]:/.test(path)) continue; + const key = `${page}|${path}`; + let files = pagesRead.get(key); + if (files === undefined) { + if (budget.total > RASTER_BYTES) continue; + const pdfAt = join(dirname(file), path.replaceAll("\\", "/")); + let pdf = pdfs.get(pdfAt); + if (pdf === undefined) pdfs.set(pdfAt, (pdf = read(pdfAt))); + const sizeOf = typeof library.pdfPageSize === "function" ? library.pdfPageSize : undefined; + const size = pdf === null ? null : sizeOf?.(pdf, page); + let readable = pdf === null ? undefined : firstPages.get(pdf); + if (pdf !== null && readable === undefined) { + firstPages.set(pdf, (readable = sizeOf?.(pdf, 1) !== undefined)); + } + const absent = size === undefined && readable === true; + const pictureAt = `${pdfAt}.page${page}.png`; + const picture = pdf === null || absent ? null : read(pictureAt); + if (picture !== null) budget.total += picture.length; + const pixels = + picture === null || picture[0] !== 0x89 ? undefined : library.rasterSize(picture); + const command = `pdftocairo -png -transp -cropbox -r 150 -f ${page} -l ${page} -singlefile ${JSON.stringify(pdfAt)} ${JSON.stringify(`${pdfAt}.page${page}`)}`; + pagesRead.set(key, (files = { pdfAt, size, absent, picture, pixels, command })); + } + const { pdfAt, size, absent, picture, pixels, command } = files; + const pictureAt = `${pdfAt}.page${page}.png`; + if (size === null) { + say( + "warning", + `The file of the underlay ${JSON.stringify(path)} is not at ${pdfAt}, so the pictures write that it is missing, as the leading CAD app does`, + ); + continue; + } + if (absent) { + say( + "warning", + `The file of the underlay ${JSON.stringify(path)} has no page ${page}, so the pictures write that it is missing`, + ); + continue; + } + const [w, h] = Array.isArray(pageSize) ? (pageSize as unknown[]) : []; + if (size === undefined && typeof library.pdfPageSize === "function") { + say( + "warning", + `The file of the underlay ${JSON.stringify(path)} has no page ${page} that pdfPageSize can read, so its size is not checked`, + ); + } else if ( + size !== undefined && + (typeof w !== "number" || + typeof h !== "number" || + !(Math.abs(w - size[0]) <= 1e-6 * Math.max(1, size[0])) || + !(Math.abs(h - size[1]) <= 1e-6 * Math.max(1, size[1]))) + ) { + say( + "error", + `Page ${page} of the underlay ${JSON.stringify(path)} is ${size[0]} by ${size[1]} inches, and the drawing gives it ${JSON.stringify(pageSize)}: the leading CAD app would place it at another size. Give it the page's size, which pdfPageSize reads. Until then the pictures write that the file of each underlay of the page is missing`, + ); + refused.push([path, page]); + continue; + } + if (picture === null) { + say( + "warning", + `Page ${page} of the underlay ${JSON.stringify(path)} has no picture at ${pictureAt}, so the pictures write that its file is missing. Draw one with: ${command}`, + ); + continue; + } + if (pixels === undefined) { + say( + "warning", + `The picture ${pictureAt} of page ${page} of the underlay ${JSON.stringify(path)} is not a PNG the pictures can draw, so they write that its file is missing. Draw one with: ${command}`, + ); + continue; + } + // Some one resolution draws both sides of the page within a pixel of the picture's. + const [px, py] = pixels; + if ( + typeof w === "number" && + typeof h === "number" && + w > 0 && + h > 0 && + !(Math.max((px - 1) / w, (py - 1) / h) <= Math.min((px + 1) / w, (py + 1) / h)) + ) { + say( + "error", + `The picture ${pictureAt} is ${px} by ${py} pixels, and page ${page} of the underlay ${JSON.stringify(path)} is ${w} by ${h} inches: the picture must have the page's shape. Draw it from the page's crop box with: ${command}. Until then the pictures write that the file of each underlay of the page is missing`, + ); + refused.push([path, page]); + continue; + } + (underlays[path] ??= Object.create(null) as Record)[page] = picture; + } + } + for (const [path, page] of refused) delete underlays[path]?.[page]; + return { underlays, diagnostics }; +} + /** * What the pictures are given for the xrefs: each drawing given with no lint error, and with * `files`, the files of its images, read from the folder of the xref's file, which `folder`, the diff --git a/cli/test/fixtures/read/reader-a/read.js b/cli/test/fixtures/read/reader-a/read.js index 12b588e..2f9636f 100644 --- a/cli/test/fixtures/read/reader-a/read.js +++ b/cli/test/fixtures/read/reader-a/read.js @@ -49,6 +49,7 @@ export async function readDrawingFile(chunks, name) { blocks: [], xrefs: [], images: [], + underlays: [], model: { census: { layers: {}, diff --git a/cli/test/render.test.ts b/cli/test/render.test.ts index 6cf38fd..377e4ec 100644 --- a/cli/test/render.test.ts +++ b/cli/test/render.test.ts @@ -1679,3 +1679,39 @@ test("render reads each image's file beside its drawing, an xref's beside the xr assert.match(svg, /data-pixels="2 2"/); assert.match(svg, /data-pixels="3 3"/); }); + +test("render checks each underlay's page size against its PDF, and draws no page the PDF lacks", () => { + const dir = realpathSync(tempDir()); + // A PDF of one page 11 by 8.5 inches, whose objects the reader finds by their headers. + writeFileSync( + join(dir, "arch.pdf"), + "%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 792 612] >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n", + ); + writeFileSync(join(dir, "arch.pdf.page1.png"), grayPng(110, 85)); + // A picture left from a page the file no longer has. + writeFileSync(join(dir, "arch.pdf.page9.png"), grayPng(110, 85)); + const underlay = { kind: "underlay", layer: "0", path: "arch.pdf", at: [0, 0] }; + const drawing = { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [ + { ...underlay, pageSize: [11, 8.5] }, + { ...underlay, at: [20, 0], pageSize: [8.5, 11] }, + { ...underlay, at: [50, 0], page: "9", pageSize: [11, 8.5] }, + ], + }; + const plan = join(dir, "plan.ts"); + writeFileSync(plan, `export default ${JSON.stringify(drawing)};\n`); + const { state } = render(plan); + const said = state.diagnostics.map((d) => `${d.severity}: ${d.message}`); + assert.equal(said.length, 2, said.join("\n")); + assert.match( + said[0]!, + /^error: Page 1 of the underlay "arch.pdf" is 11 by 8.5 inches.*\[8\.5,11\]/, + ); + assert.match(said[1]!, /^warning: The file of the underlay "arch.pdf" has no page 9,/); + // The page is drawn as missing at each placement, since one of them is refused. + assert.doesNotMatch(readFileSync(state.outputs.svg!, "utf8"), /.page.png` +beside its PDF, which the command reads once a build. A PDF that is missing gives an `underlay` +warning, and a page with no picture one that gives the `pdftocairo` command that draws it; the +pictures then write that the file is missing, as a CAD program does. A `pageSize` that is not the +page's in the PDF, and a picture not of the page's shape, are `underlay` errors. `tsdraft dev` +builds again when a PDF or a picture changes. [Underlays](underlays.md#plotting) has the rest. + ## The JSON `BuildState` in [`cli/src/state.ts`](../cli/src/state.ts) documents each field, and `schema`, diff --git a/docs/format.md b/docs/format.md index de71bf7..466ec6a 100644 --- a/docs/format.md +++ b/docs/format.md @@ -114,6 +114,12 @@ entity, which its frame is drawn in. `imageFrame: false` on the drawing hides ev A drawing with no image has the JSON it had before images existed. [Images](images.md) describes them. +An underlay is `{ "kind": "underlay" }` in `entities`, with its `layer`, its file's `path`, its +`pageSize` in inches and its lower-left corner `at`, and where they are set its `page`, `scale`, +`rotation`, `clip`, `invertClip`, `fade`, `contrast`, `monochrome` and `on`, and the `linetype` +and `lineweight` of every entity. `underlayFrame` on the drawing is `false` or `"screen"` where it +is set. [Underlays](underlays.md) describes them. + A hatch is an entity of kind `"hatch"`, with its `layer` and its `loops`, each `{ points }` and where a side is an arc its `bulges`, one for each side, its `pattern` or its `gradient` where it is not solid, and the `linetype` and `lineweight` of every entity. A pattern is `{ name }` of one of the drawing's diff --git a/docs/plotting.md b/docs/plotting.md index e2552b1..915eb67 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -71,6 +71,9 @@ preview shows it: dashes as [How it plots](polylines.md#how-it-plots) says. - An image is drawn from its file's bytes, given as `images`, clipped to its clip, with its frame in its pen, and the PDF holds each file once, as [Plotting](images.md#plotting) says. +- An underlay is drawn from a picture of its page, given as `underlays`, in its fade, contrast and + monochrome and in its own colors whatever the plot style table, clipped to its clip, with its + frame unless `underlayFrame` says otherwise, as [Plotting](underlays.md#plotting) says. - A hatch is filled by the parity of its loops, or draws its pattern's lines and dashes cut to them, a wipeout and a mask in the paper's white or a mask's color, each over what is drawn before it, as [Fills, wipeouts and masks](fills.md) says. diff --git a/docs/reading.md b/docs/reading.md index 56cd9a3..2d57e71 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -78,6 +78,10 @@ states and keeps each object's handle, and it keeps going past what it does not - `images`: each image definition of the file's dictionary of them, with its name, its path as the file holds it, the pixels it states, whether it is loaded, and how many images name it. One no image uses is kept, as CAD programs keep it through a save and a purge. +- `underlays`: each PDF definition of the file's dictionary of them, with its name, its path as the + file holds it, its page, and how many underlays name it, one no underlay uses among them. + `underlayFrame` is `false` where the file says underlays' frames neither show nor plot, and + `"screen"` where they show and do not plot. - `layouts`: each with its paper, its plotter, its plot style table, its plot's rotation, its viewports and its inserts. A viewport has its rectangle on the paper, the center and height of the model space it shows, `ratio`, which is paper units per model unit, its twist, and @@ -178,6 +182,14 @@ leader: file says not to show and `unclipped` for one it says not to clip say so, and `brightness`, `contrast` and `fade` are left out at 50, 50 and 0. An image out of the plane is counted under `other`. +- `underlay`: a page of a PDF, with its definition's `path` and `page` and the handle of the + `definition`, its lower-left corner `at`, its `scale` across and up, which takes an inch of the + page to drawing units, and its `rotation` from 0 up to 360. `clip` is its clip boundary where the + file holds one, in the world's coordinates: a rectangle's top-left and bottom-right corners along + the page, as CAD programs save them, or a polygon. `invertClip`, `monochrome`, `hidden` for one + the file says not to show and `unclipped` for one whose clip it says not to use say so, and + `fade` and `contrast` are left out at 0 and 100. A file without them means 25 and 75. It holds + no page size, which only the PDF gives. An underlay out of the plane is counted under `other`. - `hatch`: its `pattern`, such as `SOLID` or `ANSI31`, whether it is `solid`, its island `style`, `normal`, `outer` or `ignore`, `associative` where the file ties it to what it bounds, and its `loops`, each its `points`, its `bulges` where a side is an arc, and its `flags` as the file diff --git a/docs/rules.md b/docs/rules.md index bf847f1..e1f0618 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -55,6 +55,10 @@ it would take `1e+100` for `1e+10` and report nothing. two corners of a rectangle of some width and height along the image's sides, or a polygon of 3 points that differ, at most 10,000 in all, and `invertClip` needs a clip. [Images](images.md#what-lint-refuses) has the rest. +- An underlay is R2018 only. Its path follows an image's rules, its page is a string of digits + from `"1"`, its `pageSize` two numbers above 0 as written, its fade a whole number from 0 to 80 + and its contrast from 20 to 100. Its clip follows an image's, along the page's sides. + [Underlays](underlays.md#what-lint-refuses) has the rest. - A hatch and a wipeout are R2018 only. A hatch has at least one loop, and each loop at least 3 points, or 2 joined by an arc, with a bulge for each side where it has bulges. A wipeout has at least 3 points, which do not lie on one line as written, and sides that do not cross. diff --git a/docs/underlays.md b/docs/underlays.md index 8f262f2..3a3670f 100644 --- a/docs/underlays.md +++ b/docs/underlays.md @@ -1,56 +1,132 @@ # Underlays -An underlay is a PDF placed under a sheet: an architect's floor plan under an engineer's, or a -survey under a site plan. CAD programs draw the page from the file each time they open the -drawing, as they draw an image's file. Underlays themselves are coming. The first part is here: -`pdfPageSize`, which reads the size the drawing will hold of each, as `rasterSize` reads an image's -pixels. +An underlay is a page of a PDF placed under a sheet: an architect's floor plan under an +engineer's, or a survey under a site plan. The drawing holds the file's path, the page and its +size, and nothing of what the page shows. CAD programs draw the page from the file each time they +open the drawing. In the file it is a `PDFUNDERLAY`, with the page's definition, a +`PDFDEFINITION`, which every underlay of that page shares. -## A page's size +Underlays are R2018 only. The builder and `lint` refuse one in an R12 drawing. -`pdfPageSize(bytes, page)` gives a page's width and height in inches, across and down as a viewer -shows the page, or undefined: +## Drawing one + +`d.underlay(path, at, options)` places a page of the file at `path` with the lower-left corner of +the page at `at`. At scale 1 the page is one drawing unit to an inch of the page, whatever the +drawing's units, as CAD programs place it, so a 36 by 24 inch sheet under a plan drawn in feet at +1/4" = 1'-0" takes `scale: 48`. `pageSize` is the page's own width and height in inches, which +`pdfPageSize` reads from the file: ```ts import { readFileSync } from "node:fs"; -import { pdfPageSize } from "tsdraft"; +import { createDrawing, pdfPageSize } from "tsdraft"; -const size = pdfPageSize(readFileSync("A-101.pdf"), 2); // [36, 24] +const pageSize = pdfPageSize(readFileSync("arch/A-101.pdf"), 2)!; +const d = createDrawing({ units: "ft" }); +d.layer("X-ARCH", { color: 8 }, () => { + d.underlay("arch/A-101.pdf", [0, 0], { page: "2", pageSize, scale: 48, fade: 50 }); +}); ``` -CAD programs place an underlay with the lower-left corner of the page's box at the insertion -point, so at scale 1 a page is that many drawing units across and up, one to an inch of the page. +`path` starts from the folder of the drawing's file, with `\` or `/` between folders, as an +image's does, and the writers write it with `\`. An absolute path is refused. `page` is the page's +number from 1, as a string, and defaults to `"1"`. + +`rotation` turns the page about its lower-left corner, in degrees counterclockwise. In a block, an +insert's scale and rotation place it as they place the rest of the block. + +Each page is written once, as one definition that every underlay of it names, with `\` and `/` +taken as one. The definition is named by the file's name without its extension, `-` and the +page, such as `A-101 - 2`, with a number in brackets after the file's name where a file of another +folder took the name first. + +## How it plots -`page` is the page's number from 1, as a number or as a string such as `"2"`, the way a drawing -file names the page. Any other value, and a page past the file's last, gives undefined. +- `clip` hides what lies outside two corners of a rectangle along the page's sides, or a polygon, + in the drawing's coordinates. `invertClip: true` shows the page outside the clip instead. +- `fade`, a whole number from 0 to 80, mixes each color toward white by that share. +- `contrast`, a whole number from 20 to 100, draws each color's lightness toward a middle gray, + keeping its hue: 100, the default, leaves it as it is. +- `monochrome: true` plots each color as the gray of its lightness. +- `on: false` shows its frame alone. -The size is the page's box as a viewer shows it: +The page plots in its own colors whatever the plot style table, and what the page leaves +unpainted shows what is drawn before it. A page with a painted white ground hides it. + +Each underlay has a frame: the page's outline, or its clip's, drawn in the underlay's layer, +color and lineweight. `underlayFrame` on the drawing sets it for every underlay: `true`, the +default, shows and plots it; `false` neither; `"screen"` shows it in a CAD program and does not +plot it. `toSVG`, `toPDF` and the preview are plots, so they draw no frame for `"screen"`. + +## Plotting + +tsdraft draws no PDF. `toSVG` and `toPDF` draw an underlay from a picture of its page the caller +gives as `underlays`, by the underlay's path exactly as the drawing gives it and then by its page: +a PNG of the page with a clear background, such as `pdftocairo` draws: + +```sh +pdftocairo -png -transp -cropbox -r 150 -f 2 -l 2 -singlefile arch/A-101.pdf arch/A-101.pdf.page2 +``` + +```ts +const page2 = new Uint8Array(readFileSync("arch/A-101.pdf.page2.png")); +toPDF(drawing, { underlays: { "arch/A-101.pdf": { "2": page2 } }, deflate: zlib.deflateSync }); +``` + +The picture must have the page's shape, to a pixel, or `toSVG` throws a `RangeError`. 150 to 300 +pixels an inch is plenty: CAD programs plot an underlay as a picture of 400 pixels an inch, and a +picture of more than 100,000,000 pixels is drawn as a page not given. The picture is held in the +SVG once for each page and set of colors, and in the PDF once. A page in a fade, contrast or +monochrome is held in the SVG uncompressed, about 5⅓ characters a pixel, against the length +`toSVG` writes: draw such pages at 150 pixels an inch where a sheet has several. + +An underlay whose page is not given is drawn as CAD programs draw one whose file they cannot +find: three lines at its insertion point, `Missing or invalid reference`, the file and the page, +a fifth of an inch high at scale 1, and no frame. + +`tsdraft render` and `tsdraft dev` read each page's picture from beside its PDF, named +`.page.png`, and warn of one that is missing with the command that draws it. Where the +PDF is there, a `pageSize` that is not the page's is an error, and a page the PDF does not have +is drawn as missing. An underlay of an xref is drawn as missing. + +## A page's size + +`pdfPageSize(bytes, page)` gives a page's width and height in inches, across and down as a viewer +shows the page, or undefined. `page` is the page's number from 1, as a number or as a string such +as `"2"`. Any other value, and a page past the file's last, gives undefined. - The CropBox, cut to the MediaBox. With no CropBox, or one that misses the MediaBox, the MediaBox. -- A page that has no box of its own takes it from the page tree above it, the nearest first, as - a PDF reader does. So does `/Rotate`. +- A page that has no box of its own takes it from the page tree above it, the nearest first, as a + PDF reader does. So does `/Rotate`. An entry that is null counts as none. Pages are counted in the + tree's order, whatever a stale `/Count` says. - Points over 72, times the page's `/UserUnit` where it has one. A `/UserUnit` that is not a positive number counts as 1. - A `/Rotate` of 90 or 270, or -90, turns the page a quarter turn, so the width and the height change places. One that is not a multiple of 90 counts as 0. -## The files it reads +It reads cross-reference tables and streams, files that have both, the updates a program appends +to a file it saves, the newest winning, and objects packed inside object streams, compressed with +FlateDecode with or without a PNG predictor. Where the cross-reference is broken it finds the objects by scanning the +file for their headers, as viewers do. An encrypted file reads when its pages are outside object +streams. A file's bytes are untrusted: `pdfPageSize` never throws, and its work stays in +proportion to the file. -It reads a PDF's cross-reference tables and its cross-reference streams, the updates a program -appends to a file it saves, the newest winning, and objects packed inside object streams. A box, -each number in it, a page tree's `/Kids` and `/Count`, and `/Rotate` may each be given by -reference. A stream it must read, such as a cross-reference stream, may be compressed with -FlateDecode, with or without a PNG predictor; one in any other filter gives undefined. +## Reading -Where the cross-reference is broken, as when a file was edited by hand or cut short, it finds the -objects by scanning the file for their headers, as viewers do. +`readDXF` and `readDWG` read each underlay as the file places it: its path and page, its corner, +its scale across and up, its turn from 0 up to 360, its clip in the drawing's coordinates, and its +fade, contrast, monochrome and whether it shows. `underlays` lists every definition of the file, +those no underlay uses among them, which CAD programs keep through a save and a purge, and +`underlayFrame` says when the frames do not plot. A read underlay holds no page size. -An encrypted file reads when its pages are outside object streams, since encryption covers strings -and streams and leaves the numbers of a box as they are. One whose pages are packed in object -streams gives undefined. +## What lint refuses -A file's bytes are untrusted, and `pdfPageSize` never throws. It returns undefined for anything it -cannot read, and its work stays in proportion to the file: the streams of one file inflate to 64 MB -at most, a broken file's scan finds 262,144 objects at most, and a page tree deeper than 256 or one -that loops back on itself gives undefined. +- A path that is empty, absolute, longer than 32,000 characters, or that holds `* ? < > | : "`, a + multibyte escape or a character a text cannot hold. +- A page that is not a string of digits from `"1"`. +- A `pageSize` that is not two numbers above 0 as written, and a scale that is not above 0 as + written. +- A fade that is not a whole number from 0 to 80, or a contrast from 20 to 100. +- A clip of fewer than 2 points or more than 10,000, a rectangle of no width or no height along the + page, a polygon of fewer than 3 points that differ, and `invertClip` with no clip. +- An underlay in an R12 drawing. diff --git a/src/drawing.ts b/src/drawing.ts index 2bcb696..437d863 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -78,6 +78,7 @@ import { } from "./fills.ts"; import { parsePatterns } from "./patterns.ts"; import { imageVectors } from "./images.ts"; +import { underlayVectors } from "./underlays.ts"; import { canonical } from "./json.ts"; import { DrawingError, type Diagnostic, type LintRule } from "./lint.ts"; import { @@ -196,6 +197,17 @@ import { type R12Leaders, type R12Polylines, type R12Images, + type R12Underlays, + type UnderlayPath, + underlayClipProblem, + underlayContrastProblem, + underlayFadeProblem, + underlayPageProblem, + underlayPageSizeProblem, + underlayPathProblem, + underlayPlacedProblem, + underlayScaleProblem, + UNDERLAY_INVERT_WITHOUT_CLIP, type ImagePath, imageClipProblem, imagePathProblem, @@ -1030,6 +1042,50 @@ export interface Image extends EntityBase { readonly transparent?: boolean; } +/** + * A page of a PDF file under the drawing, such as an architect's plan, which the leading CAD app + * loads each time it opens the drawing and draws at one drawing unit to an inch of the page, times + * its scale. The drawing holds the file's path, the page and its size, and nothing of what it + * shows. Each page the drawing's underlays name is written as one definition, which every + * underlay of that page shares. R2018 only. + */ +export interface Underlay extends EntityBase { + readonly kind: "underlay"; + /** + * The file's path from the folder of this drawing's file, with `\` or `/` between folders, such + * as `"arch.pdf"` or `"../arch/A-101.pdf"`. + */ + readonly path: string; + /** The page's number from 1, as a string. Defaults to `"1"`. */ + readonly page?: string; + /** + * The page's width and height in inches, as the file gives them and `pdfPageSize` reads them: + * its crop box, turned as the page is turned. + */ + readonly pageSize: readonly [width: number, height: number]; + /** Where the page's lower-left corner goes. */ + readonly at: Point; + /** Drawing units to an inch of the page. Defaults to 1. */ + readonly scale?: number; + /** Degrees counterclockwise. Defaults to 0. */ + readonly rotation?: number; + /** + * The outline that clips it, in the drawing's coordinates: two opposite corners of a rectangle + * along the page's sides, or the points of a polygon, three or more. + */ + readonly clip?: readonly Point[]; + /** True to show the page outside its clip and hide what the clip holds. */ + readonly invertClip?: boolean; + /** How far its colors are mixed toward white, from 0 to 80. Defaults to 0. */ + readonly fade?: number; + /** How far its lightness keeps from a middle gray, from 20 to 100. Defaults to 100. */ + readonly contrast?: number; + /** True to plot it in grays. */ + readonly monochrome?: boolean; + /** False to show its frame alone. Defaults to true. */ + readonly on?: boolean; +} + /** * A closed outline of a hatch: from each point to the next and from the last back to the first, * each side straight or an arc by its bulge, as a closed `Polyline`'s sides are. @@ -1217,6 +1273,7 @@ export type Entity = | OrdinateDimension | Leader | Image + | Underlay | Hatch | Wipeout | Table; @@ -1606,6 +1663,13 @@ export interface Drawing { * to true, as the leading CAD app has it. A sheet with a logo or an aerial wants false. */ readonly imageFrame?: boolean; + /** + * Whether each underlay's frame shows and plots: its page's outline, or its clip's, in its pen. + * `true`, the default, as the leading CAD app has it; `false` neither; `"screen"` shows it in a + * CAD program and does not plot it. `toSVG`, `toPDF` and the preview are plots, so they draw no + * frame for `"screen"`. + */ + readonly underlayFrame?: boolean | "screen"; /** * Whether each wipeout's frame shows and plots: its polygon, in its pen. Defaults to true, as * the leading CAD app has it. A mask behind notes wants false. @@ -2122,6 +2186,43 @@ export interface ImageOptions< readonly transparent?: boolean; } +/** + * The options of `underlay()`: the page, its size, scale and turn, its clip, how it plots, and the + * options of every entity. + */ +export interface UnderlayOptions< + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, +> extends EntityOptions<"R2018", T, W, L, I, Z, P> { + /** The page's number from 1, as a string. Defaults to `"1"`. */ + readonly page?: string; + /** The page's width and height in inches, which `pdfPageSize` reads from the file. */ + readonly pageSize: readonly [width: number, height: number]; + /** Drawing units to an inch of the page. Defaults to 1. */ + readonly scale?: number; + /** Degrees counterclockwise. Defaults to 0. */ + readonly rotation?: number; + /** + * The outline that clips it, in the drawing's coordinates: two opposite corners of a rectangle + * along the page's sides, or the points of a polygon, three or more. + */ + readonly clip?: readonly Point[]; + /** True to show the page outside its clip and hide what the clip holds. */ + readonly invertClip?: boolean; + /** How far its colors are mixed toward white, a whole number from 0 to 80. Defaults to 0. */ + readonly fade?: number; + /** How far its lightness keeps from a middle gray, a whole number from 20 to 100. Defaults to 100. */ + readonly contrast?: number; + /** True to plot it in grays. */ + readonly monochrome?: boolean; + /** False to show its frame alone. Defaults to true. */ + readonly on?: boolean; +} + /** A text style to define: a `TextStyle`, checked. */ export interface TextStyleDefinition< N extends string = string, @@ -3986,6 +4087,87 @@ export class DrawingBuilder< }); } + /** + * A page of the PDF file at `path`, from the folder of this drawing's file, with its lower-left + * corner at `at` and one drawing unit to an inch of the page, times `scale`. `pageSize` is the + * page's own, which `pdfPageSize` reads. `clip` hides what lies outside two corners of a + * rectangle along its sides or a polygon, in the drawing's coordinates. R2018 only. + * + * ```ts + * d.underlay("arch.pdf", [0, 0], { page: "2", pageSize: [36, 24], scale: 48 }); + * ``` + */ + underlay< + const F extends string, + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + >( + path: V extends "R12" ? R12Underlays : UnderlayPath, + at: Point, + options: V extends "R12" ? R12Underlays : UnderlayOptions, + ): this { + const o = options as unknown as UnderlayOptions; + return this.#add(DrawingBuilder.prototype.underlay, o, () => { + if (this.dxf === "R12") refuse("underlay", R12_ONLY.underlays); + const pathProblem = underlayPathProblem(path); + if (pathProblem) refuse("underlay", pathProblem); + if (o.page !== undefined) { + const pageProblem = underlayPageProblem(o.page); + if (pageProblem) refuse("underlay", pageProblem); + } + const sizeProblem = underlayPageSizeProblem(o.pageSize); + if (sizeProblem) refuse("underlay", sizeProblem); + if (o.scale !== undefined) { + const scaleProblem = underlayScaleProblem(o.scale); + if (scaleProblem) refuse("underlay", scaleProblem); + } + const placed = underlayPlacedProblem(o.pageSize, o.scale ?? 1, pt(at)); + if (placed) refuse("underlay", placed); + if (o.fade !== undefined && underlayFadeProblem(o.fade)) + refuse("underlay", underlayFadeProblem(o.fade)!); + if (o.contrast !== undefined && underlayContrastProblem(o.contrast)) + refuse("underlay", underlayContrastProblem(o.contrast)!); + const rotation = + o.rotation === undefined ? undefined : kept(num(o.rotation, "rotation"), "rotation"); + for (const [field, value] of [ + ["invertClip", o.invertClip], + ["monochrome", o.monochrome], + ["on", o.on], + ] as const) { + if (value !== undefined && typeof value !== "boolean") { + refuse("underlay", `${field} must be true or false`); + } + } + const underlay: Underlay = { + kind: "underlay", + layer: this.#current, + path: path as string, + ...(o.page === undefined ? {} : { page: o.page }), + pageSize: [o.pageSize[0], o.pageSize[1]], + at: pt(at), + ...(o.scale === undefined ? {} : { scale: o.scale }), + ...(rotation === undefined ? {} : { rotation }), + }; + if (o.clip !== undefined) { + const [u, v] = underlayVectors(underlay); + const clipProblem = underlayClipProblem(o.clip, underlay.at, u, v); + if (clipProblem) refuse("underlay", `clip: ${clipProblem}`); + } else if (o.invertClip === true) refuse("underlay", UNDERLAY_INVERT_WITHOUT_CLIP); + return { + ...underlay, + ...(o.clip === undefined ? {} : { clip: o.clip.map(pt) }), + ...(o.invertClip === true ? { invertClip: true } : {}), + ...(o.fade === undefined || o.fade === 0 ? {} : { fade: o.fade }), + ...(o.contrast === undefined || o.contrast === 100 ? {} : { contrast: o.contrast }), + ...(o.monochrome === true ? { monochrome: true } : {}), + ...(o.on === false ? { on: false } : {}), + }; + }); + } + /** * A polyline of the current layer through `points`, with what `given` says of its sides, once * the sides are checked. A radius rounds the corners first. diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index f2ca2f9..caf3839 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -49,6 +49,7 @@ import type { EntityColor, EntityTransparency, Image, + Underlay, Insert, Layout, Leader, @@ -105,6 +106,23 @@ import { writtenImagePath, type ImageDefinition, } from "./images.ts"; +import { + drawingUnderlays, + pageOf, + UNDERLAY_DICTIONARY, + underlayClip, + underlayDefinitions, + underlayDictionaryHandle, + underlayFlags, + underlayFrameValue, + underlayFrameVariableHandle, + underlayPathKey, + type UnderlayDefinition, +} from "./underlays.ts"; + +/** The key of a page's definition: its page, and its path with \ and / as one. */ +const underlayKey = (path: string, page: string): string => + exactKey(`${page}|${underlayPathKey(path)}`); import { cellStyleOf, gridCells, @@ -269,6 +287,14 @@ export function toDXFR2018( for (const definition of definitions) definitionOf.set(exactKey(imagePathKey(definition.path)), definition); const reactors: { readonly image: string; readonly reactor: string; readonly of: string }[] = []; + // Each page the underlays show is one definition, which lists the underlays of it. + const underlays = [...drawingUnderlays(drawing)]; + const pageDefinitions = underlayDefinitions(underlays); + const pageDefinitionOf = new Map(); + for (const definition of pageDefinitions) + pageDefinitionOf.set(underlayKey(definition.path, definition.page), definition); + const underlayUsers = new Map(); + const pdfFrame = underlayFrameValue(drawing.underlayFrame); g(0, "SECTION"); g(2, "CLASSES"); @@ -332,6 +358,22 @@ export function toDXFR2018( entity: false, }); } + if (underlays.length > 0) { + writeClass(g, "PDFDEFINITION", "AcDbPdfDefinition", "ObjectDBX Classes", 1153, { + count: pageDefinitions.length, + entity: false, + }); + writeClass(g, "PDFUNDERLAY", "AcDbPdfReference", "ObjectDBX Classes", 4095, { + count: underlays.length, + entity: true, + }); + if (wipeouts === 0 && pdfFrame !== 1) { + writeClass(g, "DICTIONARYVAR", "AcDbDictionaryVar", "ObjectDBX Classes", 0, { + count: 1, + entity: false, + }); + } + } // The leading CAD app draws nothing of an image whose class it holds no count of. if (images.length > 0) { const count = (n: number, entity = false) => ({ count: n, entity }); @@ -713,6 +755,14 @@ export function toDXFR2018( }); return; } + if (entity.kind === "underlay") { + const definition = pageDefinitionOf.get(underlayKey(entity.path, pageOf(entity)))!; + const users = underlayUsers.get(definition.handle); + if (users) users.push(own); + else underlayUsers.set(definition.handle, [own]); + writeUnderlay(g, entity, { handle: own, owner, paper, definition: definition.handle }); + return; + } if (entity.kind === "leader") { const style = leaderStylesByKey.get(layerKey(entity.style)); if (style === undefined) return; @@ -944,9 +994,16 @@ export function toDXFR2018( g(3, TABLE_STYLE_DICTIONARY); g(350, tableDictionary); } + if (underlays.length > 0) { + g(3, UNDERLAY_DICTIONARY); + g(350, underlayDictionaryHandle()); + } if (wipeouts > 0) { g(3, "ACAD_WIPEOUT_VARS"); g(350, wipeoutVariablesHandle()); + } + const pdfFrameWritten = underlays.length > 0 && pdfFrame !== 1; + if (wipeouts > 0 || pdfFrameWritten) { g(3, "AcDbVariableDictionary"); g(350, variableDictionaryHandle()); } @@ -1020,7 +1077,14 @@ export function toDXFR2018( if (images.length > 0) { writeImageObjects(g, definitions, reactors, rootDictionary, drawing); } + if (underlays.length > 0) writeUnderlayObjects(g, pageDefinitions, underlayUsers, rootDictionary); if (wipeouts > 0) writeWipeoutObjects(g, rootDictionary, drawing); + if (wipeouts > 0 || pdfFrameWritten) { + writeVariables(g, rootDictionary, { + ...(pdfFrameWritten ? { PDFFRAME: pdfFrame } : {}), + ...(wipeouts > 0 ? { WIPEOUTFRAME: drawing.wipeoutFrame === false ? 0 : 1 } : {}), + }); + } if (sheets.length > 0) { g(0, "DICTIONARY"); ownedBy(g, layoutDictionary, rootDictionary); @@ -1096,6 +1160,7 @@ export function toDXFR2018( dimensionStyles.length > 0 || leaderStyles.length > 0 || images.length > 0 || + underlays.length > 0 || wipeoutCount(drawing) > 0 || drawing.entities.some((entity) => entity.id !== undefined); h(5, named ? ID_HANDLE_SEED : handle()); @@ -2616,23 +2681,122 @@ function writeImageObjects( * frames show. */ function writeWipeoutObjects(g: Group, root: string, drawing: Drawing): void { - const frame = drawing.wipeoutFrame === false ? 0 : 1; g(0, "WIPEOUTVARIABLES"); ownedBy(g, wipeoutVariablesHandle(), root); g(100, "AcDbWipeoutVariables"); - g(70, frame); + g(70, drawing.wipeoutFrame === false ? 0 : 1); +} + +/** + * The dictionary of the drawing's variables and each variable in it, by name in the order of + * their names: `PDFFRAME` and `WIPEOUTFRAME`, which is what the leading CAD app reads of whether + * the frames of underlays and wipeouts show. + */ +function writeVariables(g: Group, root: string, values: Readonly>): void { const variables = variableDictionaryHandle(); + const handles: Record = { + PDFFRAME: underlayFrameVariableHandle(), + WIPEOUTFRAME: wipeoutFrameVariableHandle(), + }; + const names = Object.keys(values).sort(); g(0, "DICTIONARY"); ownedBy(g, variables, root); g(100, "AcDbDictionary"); g(281, 1); - g(3, "WIPEOUTFRAME"); - g(350, wipeoutFrameVariableHandle()); - g(0, "DICTIONARYVAR"); - ownedBy(g, wipeoutFrameVariableHandle(), variables); - g(100, "DictionaryVariables"); - g(280, 0); - g(1, String(frame)); + for (const name of names) { + g(3, name); + g(350, handles[name]!); + } + for (const name of names) { + g(0, "DICTIONARYVAR"); + ownedBy(g, handles[name]!, variables); + g(100, "DictionaryVariables"); + g(280, 0); + g(1, String(values[name])); + } +} + +/** Where an underlay's PDFUNDERLAY goes, and what it points to. */ +interface UnderlayPlace { + readonly handle: string; + readonly owner: string; + readonly paper: boolean; + readonly definition: string; +} + +/** + * A PDFUNDERLAY, as the leading CAD app saves one: its corner, its scale both ways, its turn when + * it has one, its flags, contrast and fade, and its clip in the page's inches. + */ +function writeUnderlay(g: Group, e: Underlay, place: UnderlayPlace): void { + g(0, "PDFUNDERLAY"); + g(5, place.handle); + g(330, place.owner); + g(100, "AcDbEntity"); + if (place.paper) g(67, 1); + g(8, e.layer); + const linetype = entityLinetype(e); + if (linetype !== undefined) g(6, linetype); + if (e.lineweight !== undefined && e.lineweight !== "ByLayer") { + g(370, lineweightCode(e.lineweight)); + } + g(100, "AcDbUnderlayReference"); + g(340, place.definition); + point(g, 10, ...e.at); + // The leading CAD app leaves out a scale of 1 and no turn. + const scale = written(e.scale ?? 1); + if (scale !== 1) { + g(41, scale); + g(42, scale); + } + const turn = writtenAngle((((e.rotation ?? 0) % 360) + 360) % 360); + if (turn !== 0) g(50, turn); + g(280, underlayFlags(e)); + // Written whatever their values: the leading CAD app saves no contrast of 75 and no fade of 25, + // but reads a file without them as other values. + g(281, e.contrast ?? 100); + g(282, e.fade ?? 0); + for (const [x, y] of underlayClip(e)) { + g(11, fifteenDigits(x)); + g(21, fifteenDigits(y)); + } +} + +/** + * The objects of a drawing's underlays: the dictionary of their pages' definitions, and each + * definition with the underlays of it among its reactors. + */ +function writeUnderlayObjects( + g: Group, + definitions: readonly UnderlayDefinition[], + users: ReadonlyMap, + root: string, +): void { + const dictionary = underlayDictionaryHandle(); + g(0, "DICTIONARY"); + ownedBy(g, dictionary, root); + g(100, "AcDbDictionary"); + g(281, 1); + const sorted = definitions + .map((definition) => ({ definition, key: layerKey(definition.name) })) + .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)) + .map(({ definition }) => definition); + for (const definition of sorted) { + g(3, dxfOnce(definition.name)); + g(350, definition.handle); + } + for (const definition of definitions) { + g(0, "PDFDEFINITION"); + g(5, definition.handle); + g(102, "{ACAD_REACTORS"); + g(330, dictionary); + for (const user of users.get(definition.handle) ?? []) g(330, user); + g(102, "}"); + g(330, dictionary); + g(100, "AcDbUnderlayDefinition"); + g(1, dxfOnce(definition.path.replaceAll("/", "\\"))); + g(2, definition.page); + } } /** A color the leading CAD app holds as ByLayer and as ByBlock, as a multileader and its style write one. */ diff --git a/src/extents.ts b/src/extents.ts index 2c5000c..45a448f 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -14,6 +14,7 @@ import { } from "./blocks.ts"; import { dimensionMask, drawnLoops, loopOutline, maskOf, paragraphMaskCorners } from "./fills.ts"; import { imageCorners, imageDrawable, imageFrame } from "./images.ts"; +import { underlayCorners, underlayDrawable, underlayFrame } from "./underlays.ts"; import { dimensionArcPoints, dimensionPicture, @@ -446,6 +447,21 @@ export function boxer( add(box[2], box[3]); break; } + case "underlay": { + // The page, and the frame of a clip that reaches past it, as for an image. + if (!underlayDrawable(e, clipsChecked)) break; + for (const [x, y] of underlayCorners(e)) add(x, y); + if (e.clip === undefined) break; + if (e.clip.length === 2) { + for (const [x, y] of underlayFrame(e)) add(x, y); + break; + } + const box = pointsBox(e.clip); + if (box[0] === Infinity) break; + add(box[0], box[1]); + add(box[2], box[3]); + break; + } } }; /** diff --git a/src/index.ts b/src/index.ts index cc49d41..cf7eca3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -98,6 +98,8 @@ export { type HatchPatternChoice, type Image, type ImageOptions, + type Underlay, + type UnderlayOptions, type Insert, type JoggedRadiusDimension, type JoggedRadiusDimensionOptions, @@ -206,6 +208,28 @@ export { type ImageClip, type ImageDefinition, } from "./images.ts"; +export { + drawingUnderlays, + fromPage, + MISSING_HEIGHT, + missingLines, + pageOf, + toPage, + UNDERLAY_DICTIONARY, + underlayClip, + underlayColor, + underlayCorners, + underlayDefinitionHandle, + underlayDefinitions, + underlayDictionaryHandle, + underlayFlags, + underlayFrame, + underlayFrameValue, + underlayFrameVariableHandle, + underlayPathKey, + underlayVectors, + type UnderlayDefinition, +} from "./underlays.ts"; export { dimensionMask, GRADIENT_NAMES, @@ -494,6 +518,8 @@ export { type ReadHeader, type ReadImage, type ReadImageDefinition, + type ReadUnderlay, + type ReadUnderlayDefinition, type ReadInsert, type ReadLayer, type ReadLayerCensus, diff --git a/src/lint.ts b/src/lint.ts index 7d82e05..f94992e 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -41,6 +41,7 @@ import type { Hatch, HatchPattern, Image, + Underlay, Layout, Viewport, Insert, @@ -59,6 +60,7 @@ import type { import { isFitSpline } from "./drawing.ts"; import { boxer, type Boxer } from "./extents.ts"; import { exactKey, imagePathKey, imageReactorHandle, imageVectors } from "./images.ts"; +import { underlayVectors } from "./underlays.ts"; import { written } from "./format.ts"; import { validIdHandle } from "./handles.ts"; import { validLayoutHandles, validViewportView, viewReaches } from "./layouts.ts"; @@ -106,6 +108,15 @@ import { parseParagraph, type ParsedParagraph } from "./paragraph-codes.ts"; import { BUILT_IN_LINETYPES, builtInLinetype } from "./linetypes.ts"; import { IMAGE_CLIP_MOST, + underlayClipProblem, + underlayContrastProblem, + underlayFadeProblem, + underlayPageProblem, + underlayPageSizeProblem, + underlayPathProblem, + underlayPlacedProblem, + underlayScaleProblem, + UNDERLAY_INVERT_WITHOUT_CLIP, IMAGE_CLIP_MOST_PROBLEM, IMAGE_INVERT_WITHOUT_CLIP, IMAGE_PIXELS_SAME, @@ -293,6 +304,7 @@ export type LintRule = | "table" | "paragraph" | "image" + | "underlay" | "hatch" | "hatch-pattern" | "hatch-gradient" @@ -636,6 +648,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) cost += long1(e.style) + long1(e.textStyle); break; case "image": + case "underlay": cost += long1(e.path); break; case "hatch": @@ -840,6 +853,20 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) item: "imageFrame", }); } + const underlayFrame: unknown = drawing.underlayFrame; + if ( + underlayFrame !== undefined && + underlayFrame !== true && + underlayFrame !== false && + underlayFrame !== "screen" + ) { + out.push({ + rule: "underlay", + severity: "error", + message: 'underlayFrame must be true, false or "screen"', + item: "underlayFrame", + }); + } const wipeoutFrame: unknown = drawing.wipeoutFrame; if (wipeoutFrame !== undefined && typeof wipeoutFrame !== "boolean") { out.push({ rule: "wipeout", severity: "error", message: WIPEOUT_FRAME, item: "wipeoutFrame" }); @@ -2076,6 +2103,61 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) if (clash) add("id-handle", "error", clash); } }; + /** Checks what an underlay holds beyond the fields every entity has. */ + const lintUnderlay = (underlay: Underlay, add: Add, sound: boolean, here: () => string): void => { + const pathProblem = underlayPathProblem(underlay.path); + if (pathProblem) add("underlay", "error", pathProblem); + if (underlay.page !== undefined) { + const pageProblem = underlayPageProblem(underlay.page); + if (pageProblem) add("underlay", "error", pageProblem); + } + const sizeProblem = underlayPageSizeProblem(underlay.pageSize); + if (sizeProblem) add("underlay", "error", sizeProblem); + const scaleProblem = + underlay.scale === undefined ? undefined : underlayScaleProblem(underlay.scale); + if (scaleProblem) add("underlay", "error", scaleProblem); + if (sizeProblem === undefined && scaleProblem === undefined && sound) { + const placed = underlayPlacedProblem(underlay.pageSize, underlay.scale ?? 1, underlay.at); + if (placed) add("underlay", "error", placed); + } + if (underlay.fade !== undefined && underlayFadeProblem(underlay.fade)) + add("underlay", "error", underlayFadeProblem(underlay.fade)!); + if (underlay.contrast !== undefined && underlayContrastProblem(underlay.contrast)) + add("underlay", "error", underlayContrastProblem(underlay.contrast)!); + for (const [field, value] of [ + ["invertClip", underlay.invertClip], + ["monochrome", underlay.monochrome], + ["on", underlay.on], + ] as const) { + if (value !== undefined && typeof value !== "boolean") { + add("underlay", "error", `${field} must be true or false`); + } + } + if (underlay.clip === undefined && underlay.invertClip === true) { + add("underlay", "error", UNDERLAY_INVERT_WITHOUT_CLIP); + } + if (sound && scaleProblem === undefined && underlay.clip !== undefined) { + const list: unknown = underlay.clip; + if (Array.isArray(list) && list.length > IMAGE_CLIP_MOST) { + add( + "underlay", + "error", + `clip: ${IMAGE_CLIP_MOST_PROBLEM.replace("An image's", "An underlay's")}`, + ); + } else if ( + Array.isArray(list) && + list.length > 64 && + !spend(Math.floor(list.length / 8), here) + ) { + return; + } else { + const [u, v] = underlayVectors(underlay); + const at: Point = [written(underlay.at[0]), written(underlay.at[1])]; + const problem = underlayClipProblem(underlay.clip, at, u, v); + if (problem) add("underlay", "error", `clip: ${problem}`); + } + } + }; /** Checks the id of an entity or a viewport and takes its handle. True for an id that is new. */ const lintId = (id: unknown, add: Add): boolean => { if (id === undefined) return false; @@ -2133,6 +2215,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) isObject(entity) && (entity.kind === "polyline" || entity.kind === "image" || + entity.kind === "underlay" || entity.kind === "paragraph" || entity.kind === "hatch" || entity.kind === "wipeout" || @@ -2142,7 +2225,7 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) const columns: unknown = entity.kind === "paragraph" ? entity.columns : undefined; const loops = entity.kind === "hatch" ? filled(entity.loops as unknown) : []; const lists = - entity.kind === "image" + entity.kind === "image" || entity.kind === "underlay" ? [entity.clip] : entity.kind === "paragraph" ? [isObject(columns) ? columns.heights : undefined] @@ -2369,6 +2452,13 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) } lintImage(entity, add, problems.length === 0, named, here); } + if (entity.kind === "underlay") { + if (r12) { + add("underlay", "error", R12_ONLY.underlays); + return; + } + lintUnderlay(entity, add, problems.length === 0, here); + } if (r12 && (entity.kind === "ellipse" || entity.kind === "spline")) { add("geometry", "error", R12_ONLY.curves); return; @@ -3073,6 +3163,9 @@ function geometryProblems(e: Entity): string[] { size("width", e.width); size("height", e.height); break; + case "underlay": + finite("its position and rotation", ...e.at, e.rotation ?? 0); + break; case "hatch": { if (e.loops.length === 0) out.push(HATCH_NO_LOOPS); // One message of each kind for the hatch, with the first loop it is about. @@ -3155,6 +3248,7 @@ function zeroLength(e: Entity): string | undefined { case "aligned-dimension": case "leader": case "image": + case "underlay": return undefined; } } diff --git a/src/pdf.ts b/src/pdf.ts index 36d5e12..26f9e61 100644 --- a/src/pdf.ts +++ b/src/pdf.ts @@ -59,6 +59,11 @@ export interface PdfOptions { readonly images?: Readonly>; /** The bytes of each shape file the drawing's linetypes name, as `toSVG` takes them, for every sheet. */ readonly shapes?: ShapeFiles; + /** + * The picture of each page the drawing's underlays show, by the underlay's path exactly as the + * drawing gives it, then by its page, as `toSVG` takes them. The PDF holds each once. + */ + readonly underlays?: Readonly>>>; } /** One sheet of a set whose sheets are drawings of their own. */ @@ -70,6 +75,8 @@ export interface PdfSheet { readonly xrefs?: XrefDrawings; /** The raster files of its images, as `toPDF` takes them, in place of those of the options. */ readonly images?: Readonly>; + /** The pictures of its underlays' pages, as `toPDF` takes them, in place of those of the options. */ + readonly underlays?: Readonly>>>; } /** @@ -109,6 +116,7 @@ export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions ...(options.xrefs ? { xrefs: options.xrefs } : {}), })); const images = options.images; + const underlays = options.underlays; if (sheets.length === 0) throw new RangeError("There is no layout to plot"); sheets.forEach((sheet, i) => { if ( @@ -125,6 +133,7 @@ export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions for (const sheet of sheets) { const { drawing, layout, xrefs } = sheet; const own = sheet.images ?? images; + const ownPages = sheet.underlays ?? underlays; pdf.page( toSVG(drawing, { layout, @@ -132,6 +141,7 @@ export function toPDF(given: Drawing | readonly PdfSheet[], options: PdfOptions ...(own ? { images: own } : {}), ...(options.shapes ? { shapes: options.shapes } : {}), ...(options.plotTransparency === true ? { plotTransparency: true } : {}), + ...(ownPages ? { underlays: ownPages } : {}), }), ); } diff --git a/src/raster.ts b/src/raster.ts index 70e93da..bc0189b 100644 --- a/src/raster.ts +++ b/src/raster.ts @@ -640,15 +640,28 @@ export function opaquePng(info: PngInfo, bytes: Uint8Array): Uint8Array | undefi if (pixels === undefined) return undefined; const { width, height, channels, samples } = pixels; const colors = channels >= 3 ? 3 : 1; - const row = width * colors + 1; + const kept = new Uint8Array(width * height * colors); + for (let i = 0; i < width * height; i++) { + for (let k = 0; k < colors; k++) kept[i * colors + k] = samples[i * channels + k]!; + } + return storedPng(width, height, colors, kept); +} + +/** + * A PNG of 8-bit samples, `channels` to a pixel: 1 gray, 2 gray and alpha, 3 RGB, 4 RGB and alpha, + * rows from the top, written in deflate's stored blocks, which need no compressor. + */ +export function storedPng( + width: number, + height: number, + channels: 1 | 2 | 3 | 4, + samples: Uint8Array, +): Uint8Array { + const row = width * channels + 1; const raw = new Uint8Array(row * height); for (let y = 0; y < height; y++) { // Filter 0 on every row: the samples as they are. - for (let x = 0; x < width; x++) { - for (let k = 0; k < colors; k++) { - raw[y * row + 1 + x * colors + k] = samples[(y * width + x) * channels + k]!; - } - } + raw.set(samples.subarray(y * width * channels, (y + 1) * width * channels), y * row + 1); } const blocks = Math.max(1, Math.ceil(raw.length / 65_535)); const zlib = new Uint8Array(2 + raw.length + 5 * blocks + 4); @@ -676,7 +689,7 @@ export function opaquePng(info: PngInfo, bytes: Uint8Array): Uint8Array | undefi const header = new Uint8Array(13); header.set([width >>> 24, (width >>> 16) & 255, (width >>> 8) & 255, width & 255]); header.set([height >>> 24, (height >>> 16) & 255, (height >>> 8) & 255, height & 255], 4); - header.set([8, colors === 3 ? 2 : 0, 0, 0, 0], 8); + header.set([8, ({ 1: 0, 2: 4, 3: 2, 4: 6 } as const)[channels], 0, 0, 0], 8); return concat([ new Uint8Array(PNG_SIGNATURE), chunk("IHDR", header), diff --git a/src/read/check.ts b/src/read/check.ts index 80f7f19..0e1c335 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -17,7 +17,7 @@ type Type = | { readonly fields: Fields } | { readonly list: Type } | { readonly map: Type } - | { readonly oneOf: readonly string[] } + | { readonly oneOf: readonly (string | false)[] } /** The fields of one of these, named in a message as `named`. */ | { readonly either: readonly Fields[]; readonly named: string }; @@ -371,6 +371,23 @@ const ENTITY: Readonly> = { "contrast?": "number", "fade?": "number", }, + underlay: { + ...BASE, + kind: { oneOf: ["underlay"] }, + path: "string", + page: "string", + "definition?": "string", + at: "point", + scale: "point", + rotation: "number", + "clip?": { list: "point" }, + "unclipped?": "boolean", + "invertClip?": "boolean", + "monochrome?": "boolean", + "hidden?": "boolean", + "fade?": "number", + "contrast?": "number", + }, hatch: { ...BASE, kind: { oneOf: ["hatch"] }, @@ -609,6 +626,18 @@ const DRAWING_READ: Fields = { }, }, }, + underlays: { + list: { + fields: { + "handle?": "string", + name: "string", + path: "string", + page: "string", + underlays: "count", + }, + }, + }, + "underlayFrame?": { oneOf: [false, "screen"] }, model: { fields: SPACE }, layouts: { list: { @@ -761,7 +790,7 @@ export function checkDrawingRead(value: unknown): string[] { } } if ("oneOf" in type) { - if (typeof v !== "string" || !type.oneOf.includes(v)) { + if ((typeof v !== "string" && v !== false) || !type.oneOf.includes(v)) { say(at, `must be ${type.oneOf.map(shown).join(" or ")}`); } } else if ("list" in type) { diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 2681769..70fab19 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -15,6 +15,7 @@ import { costOf, handleAt, imageInWorld, + underlayInWorld, MAX_TAGS, nameCost, placementOf, @@ -62,6 +63,8 @@ import { type ReadHeader, type ReadImage, type ReadImageDefinition, + type ReadUnderlay, + type ReadUnderlayDefinition, type ReadInsert, type ReadLayer, type ReadLayerCensus, @@ -203,6 +206,7 @@ const BLOCK_READS = new Set([ "LWPOLYLINE", "MTEXT", "MULTILEADER", + "PDFUNDERLAY", "POLYLINE", "SEQEND", "SOLID", @@ -221,6 +225,7 @@ const SPACE_READS = new Set([ "LARGE_RADIAL_DIMENSION", "ARC_DIMENSION", "MTEXT", + "PDFUNDERLAY", "POLYLINE", "SEQEND", "TEXT", @@ -574,6 +579,21 @@ class DxfReader { readonly #imageUses = new Map(); /** The handle of the dictionary of image definitions, from the root dictionary. */ #imageDictionary: string | undefined; + /** The underlays kept, to finish once the definitions are read. */ + readonly #underlays: ReadUnderlay[] = []; + /** How many underlays name each definition, by its handle. */ + readonly #underlayUses = new Map(); + /** The handle of the dictionary of PDF definitions, from the root dictionary. */ + #underlayDictionary: string | undefined; + /** The dictionary's entries, in its order: each definition's name and handle. */ + readonly #underlayEntries: (readonly [name: string, handle: string])[] = []; + /** Each PDF definition, by its handle. */ + readonly #underlayDefinitions = new Map< + string, + { readonly path: string; readonly page: string } + >(); + /** The variable PDFFRAME's handle in the dictionary of variables. */ + #pdfFrameVariable: string | undefined; /** The dictionary of the drawing's variables, and the variable WIPEOUTFRAME's handle in it. */ #variableDictionary: string | undefined; #wipeoutFrameVariable: string | undefined; @@ -684,6 +704,7 @@ class DxfReader { type === "FIELD" || type === "LAYOUT" || type === "IMAGEDEF" || + type === "PDFDEFINITION" || type === "DICTIONARYVAR" || type === "SORTENTSTABLE" || type === "TABLESTYLE" @@ -1148,11 +1169,19 @@ class DxfReader { else if (definition !== undefined && this.#imageUses.size < this.#limits.census) this.#imageUses.set(definition, 1); } + if (r.type === "PDFUNDERLAY") { + const definition = handleAt(r, 340); + const uses = definition === undefined ? undefined : this.#underlayUses.get(definition); + if (uses !== undefined) this.#underlayUses.set(definition!, uses + 1); + else if (definition !== undefined && this.#underlayUses.size < this.#limits.census) + this.#underlayUses.set(definition, 1); + } if (!target) return; if (hidden(r)) return add(target.other, "invisible"); const reading = readingOf(r, baseOf(r, layer, handle), face, this.#later, this.#r12); const kept = reading !== undefined && "entity" in reading && this.#kept(target, reading.entity); if (kept && reading.entity.kind === "image") this.#images.push(reading.entity); + if (kept && reading.entity.kind === "underlay") this.#underlays.push(reading.entity); for (const pending of this.#settle(kept, target)) this.#starts.push(pending); if (reading === undefined) add(target.other, r.type); else if ("other" in reading) add(target.other, reading.other); @@ -1420,6 +1449,15 @@ class DxfReader { } else if (key === "ACAD_MLEADERSTYLE") this.#leaderStyleDictionary ??= value; else if (key === "ACAD_TABLESTYLE") this.#tableStyleDictionary ??= value; else if (key === "ACAD_IMAGE_DICT") this.#imageDictionary ??= value; + else if (key === "ACAD_PDFDEFINITIONS") this.#underlayDictionary ??= value; + else if (handle === this.#variableDictionary && key === "PDFFRAME") + this.#pdfFrameVariable ??= value; + else if ( + handle === this.#underlayDictionary && + key.length <= LONGEST_NAME && + this.#underlayEntries.length < this.#limits.census + ) + this.#underlayEntries.push([unescaped(key), value]); else if (key === "AcDbVariableDictionary") this.#variableDictionary ??= value; else if (handle === this.#variableDictionary && key === "WIPEOUTFRAME") this.#wipeoutFrameVariable ??= value; @@ -1492,6 +1530,16 @@ class DxfReader { }); return; } + case "PDFDEFINITION": { + const handle = handleAt(r, 5); + if (handle === undefined || this.#underlayDefinitions.size >= this.#limits.census) return; + const definition = inSubclass(r, "AcDbUnderlayDefinition"); + this.#underlayDefinitions.set(handle, { + path: name(definition, 1) ?? "", + page: name(definition, 2) ?? "", + }); + return; + } case "FIELD": { const handle = handleAt(r, 5); if (handle === undefined) return; @@ -1750,6 +1798,32 @@ class DxfReader { image.definition === undefined ? undefined : this.#imageDefinitions.get(image.definition); imageInWorld(image, definition?.path); } + for (const underlay of this.#underlays) { + const definition = + underlay.definition === undefined + ? undefined + : this.#underlayDefinitions.get(underlay.definition); + underlayInWorld(underlay, definition); + } + const underlaysListed = new Set(); + const underlays: ReadUnderlayDefinition[] = []; + const listUnderlay = (handle: string, name: string): void => { + const definition = this.#underlayDefinitions.get(handle); + if (definition === undefined || underlaysListed.has(handle)) return; + underlaysListed.add(handle); + underlays.push({ + handle, + name, + ...definition, + underlays: this.#underlayUses.get(handle) ?? 0, + }); + }; + for (const [name, handle] of this.#underlayEntries) listUnderlay(handle, name); + for (const handle of this.#underlayDefinitions.keys()) listUnderlay(handle, ""); + const pdfFrame = + this.#pdfFrameVariable === undefined + ? undefined + : Number(this.#variables.get(this.#pdfFrameVariable)); // The dictionary's definitions in its order, then any it does not list. const listed = new Set(); const images: ReadImageDefinition[] = []; @@ -1767,6 +1841,9 @@ class DxfReader { sha256, bytes, images, + underlays, + ...(pdfFrame === 0 ? { underlayFrame: false as const } : {}), + ...(pdfFrame === 2 ? { underlayFrame: "screen" as const } : {}), tableStyles, ...(groups.version !== undefined && { version: groups.version }), ...(groups.codepage !== undefined && { codepage: groups.codepage }), diff --git a/src/read/entities.ts b/src/read/entities.ts index 6b04e2a..5f2e510 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -5,6 +5,7 @@ import type { Point } from "../drawing.ts"; import { textOnce, textTwice } from "./groups.ts"; import { readAlpha } from "../transparency.ts"; import { wholeImageClip } from "../images.ts"; +import { UNDERLAY_CONTRAST_DEFAULT, UNDERLAY_FADE_DEFAULT } from "../underlays.ts"; import type { ReadAttribute, ReadAttributeParagraph, @@ -18,6 +19,7 @@ import type { ReadGradient, ReadHatchLoop, ReadImage, + ReadUnderlay, ReadPatternLine, ReadMtext, ReadMultileader, @@ -271,6 +273,8 @@ export function readingOf( return leader(r, base, face); case "IMAGE": return image(r, base); + case "PDFUNDERLAY": + return underlay(r, base); case "HATCH": return hatch(r, base, face); case "WIPEOUT": @@ -704,6 +708,71 @@ function wipeout(r: Rec, base: ReadEntityBase): Reading { return { entity: { ...base, kind: "wipeout", points } }; } +/** + * An underlay as its file places it, its clip in the world's coordinates. Its path and page are + * the definition's, which the reader fills in once it has read the definitions: + * `underlayInWorld` finishes it. + */ +function underlay(r: Rec, base: ReadEntityBase): Reading { + const s = inSubclass(r, "AcDbUnderlayReference"); + const normal = [num(s, 210) ?? 0, num(s, 220) ?? 0, num(s, 230) ?? 1]; + if (Math.abs(normal[0]!) > 1e-9 || Math.abs(normal[1]!) > 1e-9 || normal[2]! <= 0) + return { other: "PDFUNDERLAY in 3D" }; + const flags = num(s, 280) ?? 2; + const points: Point[] = []; + for (let i = 0; i < s.codes.length; i++) { + if (s.codes[i] !== 11) continue; + const y = s.codes[i + 1] === 21 ? Number(s.values[i + 1]) : 0; + points.push([Number(s.values[i]), y]); + } + const definition = handleAt(s, 340); + const contrast = num(s, 281) ?? UNDERLAY_CONTRAST_DEFAULT; + // The leading CAD app saves no contrast of 75 and no fade of 25, which a file without one means. + const fade = num(s, 282) ?? UNDERLAY_FADE_DEFAULT; + const turn = num(s, 50) ?? 0; + const rotation = ((turn % 360) + 360) % 360; + const at = point(s, 10); + const scale: [number, number] = [num(s, 41) ?? 1, num(s, 42) ?? 1]; + // The clip, from the page's inches into the world's coordinates. + const [cos, sin] = [Math.cos((rotation * Math.PI) / 180), Math.sin((rotation * Math.PI) / 180)]; + const clip = points.map(([x, y]): Point => { + const [sx, sy] = [x * scale[0], y * scale[1]]; + return [at[0] + sx * cos - sy * sin, at[1] + sx * sin + sy * cos]; + }); + if (!clip.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y))) { + return { malformed: "PDFUNDERLAY whose clip is past the doubles" }; + } + return { + entity: { + ...base, + kind: "underlay", + path: "", + page: "", + ...(definition !== undefined && { definition }), + at, + scale, + rotation, + ...(points.length >= 2 && { clip }), + ...(points.length >= 2 && (flags & 1) === 0 && { unclipped: true }), + ...((flags & 16) !== 0 && points.length >= 2 && { invertClip: true }), + ...((flags & 4) !== 0 && { monochrome: true }), + ...((flags & 2) === 0 && { hidden: true }), + ...(fade !== 0 && { fade }), + ...(contrast !== 100 && { contrast }), + }, + }; +} + +/** Finishes an underlay the reader kept: its definition's path and page. */ +export function underlayInWorld( + underlay: ReadUnderlay, + definition: { readonly path: string; readonly page: string } | undefined, +): void { + const mutable = underlay as Mutable; + mutable.path = definition?.path ?? ""; + mutable.page = definition?.page ?? ""; +} + /** * Finishes an image the reader kept: its definition's path, and its clip from its pixels into * the world's coordinates. @@ -1412,6 +1481,8 @@ export function costOf(e: ReadEntity): number { } case "image": return own + 4 + (e.clip?.length ?? 0) + chars(e.definition); + case "underlay": + return own + 4 + (e.clip?.length ?? 0) + chars(e.definition); case "hatch": { let points = 0; for (const loop of e.loops) points += 1 + loop.points.length + (loop.bulges?.length ?? 0); diff --git a/src/read/model.ts b/src/read/model.ts index f42ee29..b62acbd 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -50,6 +50,16 @@ export interface DrawingRead { * no image uses among them: the leading CAD app keeps one through a save and a purge. */ readonly images: readonly ReadImageDefinition[]; + /** + * Each PDF definition of the file's dictionary of them, in the order of the dictionary, those no + * underlay uses among them: the leading CAD app keeps one through a save and a purge. + */ + readonly underlays: readonly ReadUnderlayDefinition[]; + /** + * The dictionary variable `PDFFRAME`: `false` when underlays' frames neither show nor plot, + * `"screen"` when they show and do not plot. Left out when they show and plot, as with none. + */ + readonly underlayFrame?: false | "screen"; /** Model space: its census, and with `geometry` what it draws. */ readonly model: ReadSpace; /** Each layout of paper space, in the order of its tab. */ @@ -786,6 +796,42 @@ export interface ReadSolid extends ReadEntityBase { readonly points: readonly Point[]; } +/** + * A page of a PDF file under the drawing, as the file places it: the page's lower-left corner, its + * scale each way, which takes one inch of the page to drawing units, and its turn. + */ +export interface ReadUnderlay extends ReadEntityBase { + readonly kind: "underlay"; + /** The path of its definition as the file holds it, or `""` when it names none. */ + readonly path: string; + /** The page its definition names, or `""` when it names none. */ + readonly page: string; + /** The handle of its definition, when it names one. */ + readonly definition?: string; + readonly at: Point; + /** Drawing units to an inch of the page, across and up. */ + readonly scale: readonly [x: number, y: number]; + /** Degrees counterclockwise, from 0 up to 360. */ + readonly rotation: number; + /** + * The clip's boundary in the world's coordinates: a rectangle's top-left and bottom-right + * corners along the page's sides, or a polygon. Left out when the file holds none. + */ + readonly clip?: readonly Point[]; + /** True when the file holds a clip and says not to clip by it. */ + readonly unclipped?: boolean; + /** True when the page shows outside its clip, and the clip is a hole. */ + readonly invertClip?: boolean; + /** True when it plots in grays. */ + readonly monochrome?: boolean; + /** True when the file says not to show the page, which then shows its frame alone. */ + readonly hidden?: boolean; + /** Group 282, from 0 to 100. Left out at 0. */ + readonly fade?: number; + /** Group 281, from 0 to 100. Left out at 100. */ + readonly contrast?: number; +} + /** * A raster image, as the file places it: its lower-left corner and the vectors of one of its * pixels along its bottom and up its side, which a mirrored or slanted image has too. @@ -977,6 +1023,7 @@ export type ReadEntity = | ReadLeader | ReadSolid | ReadImage + | ReadUnderlay | ReadHatch | ReadWipeout | ReadTable; @@ -1009,6 +1056,19 @@ export interface ReadXref { readonly overlay: boolean; } +/** A PDF definition: the page of a file an underlay shows. */ +export interface ReadUnderlayDefinition { + readonly handle?: string | undefined; + /** Its name in the dictionary of PDF definitions. */ + readonly name: string; + /** The path as the file holds it, relative or absolute. */ + readonly path: string; + /** The page as the file names it. */ + readonly page: string; + /** How many underlays of the page name it. */ + readonly underlays: number; +} + /** An image definition: the file an image shows. */ export interface ReadImageDefinition { readonly handle?: string | undefined; diff --git a/src/rules.ts b/src/rules.ts index 9185a56..66347b8 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -200,6 +200,29 @@ const R12_PARAGRAPHS = 'tsdraft writes no paragraphs to R12 drawings. Use DXF version "R2018" for a paragraph'; const LINE_SPACING = "A paragraph's line spacing is a factor from 0.25 to 4"; const R12_IMAGES = 'tsdraft writes no images to R12 drawings. Use DXF version "R2018" for an image'; +const R12_UNDERLAYS = + 'tsdraft writes no PDF underlays to R12 drawings. Use DXF version "R2018" for an underlay'; +const UNDERLAY_PATH_EMPTY = + "An underlay's path cannot be empty. The leading CAD app finds no file by it"; +const UNDERLAY_PATH_ABSOLUTE = + 'An underlay\'s path must start from the folder of the drawing\'s file, as "arch.pdf" and "../arch/A-101.pdf" do, and cannot start with /, \\ or a drive such as C:. The leading CAD app looks for the file of an absolute path in that folder alone, and on another machine finds none'; +const UNDERLAY_PATH_CHARS = + "An underlay's path cannot hold * ? < > | : or \". The leading CAD app finds no file whose name holds one of them"; +const UNDERLAY_PATH_LENGTH = + "An underlay's path cannot be longer than 32,000 characters. The leading CAD app finds no file by a path that comes to more than 32,767 characters with the folder of the drawing"; +const UNDERLAY_PATH_MULTIBYTE = + "An underlay's path cannot hold a backslash before M+, a digit from 1 to 5 and four hex digits, such as \\M+10041. The leading CAD app reads those as one character, and looks for another file. Write / there"; +const UNDERLAY_PAGE = + 'An underlay\'s page is its number from 1, written as a string of digits with no leading 0, such as "1" or "12", up to "2147483647"'; +const UNDERLAY_PAGE_SIZE = + "An underlay's pageSize is its page's width and height in inches, two numbers greater than 0 as written and below 1e100, which pdfPageSize reads from the file"; +const UNDERLAY_FADE = + "An underlay's fade is a whole number from 0 to 80, as the leading CAD app sets it"; +const UNDERLAY_CONTRAST = + "An underlay's contrast is a whole number from 20 to 100, as the leading CAD app sets it"; +const UNDERLAY_SCALE = "An underlay's scale must be greater than 0 as written, and below 1e100"; +const UNDERLAY_PLACED = + "An underlay's page at its scale must come to less than 1e100 drawing units each way, which a file can write"; const R12_TABLES = 'tsdraft writes no tables to R12 drawings. Use DXF version "R2018" for a table'; const R12_HATCHES = 'tsdraft writes no hatches or wipeouts to R12 drawings. Use DXF version "R2018" for a fill'; @@ -1154,6 +1177,27 @@ export type R12Leaders = typeof R12_LEADERS; export type R12Polylines = typeof R12_POLYLINES; export type R12Paragraphs = typeof R12_PARAGRAPHS; export type R12Images = typeof R12_IMAGES; +export type R12Underlays = typeof R12_UNDERLAYS; + +/** + * Resolves to `P` when it is a path an underlay can have, and to the error message otherwise: a + * path is not empty, starts from the folder of the drawing's file, and holds no `* ? < > | : "`, + * no multibyte escape and no character a text cannot hold. Its length is checked when the code + * runs. + */ +export type UnderlayPath

= string extends P + ? P + : P extends "" + ? typeof UNDERLAY_PATH_EMPTY + : P extends `/${string}` | `\\${string}` + ? typeof UNDERLAY_PATH_ABSOLUTE + : Lowercase

extends `${LowerLetter}:${string}` + ? typeof UNDERLAY_PATH_ABSOLUTE + : P extends `${string}${Chars<'*?<>|:"'>}${string}` + ? typeof UNDERLAY_PATH_CHARS + : HasMultibyteEscape> extends true + ? typeof UNDERLAY_PATH_MULTIBYTE + : Description

; /** Resolves to `N` when it is a width a polyline can have, and to the error message otherwise. */ export type PolylineWidth = NotNegative; @@ -1991,6 +2035,7 @@ export const R12_ONLY = { polylines: R12_POLYLINES, paragraphs: R12_PARAGRAPHS, images: R12_IMAGES, + underlays: R12_UNDERLAYS, hatches: R12_HATCHES, tables: R12_TABLES, curves: R12_CURVES, @@ -3425,6 +3470,91 @@ export function imageClipProblem( return distinct.size >= 3 ? undefined : IMAGE_CLIP_POLYGON; } +/** Returns what is wrong with an underlay's path, or undefined when it is valid. */ +export function underlayPathProblem(path: unknown): string | undefined { + if (typeof path !== "string") return "An underlay's path must be a string"; + if (path.length === 0) return UNDERLAY_PATH_EMPTY; + if (/^(?:[/\\]|[A-Za-z]:)/.test(path)) return UNDERLAY_PATH_ABSOLUTE; + if (/[*?<>|:"]/.test(path)) return UNDERLAY_PATH_CHARS; + if (path.length > 32000) return UNDERLAY_PATH_LENGTH; + if (/\\[Mm]\+[1-5][0-9A-Fa-f]{4}/.test(path)) return UNDERLAY_PATH_MULTIBYTE; + return textProblem(path); +} + +/** Returns what is wrong with an underlay's page, or undefined when it is valid. */ +export function underlayPageProblem(page: unknown): string | undefined { + if (typeof page !== "string" || !/^[1-9][0-9]{0,9}$/.test(page) || Number(page) > 2_147_483_647) + return UNDERLAY_PAGE; + return undefined; +} + +/** Returns what is wrong with an underlay's page size, or undefined when it is valid. */ +export function underlayPageSizeProblem(size: unknown): string | undefined { + if (!Array.isArray(size) || size.length !== 2 || Reflect.ownKeys(size).length !== 3) + return UNDERLAY_PAGE_SIZE; + for (let i = 0; i < 2; i++) { + const item = Object.getOwnPropertyDescriptor(size, i); + const n: unknown = item && "value" in item ? item.value : undefined; + if (typeof n !== "number" || !Number.isFinite(n) || !(written(n) > 0) || n >= 1e100) + return UNDERLAY_PAGE_SIZE; + } + return undefined; +} + +/** Returns what is wrong with an underlay's scale, or undefined when it is valid. */ +export function underlayScaleProblem(scale: unknown): string | undefined { + return typeof scale === "number" && Number.isFinite(scale) && written(scale) > 0 && scale < 1e100 + ? undefined + : UNDERLAY_SCALE; +} + +/** Returns what is wrong with an underlay's page at its scale, or undefined when it is valid. */ +export function underlayPlacedProblem( + size: readonly [number, number], + scale: number, + at: readonly [number, number], +): string | undefined { + const reach = Math.hypot(size[0], size[1]) * written(scale); + return Math.abs(at[0]) + reach < 1e100 && Math.abs(at[1]) + reach < 1e100 + ? undefined + : UNDERLAY_PLACED; +} + +/** Returns what is wrong with an underlay's fade, or undefined when it is valid. */ +export function underlayFadeProblem(fade: unknown): string | undefined { + return Number.isInteger(fade) && (fade as number) >= 0 && (fade as number) <= 80 + ? undefined + : UNDERLAY_FADE; +} + +/** Returns what is wrong with an underlay's contrast, or undefined when it is valid. */ +export function underlayContrastProblem(contrast: unknown): string | undefined { + return Number.isInteger(contrast) && (contrast as number) >= 20 && (contrast as number) <= 100 + ? undefined + : UNDERLAY_CONTRAST; +} + +/** + * Returns what is wrong with an underlay's clip, or undefined when it is valid: the rules of an + * image's clip, judged in the page's axes, the vectors of one inch of it, `u` and `v`. + */ +export function underlayClipProblem( + clip: unknown, + at: readonly [number, number], + u: readonly [number, number], + v: readonly [number, number], +): string | undefined { + return imageClipProblem(clip, at, u, v) + ?.replaceAll("An image's", "An underlay's") + .replaceAll("the image's sides", "the page's sides") + .replaceAll("the image's width", "the page's width") + .replaceAll("the image's", "the underlay's"); +} + +/** What is wrong with `invertClip` on an underlay with no clip. */ +export const UNDERLAY_INVERT_WITHOUT_CLIP = + "invertClip needs a clip: it shows the page outside the clip, and with no clip there is no outside"; + /** The most points an image's clip may have. */ export const IMAGE_CLIP_MOST = 10_000; diff --git a/src/shape.ts b/src/shape.ts index ba1aeca..0a138b2 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -18,6 +18,7 @@ import type { HatchLoop, HatchPattern, Image, + Underlay, Insert, Layer, Layout, @@ -81,6 +82,7 @@ const KINDS = [ "aligned-dimension", "leader", "image", + "underlay", "hatch", "wipeout", ] as const satisfies readonly Entity["kind"][]; @@ -739,6 +741,29 @@ function shapes(all: boolean, typed = all): Shapes { transparent: ruled(boolean), }, ), + // A rule of `lint` reports the path, the page, its size, the clip and the settings, whatever + // their type. + underlay: fields( + { + kind, + layer: string, + path: ruled(string), + pageSize: ruled(point), + at: point, + }, + { + ...shared, + page: ruled(string), + scale: ruled(number), + rotation: number, + clip: ruled(list(point)), + invertClip: ruled(boolean), + fade: ruled(number), + contrast: ruled(number), + monochrome: ruled(boolean), + on: ruled(boolean), + }, + ), // A rule of `lint` reports the pattern and the gradient, whatever their types. hatch: fields( { kind, layer: string, loops: list(record(loop)) }, @@ -1001,6 +1026,7 @@ function shapes(all: boolean, typed = all): Shapes { leaderStyles: ruled(table(leaderStyle)), tableStyles: ruled(table(tableStyle)), imageFrame: ruled(boolean), + underlayFrame: LEFT, wipeoutFrame: ruled(boolean), patterns: ruled(table(pattern)), }, diff --git a/src/svg.ts b/src/svg.ts index 1e44f1f..5501e9e 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -23,6 +23,7 @@ import { type Hatch, type HatchPattern, type Image, + type Underlay, type Insert, type Layer, type Leader, @@ -78,12 +79,29 @@ import { } from "./polylines.ts"; import { boxer, type Boxer } from "./extents.ts"; import { exactKey, imageCorners, imageDrawable, imageFrame, writtenImagePath } from "./images.ts"; +import { + MISSING_HEIGHT, + missingLines, + pageOf, + missingReach, + pictureFits, + underlayAdjusted, + underlayLook, + underlayColor, + underlayCorners, + underlayDrawable, + underlayFrame, + underlayPlacement, + fromPage, +} from "./underlays.ts"; import { base64, base64Length, hasAlpha, opaquePng, plotDecodes, + pngPixels, + storedPng, RASTER_PIXELS, rasterInfo, withoutExif, @@ -323,6 +341,14 @@ export interface SvgOptions { * its frame, with its path written inside. */ readonly images?: Readonly>; + /** + * The picture of each page the drawing's underlays show, by the underlay's path exactly as the + * drawing gives it, then by its page: a PNG of the page with a clear background, as + * `pdftocairo -png -transp -cropbox` draws one, which the picture holds. Its width over its + * height must be the page's, to a pixel. An underlay whose page is not given here is drawn as + * the leading CAD app draws one whose file it cannot find: three lines that say so. + */ + readonly underlays?: Readonly>>>; /** * The drawing each xref stands for, by the xref's name. An insert of an xref draws the model * space of the drawing given here, and nothing when none is given. Given as @@ -1041,6 +1067,148 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): } return `${parts.join("")}`; }; + /** + * What each page's picture given is, read once, and the id of its image the picture holds in + * each set of colors. + */ + const pages = new WeakMap< + object, + { info: ReturnType; ids: Map } + >(); + /** + * The id of the picture's image of an underlay's page, in the colors it plots in, written the + * first time an underlay shows it, or null for a page not given or not a PNG it can draw. + */ + const pageId = (e: Underlay, from: Referenced | undefined): string | null => { + const given: unknown = from === undefined ? options.underlays : undefined; + if (typeof given !== "object" || given === null) return null; + const pagesOf = Object.getOwnPropertyDescriptor(given, e.path)?.value as unknown; + if (typeof pagesOf !== "object" || pagesOf === null) return null; + const item = Object.getOwnPropertyDescriptor(pagesOf, pageOf(e)); + const bytes = item && item.value instanceof Uint8Array ? item.value : undefined; + if (bytes === undefined) return null; + let read = pages.get(bytes); + if (!read) pages.set(bytes, (read = { info: rasterInfo(bytes), ids: new Map() })); + const { info, ids: held } = read; + const adjust = underlayLook(e); + const key = underlayAdjusted(e) ? `${adjust.fade},${adjust.contrast},${adjust.monochrome}` : ""; + // The page's picture is held to the page's shape, to a pixel. + if ( + info !== undefined && + info.kind === "png" && + !pictureFits(info.width, info.height, e.pageSize) + ) { + const [w, h] = e.pageSize; + throw new RangeError( + `The picture of page ${pageOf(e)} of ${quoted(e.path)} is ${info.width} by ${info.height} pixels, and the page is ${w} by ${h} inches: the picture must have the page's shape. Draw it from the page's crop box`, + ); + } + const known = held.get(key); + if (known !== undefined) return known; + let id: string | null = null; + if (info !== undefined && info.kind === "png" && info.width * info.height <= RASTER_PIXELS) { + let png: Uint8Array | undefined = bytes; + if (key !== "") { + // The colored picture is stored, four bytes a pixel: refused before it is drawn. + const stored = base64Length(info.width * info.height * 4); + if (length + stored > longest) { + length += stored; + refuse(`the picture of ${quoted(e.path)}`); + } + const pixels = pngPixels(info); + png = undefined; + if (pixels !== undefined) { + const { width, height, channels, samples } = pixels; + const out = new Uint8Array(width * height * 4); + for (let i = 0; i < width * height; i++) { + const gray = channels <= 2; + const at = i * channels; + const rgb = underlayColor( + gray + ? [samples[at]!, samples[at]!, samples[at]!] + : [samples[at]!, samples[at + 1]!, samples[at + 2]!], + adjust, + ); + out.set(rgb, i * 4); + out[i * 4 + 3] = channels === 2 || channels === 4 ? samples[at + channels - 1]! : 255; + } + png = storedPng(width, height, 4, out); + } + } + if (png !== undefined) { + id = `tsdraft-image-${rastersHeld++}`; + const head = ``); + } + } + held.set(key, id); + return id; + }; + /** + * An underlay: its page's picture mapped onto its corners and cut to its clip, then its frame in + * its pen. One turned off is its frame alone. One whose page is not given is three lines at its + * insertion point that say its file is missing, as the leading CAD app writes them, and no + * frame. + */ + const underlayElement = ( + e: Underlay, + mark: string, + pen: Pen, + look: Look, + from: Referenced | undefined, + matrix: Matrix | undefined, + room: number, + ): string => { + const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + const ring = (points: readonly Point[]) => + [...points, points[0]!] + .map(at) + .map(([x, y], i) => `${i === 0 ? "M" : "L"} ${precise(x)} ${precise(y)}`) + .join(" "); + const parts: string[] = []; + const on = e.on !== false; + const shown = on ? pageId(e, from) : null; + if (shown !== null) { + const [p0, p1, , p3] = underlayCorners(e).map(at) as [Point, Point, Point, Point]; + const place = [p1[0] - p0[0], p1[1] - p0[1], p0[0] - p3[0], p0[1] - p3[1], p3[0], p3[1]] + .map(precise) + .join(" "); + const use = ``; + if (e.clip === undefined) parts.push(use); + else { + const id = `tsdraft-image-clip-${clips++}`; + const outline = ring(underlayFrame(e)); + const d = e.invertClip ? `${ring(underlayCorners(e))} ${outline}` : outline; + const rule = e.invertClip ? ` clip-rule="evenodd"` : ""; + parts.push( + ``, + `${use}`, + ); + } + } else if (on) { + const { at: corner, u, v } = underlayPlacement(e); + const scale = Math.hypot(u[0], u[1]); + for (const line of missingLines(e)) { + const text: Text = { + kind: "text", + layer: e.layer, + at: fromPage(corner, u, v, line.at), + height: MISSING_HEIGHT * scale, + value: line.value, + rotation: e.rotation ?? 0, + }; + parts.push(entityToSvg(text, "", pen, look, undefined, matrix, room)); + } + } + if ((shown !== null || !on) && (drawing.underlayFrame ?? true) === true) { + parts.push( + ``, + ); + } + return `${parts.join("")}`; + }; /** * The element of an entity that draws something of its own, where `matrix` puts it. Its * dashes stop once they pass the room left in the picture, and `write` then refuses it. @@ -1090,6 +1258,11 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): ? imageElement(e, mark, drawnPen, look, from, matrix, room) : ""; } + if (e.kind === "underlay") { + return underlayDrawable(e, clipsChecked) + ? underlayElement(e, mark, drawnPen, look, from, matrix, room) + : ""; + } if (e.kind === "hatch") { const found = tablesOf(from).hatchPatterns; // A pattern whose lines cannot be placed, which `lint` refuses, is one the drawing lacks. @@ -1492,7 +1665,12 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): shown[1].kind === "insert" || isDimension(shown[1]) || shown[1].kind === "leader"; - const slack = lettered ? Math.max(box[2] - box[0], box[3] - box[1]) : 0; + const slack = lettered + ? Math.max(box[2] - box[0], box[3] - box[1]) + : // The lines of a missing file reach from the page's corner past its box. + shown[1].kind === "underlay" + ? missingReach(shown[1]) + : 0; return [{ shown, box, slack }]; }); } @@ -1893,7 +2071,10 @@ function viewOf(view: SvgOptions["view"]): [number, number, number, number] | un type Drawn = Exclude; /** An entity that is one shape, with a linetype and a lineweight it may have of its own. */ -type Shape = Exclude; +type Shape = Exclude< + Drawn, + Dimension | Leader | Paragraph | Image | Underlay | Hatch | Wipeout | Table +>; /** The linetype and the lineweight an entity has of its own. A dimension and a leader draw ByLayer. */ function styled(e: Drawn): Pick { diff --git a/src/underlays.ts b/src/underlays.ts new file mode 100644 index 0000000..7d33be0 --- /dev/null +++ b/src/underlays.ts @@ -0,0 +1,372 @@ +// PDF underlays: where a page goes, its clip as the file holds it, the outline its frame draws, +// the colors it plots in, and the definition each page is written as. The writers, the plot, the +// extents and the readers all take an underlay from here, from the numbers as they are written. +import type { Drawing, Entity, Point, Underlay } from "./drawing.ts"; +import { written } from "./format.ts"; +import { keyHandle } from "./handles.ts"; +import { exactKey } from "./images.ts"; +import { layerKey } from "./layers.ts"; +import { filled } from "./shape.ts"; + +/** A plain array of `count` finite numbers, read without running a getter. */ +function finiteNumbers(value: unknown, count: number): boolean { + if ( + !Array.isArray(value) || + value.length !== count || + Reflect.ownKeys(value).length !== count + 1 + ) + return false; + for (let i = 0; i < count; i++) { + const item = Object.getOwnPropertyDescriptor(value, i); + if (!item || !("value" in item) || typeof item.value !== "number") return false; + if (!Number.isFinite(item.value)) return false; + } + return true; +} + +/** + * Whether an underlay's fields can be drawn: a path and a page, a page size of two numbers above + * 0, a point, a finite scale not 0, and a clip of two points or more, each a point, plain arrays + * all. The plots and the extents leave out one that cannot, which `lint` refuses. + */ +export function underlayDrawable(underlay: Underlay, checked?: WeakMap): boolean { + const { path, page, pageSize, at, scale, rotation, clip } = underlay as Partial< + Record + >; + if (typeof path !== "string" || (page !== undefined && typeof page !== "string")) return false; + if (!finiteNumbers(pageSize, 2) || !finiteNumbers(at, 2)) return false; + const [w, h] = pageSize as [number, number]; + if (!(w > 0 && h > 0)) return false; + if (scale !== undefined && !(typeof scale === "number" && Number.isFinite(scale) && scale !== 0)) + return false; + if (rotation !== undefined && !(typeof rotation === "number" && Number.isFinite(rotation))) + return false; + if (clip === undefined) return true; + if (!Array.isArray(clip) || clip.length < 2) return false; + const known = checked?.get(clip); + if (known !== undefined) return known; + let sound = Reflect.ownKeys(clip).length === clip.length + 1; + for (let i = 0; sound && i < clip.length; i++) { + const item = Object.getOwnPropertyDescriptor(clip, i); + sound = item !== undefined && "value" in item && finiteNumbers(item.value, 2); + } + checked?.set(clip, sound); + return sound; +} + +/** The page's name an underlay shows: its number from 1, `"1"` when it gives none. */ +export const pageOf = (underlay: Underlay): string => underlay.page ?? "1"; + +/** + * The vectors of one inch of an underlay's page in the drawing: along its bottom edge, and up its + * side, from its scale and its turn. + */ +export function underlayVectors(underlay: Underlay): [u: Point, v: Point] { + const turn = ((underlay.rotation ?? 0) * Math.PI) / 180; + const quarter = Number.isInteger((underlay.rotation ?? 0) / 90); + const cos = quarter ? Math.round(Math.cos(turn)) : Math.cos(turn); + const sin = quarter ? Math.round(Math.sin(turn)) : Math.sin(turn); + const s = written(underlay.scale ?? 1); + return [ + [s * cos + 0, s * sin + 0], + [-s * sin + 0, s * cos + 0], + ]; +} + +/** The lower-left corner as written, and the vectors of one inch of the page. */ +function placed(underlay: Underlay): { at: Point; u: Point; v: Point } { + const [u, v] = underlayVectors(underlay); + return { at: [written(underlay.at[0]), written(underlay.at[1])], u, v }; +} + +/** A point of the drawing in an underlay's page, in inches from the page's lower-left corner. */ +export function toPage(at: Point, u: Point, v: Point, [x, y]: Point): Point { + const det = u[0] * v[1] - u[1] * v[0]; + const [dx, dy] = [x - at[0], y - at[1]]; + return [(dx * v[1] - dy * v[0]) / det, (u[0] * dy - u[1] * dx) / det]; +} + +/** A point of an underlay's page, in inches from its lower-left corner, in the drawing. */ +export function fromPage(at: Point, u: Point, v: Point, [x, y]: Point): Point { + return [at[0] + x * u[0] + y * v[0], at[1] + x * u[1] + y * v[1]]; +} + +/** The corners of an underlay's page in the drawing, from its lower-left round counterclockwise. */ +export function underlayCorners(underlay: Underlay): [Point, Point, Point, Point] { + const { at, u, v } = placed(underlay); + const [w, h] = underlay.pageSize; + return [at, fromPage(at, u, v, [w, 0]), fromPage(at, u, v, [w, h]), fromPage(at, u, v, [0, h])]; +} + +/** + * An underlay's clip as the file holds it, in inches of its page from its lower-left corner: a + * rectangle by its top-left and bottom-right corners, as the leading CAD app saves one, or a + * polygon's points as given, which that app does not close. Empty for no clip. + */ +export function underlayClip(underlay: Underlay): Point[] { + if (underlay.clip === undefined) return []; + const { at, u, v } = placed(underlay); + const points = underlay.clip.map(([x, y]) => toPage(at, u, v, [written(x), written(y)])); + if (points.length !== 2) return points; + const [[x0, y0], [x1, y1]] = points as [Point, Point]; + return [ + [Math.min(x0, x1), Math.max(y0, y1)], + [Math.max(x0, x1), Math.min(y0, y1)], + ]; +} + +/** + * The outline an underlay's frame draws, in the drawing, as a closed ring: its clip's, past the + * page too, or the page's when it is not clipped. A rectangle of a clip is the one along the + * page's sides through its corners. + */ +export function underlayFrame(underlay: Underlay): Point[] { + if (underlay.clip === undefined) return underlayCorners(underlay); + const { at, u, v } = placed(underlay); + const clip = underlayClip(underlay); + const back = (p: Point) => fromPage(at, u, v, p); + if (clip.length === 2) { + const [[x0, y1], [x1, y0]] = clip as [Point, Point]; + return [back([x0, y0]), back([x1, y0]), back([x1, y1]), back([x0, y1])]; + } + return clip.map(back); +} + +/** The flags of an underlay as the file holds them: clip 1, shown 2, monochrome 4, inverted 16. */ +export function underlayFlags(underlay: Underlay): number { + return ( + (underlay.clip !== undefined ? 1 : 0) | + (underlay.on === false ? 0 : 2) | + (underlay.monochrome === true ? 4 : 0) | + (underlay.invertClip === true && underlay.clip !== undefined ? 16 : 0) + ); +} + +/** + * The color the leading CAD app plots a color of an underlay's page in, each part from 0 to 255: + * made gray by its lightness when monochrome, its lightness drawn toward a middle gray by the + * contrast, then mixed toward white by the fade. + */ +export function underlayColor( + rgb: readonly [number, number, number], + { fade, contrast, monochrome }: { fade: number; contrast: number; monochrome: boolean }, +): [number, number, number] { + let [r, g, b] = [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255]; + if (monochrome) { + const l = (Math.max(r, g, b) + Math.min(r, g, b)) / 2; + [r, g, b] = [l, l, l]; + } + if (contrast !== 100) { + const k = contrast / 100; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const l = (max + min) / 2; + const target = CONTRAST_GRAY + (l - CONTRAST_GRAY) * k; + // The same hue and saturation at the new lightness. + if (max === min) [r, g, b] = [target, target, target]; + else { + const s = l <= 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min); + const q = target <= 0.5 ? target * (1 + s) : target + s - target * s; + const p = 2 * target - q; + const part = (x: number) => p + ((x - min) / (max - min)) * (q - p); + [r, g, b] = [part(r), part(g), part(b)]; + } + } + if (fade !== 0) { + const f = fade / 100; + [r, g, b] = [r + (1 - r) * f, g + (1 - g) * f, b + (1 - b) * f]; + } + const out = (x: number) => Math.max(0, Math.min(255, Math.round(x * 255))); + return [out(r), out(g), out(b)]; +} + +/** The gray the contrast draws a lightness toward. */ +const CONTRAST_GRAY = 0.44; + +/** One page the underlays of a drawing show, as one definition of it. */ +export interface UnderlayDefinition { + /** Its name in the dictionary of PDF definitions: the file's name and its page, made unique. */ + readonly name: string; + /** The path as the first underlay of it gives it. */ + readonly path: string; + readonly page: string; + readonly handle: string; +} + +/** The key two paths of one file share: `\` and `/` are one. */ +export function underlayPathKey(path: string): string { + return path.replaceAll("\\", "/"); +} + +/** + * The handle of the definition of a page of the file at `path`, from its path, with `\` and `/` + * taken as one, and its page. Never change the key. + */ +export function underlayDefinitionHandle(path: string, page: string): string { + return keyHandle(`underlay-definition:${underlayPathKey(path)}|${page}`); +} + +/** The handle of the dictionary of PDF definitions, `ACAD_PDFDEFINITIONS`. */ +export function underlayDictionaryHandle(): string { + return keyHandle("dictionary:acad_pdfdefinitions"); +} + +/** The handle of the dictionary variable `PDFFRAME`. */ +export function underlayFrameVariableHandle(): string { + return keyHandle("dictionary-variable:pdfframe"); +} + +/** The name of the dictionary of PDF definitions, as the leading CAD app names it. */ +export const UNDERLAY_DICTIONARY = "ACAD_PDFDEFINITIONS"; + +/** `PDFFRAME` as the drawing's frame setting holds it: 1 shows and plots, 0 neither, 2 shows. */ +export function underlayFrameValue(frame: Drawing["underlayFrame"]): 0 | 1 | 2 { + return frame === false ? 0 : frame === "screen" ? 2 : 1; +} + +/** + * The definitions of the pages a drawing's underlays show, in the order each is first met: one + * for each path and page, with `\` and `/` taken as one. Each is named by its file's name without + * its extension, then ` - ` and its page, as the leading CAD app names one, with a number in + * brackets after the file's name for a name another file took first. + */ +export function underlayDefinitions(underlays: Iterable): UnderlayDefinition[] { + const byKey = new Map(); + const taken = new Set(); + const found: UnderlayDefinition[] = []; + // The next number to try after each name taken, so many files of one name are named in time. + const next = new Map(); + for (const underlay of underlays) { + const path = underlayPathKey(underlay.path); + const page = pageOf(underlay); + const key = exactKey(`${page}|${path}`); + if (byKey.has(key)) continue; + const file = path.slice(path.lastIndexOf("/") + 1); + const dot = file.lastIndexOf("."); + const base = (dot > 0 ? file.slice(0, dot) : file) || "underlay"; + const nameOf = (stem: string) => `${stem} - ${page}`; + const baseKey = exactKey(layerKey(nameOf(base))); + let name = nameOf(base); + if (taken.has(baseKey)) { + let n = next.get(baseKey) ?? 2; + while (taken.has(exactKey(layerKey(nameOf(`${base} (${n})`))))) n++; + name = nameOf(`${base} (${n})`); + next.set(baseKey, n + 1); + } + taken.add(exactKey(layerKey(name))); + const definition: UnderlayDefinition = { + name, + path: underlay.path, + page, + handle: underlayDefinitionHandle(underlay.path, page), + }; + byKey.set(key, definition); + found.push(definition); + } + return found; +} + +/** + * Every underlay of a drawing, in the order the writers name their pages by: model space, each + * layout, then each block, each list read up to its first empty slot. + */ +export function* drawingUnderlays(drawing: Drawing): Generator { + const lists: (readonly Entity[] | undefined)[] = [ + drawing.entities, + ...filled(drawing.layouts ?? []).map((layout) => layout.entities), + ...filled(drawing.blocks ?? []).map((block) => block.entities), + ]; + for (const list of lists) { + for (const e of filled(list ?? [])) if (e.kind === "underlay") yield e; + } +} + +/** + * The three lines the leading CAD app writes where an underlay's file is missing, from the top, + * each with its baseline's start in the page's inches: one fifth of an inch high, a third apart, + * the last on the insertion point. + */ +export function missingLines(underlay: Underlay): { value: string; at: Point }[] { + const path = underlay.path.replaceAll("/", "\\"); + return [ + { value: "Missing or invalid reference", at: [0, 2 / 3] }, + { value: `File: ${path}`, at: [0, 1 / 3] }, + { value: `Sheet: ${pageOf(underlay)}`, at: [0, 0] }, + ]; +} + +/** The height of the lines of a missing file, in the page's inches. */ +export const MISSING_HEIGHT = 0.2; + +/** The fade a file means when it gives none: the leading CAD app's DXF saves no fade of 25. */ +export const UNDERLAY_FADE_DEFAULT = 25; + +/** The contrast a file means when it gives none: that app's DXF saves no contrast of 75. */ +export const UNDERLAY_CONTRAST_DEFAULT = 75; + +/** The most an underlay's fade may be, and the least its contrast, as the leading CAD app sets them. */ +export const UNDERLAY_FADE_MOST = 80; +export const UNDERLAY_CONTRAST_LEAST = 20; + +/** + * The fade, contrast and monochrome an underlay plots in. A field that is not a whole number in + * its range, which lint refuses, plots as none. + */ +export function underlayLook(underlay: Underlay): { + fade: number; + contrast: number; + monochrome: boolean; +} { + const { fade, contrast } = underlay as { fade?: unknown; contrast?: unknown }; + return { + fade: + Number.isInteger(fade) && (fade as number) >= 0 && (fade as number) <= UNDERLAY_FADE_MOST + ? (fade as number) + : 0, + contrast: + Number.isInteger(contrast) && + (contrast as number) >= UNDERLAY_CONTRAST_LEAST && + (contrast as number) <= 100 + ? (contrast as number) + : 100, + monochrome: underlay.monochrome === true, + }; +} + +/** Whether an underlay plots its page in colors other than the page's own. */ +export function underlayAdjusted(underlay: Underlay): boolean { + const { fade, contrast, monochrome } = underlayLook(underlay); + return fade !== 0 || contrast !== 100 || monochrome; +} + +/** + * Whether a picture `width` by `height` pixels has the shape of a page `size` inches, to a pixel + * along each side: some one resolution draws both sides within a pixel of the picture's. + */ +export function pictureFits( + width: number, + height: number, + size: readonly [number, number], +): boolean { + const [w, h] = size; + if (!(width > 0 && height > 0 && w > 0 && h > 0)) return false; + return Math.max((width - 1) / w, (height - 1) / h) <= Math.min((width + 1) / w, (height + 1) / h); +} + +/** + * How far the lines of a missing file may reach from the page's corner, in the drawing's units: + * each letter is held as wide as the lines are high. + */ +export function missingReach(underlay: Underlay): number { + const longest = Math.max( + "Missing or invalid reference".length, + "File: ".length + underlay.path.length, + "Sheet: ".length + pageOf(underlay).length, + ); + return (longest + 1) * MISSING_HEIGHT * Math.abs(written(underlay.scale ?? 1)); +} + +/** Where `placed` puts the page, for the plot: its corner as written and its vectors. */ +export function underlayPlacement(underlay: Underlay): { at: Point; u: Point; v: Point } { + return placed(underlay); +} diff --git a/test/format.test.ts b/test/format.test.ts index 357d7bd..2f9a10e 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -39,7 +39,7 @@ function refusal(value: unknown): readonly Diagnostic[] { return assert.fail("fromJSON took the value"); } -const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "ellipse", "spline", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader", "image", "hatch" or "wipeout"`; +const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "ellipse", "spline", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader", "image", "underlay", "hatch" or "wipeout"`; test("a drawing goes to JSON and back unchanged", () => { const drawing = sample(); diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index c41b07c..67786fd 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -147,6 +147,36 @@ export function seedFiles(): Uint8Array[] { ); curves.insert("CURVE", [10, 10]); }); + // Underlays in model space and in a block, clipped both ways, faded, with their definitions. + const underlays = createDrawing({ units: "in" }); + underlays.block("SEAL", {}, () => + underlays.underlay("seal.pdf", [0, 0], { pageSize: [2, 2], scale: 0.5, fade: 40 }), + ); + underlays.layer("A", { color: 1 }, () => { + underlays.underlay("a.pdf", [0, 0], { + pageSize: [11, 8.5], + page: "2", + scale: 0.25, + rotation: 30, + clip: [ + [0.5, 0.5], + [2, 1.5], + ], + }); + underlays.underlay("b/a.pdf", [5, 0], { + pageSize: [17, 11], + scale: 0.2, + invertClip: true, + monochrome: true, + contrast: 50, + clip: [ + [5.5, 0.5], + [7, 0.5], + [6, 2], + ], + }); + underlays.insert("SEAL", [0, 10], { scale: [2, 1] }); + }); return [ ...[ toDXF(sheet), @@ -155,6 +185,7 @@ export function seedFiles(): Uint8Array[] { toDXF(images.build()), toDXF(tables.build()), toDXF(curves.build()), + toDXF({ ...underlays.build(), underlayFrame: "screen" }), ].map((t) => encoder.encode(t)), leaderFile(), ]; diff --git a/test/shape.test.ts b/test/shape.test.ts index 994d1bd..2ccab91 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -208,6 +208,28 @@ const kinds: { id: "m", ...styled, }, + underlay: { + kind: "underlay", + layer: "0", + path: "refs/arch.pdf", + page: "2", + pageSize: [17, 11], + at: [80, 0], + scale: 0.5, + rotation: 10, + clip: [ + [81, 1], + [86, 1], + [84, 4], + ], + invertClip: true, + fade: 25, + contrast: 60, + monochrome: true, + on: true, + id: "u", + ...styled, + }, hatch: { kind: "hatch", layer: "0", @@ -500,6 +522,7 @@ const full: Required & { dxf: "R2018", linetypeScale: 2, imageFrame: false, + underlayFrame: "screen", wipeoutFrame: false, linetypes: [ { @@ -929,7 +952,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #22: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #23: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ diff --git a/test/underlays.test.ts b/test/underlays.test.ts new file mode 100644 index 0000000..140475d --- /dev/null +++ b/test/underlays.test.ts @@ -0,0 +1,267 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { deflateSync } from "node:zlib"; +import { + createDrawing, + lint, + readDXF, + toDXF, + toPDF, + toSVG, + fromPage, + toPage, + underlayColor, + underlayDefinitions, + underlayVectors, + type Drawing, + type Entity, + type ReadUnderlay, + type Underlay, +} from "../src/index.ts"; +import { storedPng } from "../src/raster.ts"; +import { pictureFits } from "../src/underlays.ts"; + +/** A page's picture: `w` by `h` pixels, a black square on a clear ground in its lower-left quarter. */ +function page(w: number, h: number): Uint8Array { + const samples = new Uint8Array(w * h * 4); + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + if (x < w / 2 && y >= h / 2) samples[(y * w + x) * 4 + 3] = 255; + } + } + return storedPng(w, h, 4, samples); +} + +const base = (entities: Entity[], more: Partial = {}): Drawing => + ({ + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities, + ...more, + }) as Drawing; + +const underlay = (more: Partial = {}): Underlay => ({ + kind: "underlay", + layer: "0", + path: "arch.pdf", + pageSize: [11, 8.5], + at: [0, 0], + ...more, +}); + +test("an underlay's rules are compile errors and runtime errors", () => { + const d = createDrawing({ units: "in" }); + // @ts-expect-error an absolute path finds no file on another machine + assert.throws(() => d.underlay("C:/plans/arch.pdf", [0, 0], { pageSize: [11, 8.5] }), /folder/); + assert.throws(() => d.underlay("arch.pdf", [0, 0], { pageSize: [11, 0] }), /pageSize/); + assert.throws(() => d.underlay("arch.pdf", [0, 0], { pageSize: [11, 8.5], page: "0" }), /page/); + assert.throws(() => d.underlay("arch.pdf", [0, 0], { pageSize: [11, 8.5], fade: 81 }), /fade/); + assert.throws( + () => d.underlay("arch.pdf", [0, 0], { pageSize: [11, 8.5], contrast: 19 }), + /contrast/, + ); + assert.throws( + () => d.underlay("arch.pdf", [0, 0], { pageSize: [11, 8.5], invertClip: true }), + /invertClip needs a clip/, + ); + assert.throws( + () => + d.underlay("arch.pdf", [0, 0], { + pageSize: [11, 8.5], + clip: [ + [1, 1], + [1, 3], + ], + }), + /page's sides/, + ); + const r12 = createDrawing({ units: "in", dxf: "R12" }); + // @ts-expect-error tsdraft writes no underlays to R12 + assert.throws(() => r12.underlay("arch.pdf", [0, 0], { pageSize: [11, 8.5] }), /R12/); + const errors = lint(base([underlay({ fade: 90, page: "x" })])).filter( + (e) => e.severity === "error", + ); + assert.deepEqual( + errors.map((e) => e.rule), + ["underlay", "underlay"], + ); +}); + +test("toDXF writes an underlay as the leading CAD app saves one, and readDXF reads it back", async () => { + const d = createDrawing({ units: "in" }) + .underlay("refs/arch.pdf", [1, 2], { + page: "2", + pageSize: [17, 11], + scale: 0.25, + rotation: -45, + clip: [ + [1.5, 2.5], + [3, 2], + ], + fade: 30, + contrast: 60, + monochrome: true, + }) + .underlay("refs\\arch.pdf", [10, 2], { page: "2", pageSize: [17, 11] }) + .build(); + const dxf = toDXF({ ...d, underlayFrame: "screen" } as Drawing); + assert.match(dxf, /\r\nPDFUNDERLAY\r\n/); + // One definition for both paths of one page. + assert.equal(dxf.match(/\r\nPDFDEFINITION\r\n/g)?.length, 2); + assert.match(dxf, /\r\n3\r\narch - 2\r\n/); + assert.match(dxf, /\r\n1\r\nrefs\\arch\.pdf\r\n2\r\n2\r\n/); + assert.match(dxf, /\r\n3\r\nPDFFRAME\r\n/); + const read = await readDXF(dxf, { geometry: true }); + const found = (read.model.entities ?? []).filter((e) => e.kind === "underlay") as ReadUnderlay[]; + assert.equal(found.length, 2); + const [first] = found; + assert.equal(first!.path, "refs\\arch.pdf"); + assert.equal(first!.page, "2"); + assert.deepEqual(first!.scale, [0.25, 0.25]); + assert.equal(first!.rotation, 315); + assert.equal(first!.fade, 30); + assert.equal(first!.contrast, 60); + assert.equal(first!.monochrome, true); + // A rectangle comes back as its top-left and bottom-right corners along the page. + const made = d.entities[0] as Underlay; + const [u, v] = underlayVectors(made); + const [p, q] = made.clip!.map((point) => toPage(made.at, u, v, point)); + const want = [ + fromPage(made.at, u, v, [Math.min(p![0], q![0]), Math.max(p![1], q![1])]), + fromPage(made.at, u, v, [Math.max(p![0], q![0]), Math.min(p![1], q![1])]), + ]; + first!.clip!.forEach((point, i) => { + assert.ok(Math.abs(point[0] - want[i]![0]) < 1e-6 && Math.abs(point[1] - want[i]![1]) < 1e-6); + }); + assert.equal(read.underlays.length, 1); + assert.equal(read.underlays[0]!.underlays, 2); + assert.equal(read.underlayFrame, "screen"); +}); + +test("pages are named by their file and page, and a file of another folder takes a number", () => { + const names = underlayDefinitions([ + underlay({ path: "a/arch.pdf" }), + underlay({ path: "a\\arch.pdf" }), + underlay({ path: "a/arch.pdf", page: "2" }), + underlay({ path: "b/arch.pdf" }), + ]).map((d) => d.name); + assert.deepEqual(names, ["arch - 1", "arch - 2", "arch (2) - 1"]); +}); + +test("the plot draws a page given, its frame by the drawing's setting, and a page not given as missing", () => { + const pictures = { "arch.pdf": { "1": page(110, 85) } }; + const shown = toSVG(base([underlay()]), { underlays: pictures }); + assert.match(shown, /Missing or invalid referenceFile: arch\.pdfSheet: 1 toSVG(base([underlay()]), { underlays: { "arch.pdf": { "1": page(100, 100) } } }), + RangeError, + ); + const sheet = { name: "S", paper: "ANSI A", viewports: [], entities: [underlay()] }; + const pdf = toPDF(base([], { layouts: [sheet] } as Partial), { + underlays: pictures, + deflate: (b) => new Uint8Array(deflateSync(b)), + } as Parameters[1]); + assert.ok(pdf.length > 0); +}); + +test("fade, contrast and monochrome give the colors the leading CAD app plots", () => { + const plain = { fade: 0, contrast: 100, monochrome: false }; + assert.deepEqual(underlayColor([255, 0, 0], plain), [255, 0, 0]); + assert.deepEqual(underlayColor([0, 0, 0], { ...plain, fade: 50 }), [128, 128, 128]); + assert.deepEqual(underlayColor([255, 0, 0], { ...plain, monochrome: true }), [128, 128, 128]); + // Contrast draws lightness toward a gray a little below the middle, keeping hue. + const [r, g, b] = underlayColor([255, 0, 0], { ...plain, contrast: 20 }); + assert.ok(r > 225 && r < 240 && g === 0 && b === 0); + const pictures = { "arch.pdf": { "1": page(110, 85) } }; + const plainSvg = toSVG(base([underlay()]), { underlays: pictures }); + const faded = toSVG(base([underlay({ fade: 40 })]), { underlays: pictures }); + assert.notEqual(plainSvg.match(/base64,[^"]*/)![0], faded.match(/base64,[^"]*/)![0]); +}); + +test("lint and the plot stay whole on underlays of hostile fields", () => { + const hostile: unknown[] = [ + { pageSize: [1e99, 1e99], scale: 1e99 }, + { pageSize: [1e-7, 1e-7] }, + { pageSize: "big" }, + { pageSize: [11, 8.5], clip: Array.from({ length: 20_000 }, (_, i) => [i, i % 7]) }, + { pageSize: [11, 8.5], clip: [[0, 0]] }, + { pageSize: [11, 8.5], clip: "none", invertClip: 1 }, + { pageSize: [11, 8.5], scale: -1, rotation: Infinity, fade: 0.5, contrast: 1e9 }, + { pageSize: [11, 8.5], page: "1".repeat(100_000), path: "a".repeat(40_000) }, + { pageSize: [11, 8.5], scale: 0 }, + { pageSize: [11, 8.5], fade: { toString: 1, valueOf: 2 }, contrast: [] }, + ]; + for (const fields of hostile) { + const drawing = base([{ ...underlay(), ...(fields as object) } as Entity]); + const found = lint(drawing); + assert.ok( + found.some((d) => d.severity === "error"), + JSON.stringify(fields).slice(0, 80), + ); + assert.throws(() => toDXF(drawing)); + // The plot draws what it can and leaves out what it cannot, never throwing but a RangeError. + try { + toSVG(drawing, { underlays: { "arch.pdf": { "1": page(11, 9) } } }); + } catch (error) { + assert.ok(error instanceof RangeError, String(error)); + } + } + // A picture that is no PNG, and pages given in the wrong shape of option, draw as missing. + for (const underlays of [ + { "arch.pdf": { "1": new Uint8Array([1, 2, 3]) } }, + { "arch.pdf": 5 }, + 7, + ]) { + const svg = toSVG(base([underlay()]), { underlays } as unknown as Parameters[1]); + assert.match(svg, /Missing or invalid reference/); + } +}); + +test("a picture fits its page when one resolution draws both sides within a pixel", () => { + // A tall schedule at 150 pixels an inch: 1237.5 by 5400, rounded up. + assert.ok(pictureFits(1238, 5400, [8.25, 36])); + assert.ok(pictureFits(110, 85, [11, 8.5])); + // A4 upright, whose width at 150 pixels an inch is 1240.2, rounded up. + assert.ok(pictureFits(1241, 1754, [595.276 / 72, 841.89 / 72])); + assert.ok(!pictureFits(100, 100, [11, 8.5])); + assert.ok(!pictureFits(1238, 5420, [8.25, 36])); +}); + +test("a view that reaches only the missing file's lines draws them", () => { + const path = "Reference Drawings/Architect - Level 1 Revision 2026-11-21 and Previous Issues.pdf"; + const svg = toSVG(base([underlay({ path })]), { view: [12, 0.28, 12.5, 0.65] }); + assert.match(svg, /Previous Issues/); +}); + +test("readDXF refuses a clip the scale puts past the doubles", async () => { + const d = createDrawing({ units: "in" }) + .underlay("arch.pdf", [0, 0], { + pageSize: [11, 8.5], + clip: [ + [1, 1], + [5, 5], + ], + }) + .build(); + const written = toDXF(d); + const at = written.indexOf("\r\nAcDbUnderlayReference\r\n"); + const dxf = + written.slice(0, at) + + written.slice(at).replace("\r\n280\r\n", "\r\n41\r\n1e308\r\n42\r\n1e308\r\n280\r\n"); + const read = await readDXF(dxf, { geometry: true }); + assert.equal((read.model.entities ?? []).filter((e) => e.kind === "underlay").length, 0); + assert.ok(JSON.stringify(read.unread).includes("PDFUNDERLAY whose clip is past the doubles")); +}); From 2e2309ce59e9208d37d9ac369862012178b449f0 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 21:33:32 -0500 Subject: [PATCH 30/35] The shape sweep runs as seven test files after the other tests Tests only: nothing in the library changes. The test that replaces every value of a full drawing with values of other types now runs as seven test files, `test/shape-sweep/share-1.test.ts` to `share-7.test.ts`, which share its cases from `test/shape-sweep.ts`. `pnpm test` runs them after the other tests. It had become the slowest test by far, since each case lints and draws the whole drawing and the drawing grows with every feature. Each case still makes every check it made before. Co-authored-by: Claude Fable 5.2 Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 11 +- cli/AGENTS.md | 2 +- package.json | 2 +- test/shape-sweep.ts | 971 +++++++++++++++++++++++++++++++ test/shape-sweep/share-1.test.ts | 3 + test/shape-sweep/share-2.test.ts | 3 + test/shape-sweep/share-3.test.ts | 3 + test/shape-sweep/share-4.test.ts | 3 + test/shape-sweep/share-5.test.ts | 3 + test/shape-sweep/share-6.test.ts | 3 + test/shape-sweep/share-7.test.ts | 3 + test/shape.test.ts | 950 +----------------------------- 12 files changed, 1014 insertions(+), 943 deletions(-) create mode 100644 test/shape-sweep.ts create mode 100644 test/shape-sweep/share-1.test.ts create mode 100644 test/shape-sweep/share-2.test.ts create mode 100644 test/shape-sweep/share-3.test.ts create mode 100644 test/shape-sweep/share-4.test.ts create mode 100644 test/shape-sweep/share-5.test.ts create mode 100644 test/shape-sweep/share-6.test.ts create mode 100644 test/shape-sweep/share-7.test.ts diff --git a/AGENTS.md b/AGENTS.md index 19d26b0..ba4e6c6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -354,8 +354,15 @@ of its own. A message shows a value from the drawing only through `shown` in `src/rules.ts`, and a diagnostic's field holds a name only when it is a string. An error about a value of the wrong type carries `item`, the path of what a reader has to leave out. - `test/shape.test.ts` replaces every field of a full drawing with values of other types, and - its drawing is typed so that a new field or entity kind is a compile error there. + `test/shape-sweep.ts` replaces every field of a full drawing with values of other types, and + its drawing is typed so that a new field or entity kind is a compile error there. Each value + runs every check on the whole drawing, so the work grows with the square of the drawing: the + test files `test/shape-sweep/share-1.test.ts` and on share the cases, and `node --test` runs + one file fewer at once than the machine has cores. `pnpm test` runs them after every other + test, in a run of their own: beside the others they fill every core for a minute, and a test + with a time limit, as in `test/bounded.test.ts`, then fails at a limit tuned to a machine + with room. Raise `SHARES` and add a file only where the machines that run the tests have the + cores for one more. - `src/read/` reads a file into a `DrawingRead`, the read model, which is not a `Drawing` and is never written back. `readDXF` reads as the bytes arrive and must never hold the whole file or a list that grows with entities past its limits, `CENSUS_LIMIT`, `BLOCK_ITEMS` and diff --git a/cli/AGENTS.md b/cli/AGENTS.md index 44fedc5..451da83 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -80,7 +80,7 @@ for an entity so the others keep their indexes. `drawing.omitted` lists what was left out, and the counts are the real drawing's. If that throws too, the build fails with `lint`'s diagnostics kept and exit code 2. A throw with no lint error is a failed build as before. - `test/shape.test.ts` in the package proves `without` gives a drawing `toSVG` draws. + `test/shape-sweep.ts` in the package proves `without` gives a drawing `toSVG` draws. - `tsdraft dev` must never present a stale or mismatched answer as current. Every file a build loads whose real path has no `node_modules` folder is watched and version-checked, wherever it is; `inProject` only places errors. A build that read a file changed since, or one file at two diff --git a/package.json b/package.json index 25b7116..f2f3ca9 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "lint": "oxlint", "fmt": "oxfmt", "fmt:check": "oxfmt --check", - "test": "pnpm build:lib && node --test test/*.test.ts cli/test/*.test.ts", + "test": "pnpm build:lib && node --test test/*.test.ts cli/test/*.test.ts && node --test test/shape-sweep/*.test.ts", "test:package": "node scripts/package-smoke.ts", "example": "node examples/site-plan.ts && node examples/outdoor-kitchen.ts && node examples/plan-set/set.ts", "readme:drawing": "node scripts/readme-drawing.ts", diff --git a/test/shape-sweep.ts b/test/shape-sweep.ts new file mode 100644 index 0000000..fe0797f --- /dev/null +++ b/test/shape-sweep.ts @@ -0,0 +1,971 @@ +import assert from "node:assert/strict"; +import { basename } from "node:path"; +import { test } from "node:test"; +import { inspect } from "node:util"; +import { Script } from "node:vm"; +import { without } from "../cli/src/omit.ts"; +import { + BUILT_IN_STANDARD, + defineStandard, + DrawingError, + fromJSON, + lint, + toDXF, + toJSON, + toSVG, + type ParagraphAttributeDefinition, + type TextAttributeDefinition, + type Block, + type Diagnostic, + type DimensionStyle, + type Drawing, + type Entity, + type Layer, + type Layout, + type LeaderStyle, + type TableCellStyle, + type TableStyle, + type Hatch, + type HatchPattern, + type Linetype, + type PatternLine, + type Leader, + type Polyline, + type TextStyle, + type Viewport, + type Xref, + type FitSpline, +} from "../src/index.ts"; +import { timeLimit } from "./time-limit.ts"; + +const styled = { + linetype: "DD", + lineweight: 0.25, + color: [10, 200, 30], + transparency: 50, +} as const; +const justified = { style: "NOTES", align: "center", valign: "middle" } as const; + +/** + * Each kind of entity with every field it can have: a field left out is a compile error. A + * polyline has a width or widths for each side, and `wide` has the other. A leader has a note, + * and `keyed` a block in its place. A hatch has a pattern, and `shaded` and `tinted` a gradient. + */ +export const kinds: { + readonly [K in Entity["kind"]]: K extends "polyline" + ? Required> + : K extends "leader" + ? Required> + : K extends "hatch" + ? Required> + : Required>; +} = { + line: { kind: "line", layer: "WALL", from: [0, 0], to: [10, 0], id: "a", ...styled }, + polyline: { + kind: "polyline", + layer: "0", + points: [ + [0, 0], + [10, 0], + [10, 5], + ], + closed: true, + bulges: [0, 0.5, -1], + widths: [ + [0, 1], + [1, 1], + [0.5, 0], + ], + linetypeGeneration: true, + id: "b", + ...styled, + }, + circle: { kind: "circle", layer: "0", center: [5, 5], radius: 2, id: "c", ...styled }, + arc: { + kind: "arc", + layer: "0", + center: [5, 5], + radius: 3, + startAngle: 0, + endAngle: 90, + id: "d", + ...styled, + }, + text: { + kind: "text", + layer: "0", + at: [0, 4], + height: 1, + rotation: 0, + value: "T-0", + id: "e", + ...styled, + ...justified, + }, + paragraph: { + kind: "paragraph", + layer: "0", + at: [0, 8], + height: 0.5, + rotation: 15, + value: 'ALL WORK SHALL {\\LCOMPLY}\\P3\\S1/2;" GAP', + width: 6, + style: "NOTES", + align: "center", + valign: "bottom", + lineSpacing: 1.5, + lineSpacingStyle: "exactly", + columns: { height: 4, count: 2, gutter: 0.5 }, + // A paragraph in columns takes no mask; a leader's note has one of every field. + mask: false, + id: "k", + ...styled, + }, + insert: { + kind: "insert", + color: "ByBlock", + transparency: "ByBlock", + layer: "0", + block: "TREE", + at: [20, 0], + id: "f", + scale: [2, 2], + rotation: 30, + attributes: { TAG: "T-1" }, + }, + "linear-dimension": { + kind: "linear-dimension", + color: 1, + transparency: 40, + layer: "0", + style: "DIMS", + from: [0, 0], + to: [30, 10], + line: [0, -6], + angle: 15, + text: "<> TYP", + textBelow: "CLR.", + id: "g", + }, + "aligned-dimension": { + kind: "aligned-dimension", + color: [200, 100, 50], + transparency: "ByLayer", + layer: "0", + style: "DIMS", + from: [0, 0], + to: [30, 10], + offset: 8, + text: "VARIES", + textBelow: "<> O.C.", + id: "h", + }, + leader: { + kind: "leader", + color: 255, + transparency: 0, + layer: "0", + style: "NOTE", + text: ["NOTE", "SECOND LINE"], + at: [40, 10], + shafts: [ + [[35, 5]], + [ + [36, 2], + [38, 4], + ], + ], + side: "right", + attachment: "last-line", + verticalAttachment: "line", + width: 2, + frame: true, + mask: { color: 1, offsetFactor: 1.25 }, + shaft: "curved", + farShafts: [[[45, 5]]], + textStyle: "NOTES", + textHeight: 0.08, + arrowSize: 0.05, + landing: 0.1, + gap: 0.02, + id: "i", + }, + image: { + kind: "image", + layer: "0", + path: "images/aerial.png", + pixels: [400, 200], + at: [50, 0], + width: 20, + height: 10, + rotation: 15, + clip: [ + [52, 2], + [60, 1], + [58, 8], + ], + invertClip: true, + transparent: true, + id: "m", + ...styled, + }, + underlay: { + kind: "underlay", + layer: "0", + path: "refs/arch.pdf", + page: "2", + pageSize: [17, 11], + at: [80, 0], + scale: 0.5, + rotation: 10, + clip: [ + [81, 1], + [86, 1], + [84, 4], + ], + invertClip: true, + fade: 25, + contrast: 60, + monochrome: true, + on: true, + id: "u", + ...styled, + }, + hatch: { + kind: "hatch", + layer: "0", + loops: [ + { + points: [ + [70, 0], + [80, 0], + [80, 10], + ], + bulges: [0, 0.5, 0], + }, + ], + pattern: { name: "STRIPES", scale: 2, angle: 30, origin: [1, 1] }, + id: "w1", + ...styled, + }, + wipeout: { + kind: "wipeout", + layer: "0", + points: [ + [90, 0], + [95, 0], + [92, 4], + ], + id: "w2", + ...styled, + }, + ellipse: { + kind: "ellipse", + layer: "0", + center: [100, 5], + majorAxis: [4, 1], + ratio: 0.5, + startParameter: 30, + endParameter: 270, + id: "w6", + ...styled, + }, + // A spline by its control points; `fitted` is one through fit points. + spline: { + kind: "spline", + layer: "0", + controlPoints: [ + [110, 0], + [112, 4], + ], + degree: 1, + knots: [0, 0, 1, 1], + weights: [1, 2], + closed: false, + id: "w7", + ...styled, + }, + "radius-dimension": { + kind: "radius-dimension", + color: 7, + transparency: 90, + layer: "0", + style: "ARCH", + center: [0, 0], + point: [3, 4], + text: "<> TYP", + textBelow: "MIN.", + textFromCenter: 2, + id: "h-r", + }, + "diameter-dimension": { + kind: "diameter-dimension", + color: [0, 0, 0], + transparency: 25, + layer: "0", + style: "ARCH", + center: [0, 0], + point: [-3, 4], + text: "<> BOLT", + textBelow: "EQ.", + textFromCenter: -1, + id: "h-d", + }, + "jogged-radius-dimension": { + kind: "jogged-radius-dimension", + color: 8, + transparency: "ByBlock", + layer: "0", + style: "ARCH", + center: [0, 0], + point: [30, 40], + start: [25, 20], + jog: [27, 30], + text: "<> CL", + textBelow: "CURB", + id: "h-j", + }, + "arc-length-dimension": { + kind: "arc-length-dimension", + color: "ByLayer", + transparency: 10, + layer: "0", + style: "ARCH", + center: [0, 0], + radius: 10, + startAngle: 30, + endAngle: 120, + at: [0, 12], + text: "<> TYP", + textBelow: "MIN.", + id: "h-l", + }, + "angular-dimension": { + kind: "angular-dimension", + color: 250, + transparency: 75, + layer: "0", + style: "ARCH", + vertex: [0, 0], + from: [10, 0], + to: [0, 10], + at: [7, 7], + text: "<> TYP", + textBelow: "MIN.", + id: "h-a", + }, + table: { + kind: "table", + color: "ByLayer", + transparency: "ByLayer", + layer: "0", + style: "SCHEDULE", + at: [100, 20], + rotation: 0, + columns: [1, 2], + title: "DOORS", + titleHeight: 0.4, + header: [ + { text: "MARK", align: "left", valign: "bottom", textHeight: 0.1, color: 1, fill: 2 }, + "SIZE", + ], + headerHeight: 0.3, + rows: [ + [{ block: "TREE", blockScale: 0.5, columnSpan: 2, rowSpan: 2 }, null], + [null, null], + ], + rowHeights: [0.5, null], + id: "tb", + }, + "ordinate-dimension": { + kind: "ordinate-dimension", + color: [40, 160, 220], + transparency: 50, + layer: "0", + style: "ARCH", + axis: "x", + origin: [1, 2], + feature: [10, 5], + leaderEnd: [10, 15], + text: "<> TYP", + textBelow: "MIN.", + id: "h-o", + }, +}; + +/** A polyline of one width, with every field the polyline of `kinds` leaves out. */ +const wide: Required> = { + kind: "polyline", + layer: "0", + points: kinds.polyline.points, + closed: false, + bulges: [0.25, 0], + width: 0.25, + linetypeGeneration: true, + id: "j", + ...styled, +}; + +/** A hatch with a gradient of two colors, with every field the hatch of `kinds` leaves out. */ +const shaded: Required> = { + kind: "hatch", + layer: "0", + loops: kinds.hatch.loops, + gradient: { + name: "spherical", + angle: 30, + centered: false, + colors: [ + [200, 40, 30], + [20, 90, 180], + ], + }, + id: "w3", + ...styled, +}; + +/** A hatch with a gradient of one color and its tint. */ +const tinted: Required> = { + kind: "hatch", + layer: "0", + loops: kinds.hatch.loops, + gradient: { + name: "inverted-curved", + angle: 200, + centered: true, + color: [30, 120, 200], + tint: 0.4, + }, + id: "w4", + ...styled, +}; + +/** A spline through fit points, with every field one can have. */ +const fitted: Required = { + kind: "spline", + layer: "0", + fitPoints: [ + [120, 0], + [124, 3], + ], + startTangent: [0, 1], + endTangent: [1, 0], + closed: false, + id: "w5", + ...styled, +}; + +const keyed: Required< + Omit< + Leader, + | "text" + | "attachment" + | "verticalAttachment" + | "width" + | "frame" + | "mask" + | "textStyle" + | "textHeight" + > +> = { + kind: "leader", + color: "ByBlock", + transparency: 20, + layer: "0", + style: "NOTE", + block: "TREE", + attributes: { TAG: "T-2" }, + at: [60, 10], + shafts: [[[55, 5]]], + side: "right", + shaft: "straight", + farShafts: [[[65, 5]]], + arrowSize: 0.05, + landing: 0.1, + gap: 0.02, + id: "keyed", +}; + +/** One of everything an R2018 drawing can hold, with every field of every object. */ +export const full: Required & { + readonly linetypes: readonly [Required, Required]; + readonly patterns: readonly [ + Required & { readonly lines: readonly [Required] }, + ]; + readonly textStyles: readonly [Required]; + // A style in decimal units leaves zeros out, and one in architectural units writes them. + readonly dimensionStyles: readonly [ + Required>, + Required>, + ]; + readonly leaderStyles: readonly [Required]; + readonly tableStyles: readonly [ + Required & { readonly data: Required }, + ]; + readonly layers: readonly [Layer, Required]; + readonly blocks: readonly [ + Block, + Required & { + readonly attributes: readonly [ + Required, + Required, + ]; + }, + ]; + readonly xrefs: readonly [Required]; + readonly layouts: readonly [ + Required & { readonly viewports: readonly [Required] }, + Layout, + ]; +} = { + format: 0, + units: "ft", + dxf: "R2018", + linetypeScale: 2, + imageFrame: false, + underlayFrame: "screen", + wipeoutFrame: false, + linetypes: [ + { + name: "DD", + description: "Dash dot", + pattern: [0.5, -0.25, 0, -0.25], + marks: [ + { + after: 1, + text: "W", + style: "Standard", + height: 0.1, + rotation: 0, + orient: "upright", + offset: [0, -0.05], + }, + ], + }, + // A linetype of shapes that nothing draws in, which lint does not warn of. + { + name: "SHAPES", + description: "Shapes", + pattern: [0.5, -0.25], + marks: [ + { + after: 1, + shape: 3, + file: "shapes.shx", + scale: 0.1, + rotation: 0, + orient: "relative", + offset: [0, 0], + }, + ], + }, + ], + patterns: [ + { + name: "STRIPES", + description: "Dashed stripes", + lines: [{ angle: 45, base: [0, 0], offset: [0, 0.25], dashes: [0.5, -0.25, 0, -0.25] }], + }, + ], + textStyles: [{ name: "NOTES", font: "Arial", widthFactor: 0.9, obliqueAngle: 10 }], + dimensionStyles: [ + { + name: "DIMS", + textStyle: "NOTES", + textHeight: 0.1, + arrowhead: "architectural-tick", + arrowSize: 0.1, + extensionOffset: 0.05, + extensionBeyond: 0.1, + textGap: 0.05, + scale: 10, + precision: 2, + prefix: "L ", + suffix: "'", + units: "decimal", + suppressZeros: "trailing", + measurementScale: 2, + textPlacement: "centered", + textFit: "leader", + dimensionLineweight: 0.5, + extensionLineweight: 0.25, + radialText: "horizontal", + jogAngle: 30, + angleUnits: "degrees-minutes-seconds", + anglePrecision: 4, + suppressAngleZeros: "leading", + textMask: { color: 3 }, + arcSymbol: "above", + }, + { + name: "ARCH", + textStyle: "NOTES", + textHeight: 0.1, + arrowhead: "architectural-tick", + arrowSize: 0.1, + extensionOffset: 0.05, + extensionBeyond: 0.1, + textGap: 0.05, + scale: 10, + precision: 4, + prefix: "", + suffix: "", + units: "architectural", + feetInchZeros: "both", + measurementScale: 12, + fraction: "stacked", + fractionScale: 0.75, + textPlacement: "above", + textFit: "inside", + dimensionLineweight: 0.35, + extensionLineweight: 0.18, + radialText: "aligned", + jogAngle: 45, + angleUnits: "degrees", + anglePrecision: 0, + suppressAngleZeros: "both", + textMask: true, + arcSymbol: "none", + }, + ], + leaderStyles: [ + { + name: "NOTE", + textStyle: "NOTES", + textHeight: 0.1, + arrowhead: "dot", + arrowSize: 0.1, + landing: 0.1, + gap: 0.05, + attachment: "first-line", + direction: "vertical", + verticalAttachment: "line", + frame: true, + shaft: "curved", + block: "TREE", + blockConnection: "insertion", + blockScale: 2, + scale: 10, + }, + ], + tableStyles: [ + { + name: "SCHEDULE", + textStyle: "NOTES", + textHeight: 0.1, + horizontalMargin: 0.03, + verticalMargin: 0.02, + title: { textHeight: 0.15 }, + header: { fill: 8 }, + data: { + textStyle: "NOTES", + textHeight: 0.08, + align: "left", + valign: "middle", + color: 3, + fill: 9, + lineweight: 0.25, + }, + }, + ], + layers: [ + { name: "0", color: 7 }, + { + name: "WALL", + color: 1, + linetype: "DD", + lineweight: 0.5, + off: false, + frozen: false, + locked: true, + plot: false, + }, + ], + blocks: [ + { name: "LEAF", entities: [{ kind: "circle", layer: "0", center: [0, 0], radius: 1 }] }, + { + name: "TREE", + base: [1, 2], + attributes: [ + { + kind: "text", + tag: "TAG", + prompt: "Tree tag", + value: "T-0", + layer: "0", + at: [0, 4], + height: 1, + rotation: 0, + ...justified, + }, + { + kind: "paragraph", + tag: "NOTE", + prompt: "Note", + value: "PLANT IN\\PSPRING", + layer: "0", + at: [0, -4], + height: 0.5, + rotation: 0, + style: "NOTES", + width: 6, + align: "center", + valign: "middle", + lineSpacing: 1.5, + lineSpacingStyle: "exactly", + }, + ], + entities: [ + { kind: "arc", layer: "0", center: [0, 0], radius: 3, startAngle: 0, endAngle: 90 }, + { kind: "insert", layer: "0", block: "LEAF", at: [1, 1] }, + ], + }, + ], + xrefs: [{ name: "BASE", path: "base.dwg", attach: true }], + entities: [ + ...Object.values(kinds), + { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }, + wide, + keyed, + fitted, + shaded, + tinted, + ], + layouts: [ + { + name: "C-101", + paper: "ARCH D", + plotStyle: "acad.ctb", + viewports: [ + { + id: "view", + layer: "WALL", + corner: [1, 1], + width: 20, + height: 10, + center: [5, 2], + ratio: 12, + frozenLayers: ["WALL"], + twist: 30, + }, + ], + // One of each kind of entity on the sheet, each with an id of its own. + entities: Object.values(kinds).map((entity) => ({ ...entity, id: `sheet-${entity.id}` })), + }, + { name: "Blank", paper: "ANSI B", viewports: [], entities: [] }, + ], +}; + +/** What an R12 drawing can hold. */ +export const r12: Drawing = { + format: 0, + units: "ft", + dxf: "R12", + layers: [{ name: "0", color: 7 }], + entities: [ + { kind: "line", layer: "0", from: [0, 0], to: [10, 0], id: "a" }, + { + kind: "polyline", + layer: "0", + points: kinds.polyline.points, + closed: true, + id: "b", + linetype: "ByLayer", + lineweight: "ByLayer", + }, + { kind: "circle", layer: "0", center: [5, 5], radius: 2 }, + { kind: "arc", layer: "0", center: [5, 5], radius: 3, startAngle: 0, endAngle: 90 }, + { kind: "text", layer: "0", at: [0, 4], height: 1, rotation: 0, value: "T-0" }, + ], +}; + +export type Path = readonly (string | number)[]; + +/** Every path to a value in `value`, at every depth. */ +function paths(value: unknown, at: Path = []): Path[] { + if (typeof value !== "object" || value === null) return []; + return Object.keys(value).flatMap((key) => { + const step = [...at, Array.isArray(value) ? Number(key) : key]; + return [step, ...paths((value as Record)[key], step)]; + }); +} + +export const HOLE = Symbol("an empty slot"); + +/** A copy of `drawing` with the value at `path` replaced, or its slot emptied for `HOLE`. */ +export function replaced(drawing: unknown, path: Path, value: unknown): unknown { + if (path.length === 0) return value; + const copy = structuredClone(drawing) as Record; + let parent = copy; + for (const step of path.slice(0, -1)) parent = parent[step] as typeof parent; + if (value === HOLE) delete parent[path.at(-1)!]; + else parent[path.at(-1)!] = value; + return copy; +} + +const at = (drawing: unknown, path: Path): unknown => + path.reduce((value, step) => (value as Record)[step], drawing); + +const circular: Record = {}; +circular.self = circular; +const wrong = [undefined, null, 5, "x", {}, [], 1n, circular, { toString: 0 }]; + +/** The values to put in place of the one at `path`. */ +function replacements(drawing: unknown, path: Path): unknown[] { + const parent = at(drawing, path.slice(0, -1)); + const value = at(drawing, path); + return [ + ...wrong, + ...(Array.isArray(value) ? [[null], new Array(2)] : []), + ...(typeof value === "number" ? [0, -1, NaN, Infinity] : []), + ...(Array.isArray(parent) ? [HOLE] : []), + // The same value with a field nobody knows. + ...(typeof value === "object" && !Array.isArray(value) ? [{ ...value, zz: 1 }] : []), + ]; +} + +/** + * A standard whose title block is the full drawing's block `TREE` on its sheet, so that `lint` + * walks every rule of a standard over the drawing, its title block and its fields among them. + */ +const treeStandard = defineStandard({ + id: "tree", + version: "1", + paperUnits: "in", + minTextHeight: 0.05, + layers: { WALL: { color: 1 } }, + textRoles: { note: { font: "Arial", height: 0.1 } }, + titleBlocks: { + tree: { + paper: "ARCH D", + block: { + format: 0, + units: "in", + dxf: "R2018", + layers: [{ name: "0", color: 7 }], + entities: [], + textStyles: full.textStyles, + blocks: full.blocks, + }, + blockName: "TREE", + layer: "WALL", + drawingArea: [0.5, 0.5, 35.5, 23.5], + fields: { TAG: { box: [1, 1, 2, 2] } }, + }, + }, + sheetFormats: { d: { paper: "ARCH D", titleBlock: "tree" } }, +}); + +export const errors = (drawing: Drawing, version?: "R12" | "R2018") => + lint(drawing, version ? { version } : {}).filter((d) => d.severity === "error"); + +/** + * Runs `toSVG` for model space and for each layout, as the command does, and stops it after a + * second, so a drawing that never finishes fails the test. + */ +const draw = new Script( + "toSVG(drawing); if (Array.isArray(drawing?.layouts)) for (const layout of drawing.layouts) toSVG(drawing, { layout: layout.name });", +); +Object.assign(globalThis, { toSVG }); + +/** What `toSVG` does with a drawing: the error it throws, or undefined when it draws it. */ +function drawn(drawing: Drawing): unknown { + Object.assign(globalThis, { drawing }); + try { + draw.runInThisContext({ timeout: timeLimit(1000) }); + return undefined; + } catch (thrown) { + return thrown; + } +} + +const hung = (thrown: unknown): boolean => + (thrown as { code?: unknown } | null)?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT"; + +/** + * Says what `lint` does wrong with a value: it must return, `toSVG` must return or throw in a + * second, a value `lint` reports no error for must be one the writers, `toSVG` and `fromJSON` + * take, and a drawing it reports an error for must be one `toSVG` draws, at least once the + * items the errors name are left out. + */ +function failure(value: unknown): string | undefined { + const drawing = value as Drawing; + let found: Diagnostic[]; + try { + for (const version of ["R12", "R2018"] as const) errors(drawing, version); + lint(drawing, { standard: BUILT_IN_STANDARD }); + lint(drawing, { standard: treeStandard }); + found = errors(drawing); + } catch (thrown) { + return `lint threw ${String(thrown)}`; + } + const refused = drawn(drawing); + if (hung(refused)) return "toSVG does not finish"; + if (found.length > 0) { + // A writer refuses what `lint` reports before it reads the drawing. + try { + toDXF(drawing); + return "lint reports an error, and toDXF writes the drawing"; + } catch (thrown) { + if (!(thrown instanceof DrawingError)) { + return `lint reports an error, and toDXF throws ${String(thrown).split("\n", 1)[0]}`; + } + } + // The command asks for a drawing with a list of layers and one of entities before it lints. + if (!Array.isArray(drawing?.layers) || !Array.isArray(drawing.entities)) return undefined; + if (refused === undefined) return undefined; + const rest = drawn(without(drawing, new Set(found.flatMap((d) => d.item ?? [])))); + return rest === undefined + ? undefined + : `it cannot be drawn without what lint names: ${String(rest).split("\n", 1)[0]}`; + } + try { + if (refused !== undefined) throw refused; + toDXF(drawing); + fromJSON(toJSON(drawing)); + fromJSON(structuredClone(value)); + } catch (thrown) { + return `lint reports no error, and then: ${String(thrown).split("\n", 1)[0]}`; + } + return undefined; +} + +/** + * How many test files share the sweep. `node --test` runs each file in a process of its own, and + * one file fewer at once than the machine has cores: 7 is what 8 cores run at once. + */ +export const SHARES = 7; + +type Case = { drawing: Drawing; path: Path; value: unknown; count: number }; + +/** Every case of the sweep: each value put in place of each value of both drawings, counted. */ +export function* cases(): Generator { + let count = 0; + for (const drawing of [full, r12]) { + for (const path of [[], ...paths(drawing)]) { + for (const value of replacements(drawing, path)) + yield { drawing, path, value, count: count++ }; + } + } +} + +/** + * One test file's share of the sweep: the file `shape-sweep/share-N.test.ts` takes each case + * whose count leaves N - 1 when divided by `SHARES`. So the files together take every case once. + */ +export function sweep(file: string): void { + const share = Number(/^share-(\d+)\.test\.ts$/.exec(basename(file))?.[1]); + const name = + "lint returns for every value of the wrong type, with an error for what cannot be written"; + test(`${name}: share ${share} of ${SHARES}`, () => { + assert.ok(share >= 1 && share <= SHARES, `${file} is no share of the sweep`); + const failures: string[] = []; + for (const { drawing, path, value, count } of cases()) { + if (count % SHARES !== share - 1) continue; + const found = failure(replaced(drawing, path, value)); + const shown = inspect(value, { depth: 0, breakLength: Infinity }); + if (found) failures.push(`${drawing.dxf} ${path.join(".")} = ${shown}: ${found}`); + } + assert.deepEqual(failures, []); + }); +} diff --git a/test/shape-sweep/share-1.test.ts b/test/shape-sweep/share-1.test.ts new file mode 100644 index 0000000..4ab2f29 --- /dev/null +++ b/test/shape-sweep/share-1.test.ts @@ -0,0 +1,3 @@ +import { sweep } from "../shape-sweep.ts"; + +sweep(import.meta.filename); diff --git a/test/shape-sweep/share-2.test.ts b/test/shape-sweep/share-2.test.ts new file mode 100644 index 0000000..4ab2f29 --- /dev/null +++ b/test/shape-sweep/share-2.test.ts @@ -0,0 +1,3 @@ +import { sweep } from "../shape-sweep.ts"; + +sweep(import.meta.filename); diff --git a/test/shape-sweep/share-3.test.ts b/test/shape-sweep/share-3.test.ts new file mode 100644 index 0000000..4ab2f29 --- /dev/null +++ b/test/shape-sweep/share-3.test.ts @@ -0,0 +1,3 @@ +import { sweep } from "../shape-sweep.ts"; + +sweep(import.meta.filename); diff --git a/test/shape-sweep/share-4.test.ts b/test/shape-sweep/share-4.test.ts new file mode 100644 index 0000000..4ab2f29 --- /dev/null +++ b/test/shape-sweep/share-4.test.ts @@ -0,0 +1,3 @@ +import { sweep } from "../shape-sweep.ts"; + +sweep(import.meta.filename); diff --git a/test/shape-sweep/share-5.test.ts b/test/shape-sweep/share-5.test.ts new file mode 100644 index 0000000..4ab2f29 --- /dev/null +++ b/test/shape-sweep/share-5.test.ts @@ -0,0 +1,3 @@ +import { sweep } from "../shape-sweep.ts"; + +sweep(import.meta.filename); diff --git a/test/shape-sweep/share-6.test.ts b/test/shape-sweep/share-6.test.ts new file mode 100644 index 0000000..4ab2f29 --- /dev/null +++ b/test/shape-sweep/share-6.test.ts @@ -0,0 +1,3 @@ +import { sweep } from "../shape-sweep.ts"; + +sweep(import.meta.filename); diff --git a/test/shape-sweep/share-7.test.ts b/test/shape-sweep/share-7.test.ts new file mode 100644 index 0000000..4ab2f29 --- /dev/null +++ b/test/shape-sweep/share-7.test.ts @@ -0,0 +1,3 @@ +import { sweep } from "../shape-sweep.ts"; + +sweep(import.meta.filename); diff --git a/test/shape.test.ts b/test/shape.test.ts index 2ccab91..25e3be1 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -1,947 +1,19 @@ import assert from "node:assert/strict"; +import { readdirSync } from "node:fs"; +import { join } from "node:path"; import { test } from "node:test"; -import { inspect } from "node:util"; -import { Script } from "node:vm"; -import { without } from "../cli/src/omit.ts"; -import { - BUILT_IN_STANDARD, - defineStandard, - DrawingError, - fromJSON, - lint, - toDXF, - toJSON, - toSVG, - type ParagraphAttributeDefinition, - type TextAttributeDefinition, - type Block, - type Diagnostic, - type DimensionStyle, - type Drawing, - type Entity, - type Layer, - type Layout, - type LeaderStyle, - type TableCellStyle, - type TableStyle, - type Hatch, - type HatchPattern, - type Linetype, - type PatternLine, - type Leader, - type Polyline, - type TextStyle, - type Viewport, - type Xref, - type FitSpline, -} from "../src/index.ts"; -import { timeLimit } from "./time-limit.ts"; +import { fromJSON, lint, toJSON, type Drawing } from "../src/index.ts"; +import { errors, full, HOLE, kinds, r12, replaced, SHARES, type Path } from "./shape-sweep.ts"; -const styled = { - linetype: "DD", - lineweight: 0.25, - color: [10, 200, 30], - transparency: 50, -} as const; -const justified = { style: "NOTES", align: "center", valign: "middle" } as const; - -/** - * Each kind of entity with every field it can have: a field left out is a compile error. A - * polyline has a width or widths for each side, and `wide` has the other. A leader has a note, - * and `keyed` a block in its place. A hatch has a pattern, and `shaded` and `tinted` a gradient. - */ -const kinds: { - readonly [K in Entity["kind"]]: K extends "polyline" - ? Required> - : K extends "leader" - ? Required> - : K extends "hatch" - ? Required> - : Required>; -} = { - line: { kind: "line", layer: "WALL", from: [0, 0], to: [10, 0], id: "a", ...styled }, - polyline: { - kind: "polyline", - layer: "0", - points: [ - [0, 0], - [10, 0], - [10, 5], - ], - closed: true, - bulges: [0, 0.5, -1], - widths: [ - [0, 1], - [1, 1], - [0.5, 0], - ], - linetypeGeneration: true, - id: "b", - ...styled, - }, - circle: { kind: "circle", layer: "0", center: [5, 5], radius: 2, id: "c", ...styled }, - arc: { - kind: "arc", - layer: "0", - center: [5, 5], - radius: 3, - startAngle: 0, - endAngle: 90, - id: "d", - ...styled, - }, - text: { - kind: "text", - layer: "0", - at: [0, 4], - height: 1, - rotation: 0, - value: "T-0", - id: "e", - ...styled, - ...justified, - }, - paragraph: { - kind: "paragraph", - layer: "0", - at: [0, 8], - height: 0.5, - rotation: 15, - value: 'ALL WORK SHALL {\\LCOMPLY}\\P3\\S1/2;" GAP', - width: 6, - style: "NOTES", - align: "center", - valign: "bottom", - lineSpacing: 1.5, - lineSpacingStyle: "exactly", - columns: { height: 4, count: 2, gutter: 0.5 }, - // A paragraph in columns takes no mask; a leader's note has one of every field. - mask: false, - id: "k", - ...styled, - }, - insert: { - kind: "insert", - color: "ByBlock", - transparency: "ByBlock", - layer: "0", - block: "TREE", - at: [20, 0], - id: "f", - scale: [2, 2], - rotation: 30, - attributes: { TAG: "T-1" }, - }, - "linear-dimension": { - kind: "linear-dimension", - color: 1, - transparency: 40, - layer: "0", - style: "DIMS", - from: [0, 0], - to: [30, 10], - line: [0, -6], - angle: 15, - text: "<> TYP", - textBelow: "CLR.", - id: "g", - }, - "aligned-dimension": { - kind: "aligned-dimension", - color: [200, 100, 50], - transparency: "ByLayer", - layer: "0", - style: "DIMS", - from: [0, 0], - to: [30, 10], - offset: 8, - text: "VARIES", - textBelow: "<> O.C.", - id: "h", - }, - leader: { - kind: "leader", - color: 255, - transparency: 0, - layer: "0", - style: "NOTE", - text: ["NOTE", "SECOND LINE"], - at: [40, 10], - shafts: [ - [[35, 5]], - [ - [36, 2], - [38, 4], - ], - ], - side: "right", - attachment: "last-line", - verticalAttachment: "line", - width: 2, - frame: true, - mask: { color: 1, offsetFactor: 1.25 }, - shaft: "curved", - farShafts: [[[45, 5]]], - textStyle: "NOTES", - textHeight: 0.08, - arrowSize: 0.05, - landing: 0.1, - gap: 0.02, - id: "i", - }, - image: { - kind: "image", - layer: "0", - path: "images/aerial.png", - pixels: [400, 200], - at: [50, 0], - width: 20, - height: 10, - rotation: 15, - clip: [ - [52, 2], - [60, 1], - [58, 8], - ], - invertClip: true, - transparent: true, - id: "m", - ...styled, - }, - underlay: { - kind: "underlay", - layer: "0", - path: "refs/arch.pdf", - page: "2", - pageSize: [17, 11], - at: [80, 0], - scale: 0.5, - rotation: 10, - clip: [ - [81, 1], - [86, 1], - [84, 4], - ], - invertClip: true, - fade: 25, - contrast: 60, - monochrome: true, - on: true, - id: "u", - ...styled, - }, - hatch: { - kind: "hatch", - layer: "0", - loops: [ - { - points: [ - [70, 0], - [80, 0], - [80, 10], - ], - bulges: [0, 0.5, 0], - }, - ], - pattern: { name: "STRIPES", scale: 2, angle: 30, origin: [1, 1] }, - id: "w1", - ...styled, - }, - wipeout: { - kind: "wipeout", - layer: "0", - points: [ - [90, 0], - [95, 0], - [92, 4], - ], - id: "w2", - ...styled, - }, - ellipse: { - kind: "ellipse", - layer: "0", - center: [100, 5], - majorAxis: [4, 1], - ratio: 0.5, - startParameter: 30, - endParameter: 270, - id: "w6", - ...styled, - }, - // A spline by its control points; `fitted` is one through fit points. - spline: { - kind: "spline", - layer: "0", - controlPoints: [ - [110, 0], - [112, 4], - ], - degree: 1, - knots: [0, 0, 1, 1], - weights: [1, 2], - closed: false, - id: "w7", - ...styled, - }, - "radius-dimension": { - kind: "radius-dimension", - color: 7, - transparency: 90, - layer: "0", - style: "ARCH", - center: [0, 0], - point: [3, 4], - text: "<> TYP", - textBelow: "MIN.", - textFromCenter: 2, - id: "h-r", - }, - "diameter-dimension": { - kind: "diameter-dimension", - color: [0, 0, 0], - transparency: 25, - layer: "0", - style: "ARCH", - center: [0, 0], - point: [-3, 4], - text: "<> BOLT", - textBelow: "EQ.", - textFromCenter: -1, - id: "h-d", - }, - "jogged-radius-dimension": { - kind: "jogged-radius-dimension", - color: 8, - transparency: "ByBlock", - layer: "0", - style: "ARCH", - center: [0, 0], - point: [30, 40], - start: [25, 20], - jog: [27, 30], - text: "<> CL", - textBelow: "CURB", - id: "h-j", - }, - "arc-length-dimension": { - kind: "arc-length-dimension", - color: "ByLayer", - transparency: 10, - layer: "0", - style: "ARCH", - center: [0, 0], - radius: 10, - startAngle: 30, - endAngle: 120, - at: [0, 12], - text: "<> TYP", - textBelow: "MIN.", - id: "h-l", - }, - "angular-dimension": { - kind: "angular-dimension", - color: 250, - transparency: 75, - layer: "0", - style: "ARCH", - vertex: [0, 0], - from: [10, 0], - to: [0, 10], - at: [7, 7], - text: "<> TYP", - textBelow: "MIN.", - id: "h-a", - }, - table: { - kind: "table", - color: "ByLayer", - transparency: "ByLayer", - layer: "0", - style: "SCHEDULE", - at: [100, 20], - rotation: 0, - columns: [1, 2], - title: "DOORS", - titleHeight: 0.4, - header: [ - { text: "MARK", align: "left", valign: "bottom", textHeight: 0.1, color: 1, fill: 2 }, - "SIZE", - ], - headerHeight: 0.3, - rows: [ - [{ block: "TREE", blockScale: 0.5, columnSpan: 2, rowSpan: 2 }, null], - [null, null], - ], - rowHeights: [0.5, null], - id: "tb", - }, - "ordinate-dimension": { - kind: "ordinate-dimension", - color: [40, 160, 220], - transparency: 50, - layer: "0", - style: "ARCH", - axis: "x", - origin: [1, 2], - feature: [10, 5], - leaderEnd: [10, 15], - text: "<> TYP", - textBelow: "MIN.", - id: "h-o", - }, -}; - -/** A polyline of one width, with every field the polyline of `kinds` leaves out. */ -const wide: Required> = { - kind: "polyline", - layer: "0", - points: kinds.polyline.points, - closed: false, - bulges: [0.25, 0], - width: 0.25, - linetypeGeneration: true, - id: "j", - ...styled, -}; - -/** A hatch with a gradient of two colors, with every field the hatch of `kinds` leaves out. */ -const shaded: Required> = { - kind: "hatch", - layer: "0", - loops: kinds.hatch.loops, - gradient: { - name: "spherical", - angle: 30, - centered: false, - colors: [ - [200, 40, 30], - [20, 90, 180], - ], - }, - id: "w3", - ...styled, -}; - -/** A hatch with a gradient of one color and its tint. */ -const tinted: Required> = { - kind: "hatch", - layer: "0", - loops: kinds.hatch.loops, - gradient: { - name: "inverted-curved", - angle: 200, - centered: true, - color: [30, 120, 200], - tint: 0.4, - }, - id: "w4", - ...styled, -}; - -/** A spline through fit points, with every field one can have. */ -const fitted: Required = { - kind: "spline", - layer: "0", - fitPoints: [ - [120, 0], - [124, 3], - ], - startTangent: [0, 1], - endTangent: [1, 0], - closed: false, - id: "w5", - ...styled, -}; - -const keyed: Required< - Omit< - Leader, - | "text" - | "attachment" - | "verticalAttachment" - | "width" - | "frame" - | "mask" - | "textStyle" - | "textHeight" - > -> = { - kind: "leader", - color: "ByBlock", - transparency: 20, - layer: "0", - style: "NOTE", - block: "TREE", - attributes: { TAG: "T-2" }, - at: [60, 10], - shafts: [[[55, 5]]], - side: "right", - shaft: "straight", - farShafts: [[[65, 5]]], - arrowSize: 0.05, - landing: 0.1, - gap: 0.02, - id: "keyed", -}; - -/** One of everything an R2018 drawing can hold, with every field of every object. */ -const full: Required & { - readonly linetypes: readonly [Required, Required]; - readonly patterns: readonly [ - Required & { readonly lines: readonly [Required] }, - ]; - readonly textStyles: readonly [Required]; - // A style in decimal units leaves zeros out, and one in architectural units writes them. - readonly dimensionStyles: readonly [ - Required>, - Required>, - ]; - readonly leaderStyles: readonly [Required]; - readonly tableStyles: readonly [ - Required & { readonly data: Required }, - ]; - readonly layers: readonly [Layer, Required]; - readonly blocks: readonly [ - Block, - Required & { - readonly attributes: readonly [ - Required, - Required, - ]; - }, - ]; - readonly xrefs: readonly [Required]; - readonly layouts: readonly [ - Required & { readonly viewports: readonly [Required] }, - Layout, - ]; -} = { - format: 0, - units: "ft", - dxf: "R2018", - linetypeScale: 2, - imageFrame: false, - underlayFrame: "screen", - wipeoutFrame: false, - linetypes: [ - { - name: "DD", - description: "Dash dot", - pattern: [0.5, -0.25, 0, -0.25], - marks: [ - { - after: 1, - text: "W", - style: "Standard", - height: 0.1, - rotation: 0, - orient: "upright", - offset: [0, -0.05], - }, - ], - }, - // A linetype of shapes that nothing draws in, which lint does not warn of. - { - name: "SHAPES", - description: "Shapes", - pattern: [0.5, -0.25], - marks: [ - { - after: 1, - shape: 3, - file: "shapes.shx", - scale: 0.1, - rotation: 0, - orient: "relative", - offset: [0, 0], - }, - ], - }, - ], - patterns: [ - { - name: "STRIPES", - description: "Dashed stripes", - lines: [{ angle: 45, base: [0, 0], offset: [0, 0.25], dashes: [0.5, -0.25, 0, -0.25] }], - }, - ], - textStyles: [{ name: "NOTES", font: "Arial", widthFactor: 0.9, obliqueAngle: 10 }], - dimensionStyles: [ - { - name: "DIMS", - textStyle: "NOTES", - textHeight: 0.1, - arrowhead: "architectural-tick", - arrowSize: 0.1, - extensionOffset: 0.05, - extensionBeyond: 0.1, - textGap: 0.05, - scale: 10, - precision: 2, - prefix: "L ", - suffix: "'", - units: "decimal", - suppressZeros: "trailing", - measurementScale: 2, - textPlacement: "centered", - textFit: "leader", - dimensionLineweight: 0.5, - extensionLineweight: 0.25, - radialText: "horizontal", - jogAngle: 30, - angleUnits: "degrees-minutes-seconds", - anglePrecision: 4, - suppressAngleZeros: "leading", - textMask: { color: 3 }, - arcSymbol: "above", - }, - { - name: "ARCH", - textStyle: "NOTES", - textHeight: 0.1, - arrowhead: "architectural-tick", - arrowSize: 0.1, - extensionOffset: 0.05, - extensionBeyond: 0.1, - textGap: 0.05, - scale: 10, - precision: 4, - prefix: "", - suffix: "", - units: "architectural", - feetInchZeros: "both", - measurementScale: 12, - fraction: "stacked", - fractionScale: 0.75, - textPlacement: "above", - textFit: "inside", - dimensionLineweight: 0.35, - extensionLineweight: 0.18, - radialText: "aligned", - jogAngle: 45, - angleUnits: "degrees", - anglePrecision: 0, - suppressAngleZeros: "both", - textMask: true, - arcSymbol: "none", - }, - ], - leaderStyles: [ - { - name: "NOTE", - textStyle: "NOTES", - textHeight: 0.1, - arrowhead: "dot", - arrowSize: 0.1, - landing: 0.1, - gap: 0.05, - attachment: "first-line", - direction: "vertical", - verticalAttachment: "line", - frame: true, - shaft: "curved", - block: "TREE", - blockConnection: "insertion", - blockScale: 2, - scale: 10, - }, - ], - tableStyles: [ - { - name: "SCHEDULE", - textStyle: "NOTES", - textHeight: 0.1, - horizontalMargin: 0.03, - verticalMargin: 0.02, - title: { textHeight: 0.15 }, - header: { fill: 8 }, - data: { - textStyle: "NOTES", - textHeight: 0.08, - align: "left", - valign: "middle", - color: 3, - fill: 9, - lineweight: 0.25, - }, - }, - ], - layers: [ - { name: "0", color: 7 }, - { - name: "WALL", - color: 1, - linetype: "DD", - lineweight: 0.5, - off: false, - frozen: false, - locked: true, - plot: false, - }, - ], - blocks: [ - { name: "LEAF", entities: [{ kind: "circle", layer: "0", center: [0, 0], radius: 1 }] }, - { - name: "TREE", - base: [1, 2], - attributes: [ - { - kind: "text", - tag: "TAG", - prompt: "Tree tag", - value: "T-0", - layer: "0", - at: [0, 4], - height: 1, - rotation: 0, - ...justified, - }, - { - kind: "paragraph", - tag: "NOTE", - prompt: "Note", - value: "PLANT IN\\PSPRING", - layer: "0", - at: [0, -4], - height: 0.5, - rotation: 0, - style: "NOTES", - width: 6, - align: "center", - valign: "middle", - lineSpacing: 1.5, - lineSpacingStyle: "exactly", - }, - ], - entities: [ - { kind: "arc", layer: "0", center: [0, 0], radius: 3, startAngle: 0, endAngle: 90 }, - { kind: "insert", layer: "0", block: "LEAF", at: [1, 1] }, - ], - }, - ], - xrefs: [{ name: "BASE", path: "base.dwg", attach: true }], - entities: [ - ...Object.values(kinds), - { kind: "insert", layer: "0", block: "BASE", at: [0, 0] }, - wide, - keyed, - fitted, - shaded, - tinted, - ], - layouts: [ - { - name: "C-101", - paper: "ARCH D", - plotStyle: "acad.ctb", - viewports: [ - { - id: "view", - layer: "WALL", - corner: [1, 1], - width: 20, - height: 10, - center: [5, 2], - ratio: 12, - frozenLayers: ["WALL"], - twist: 30, - }, - ], - // One of each kind of entity on the sheet, each with an id of its own. - entities: Object.values(kinds).map((entity) => ({ ...entity, id: `sheet-${entity.id}` })), - }, - { name: "Blank", paper: "ANSI B", viewports: [], entities: [] }, - ], -}; - -/** What an R12 drawing can hold. */ -const r12: Drawing = { - format: 0, - units: "ft", - dxf: "R12", - layers: [{ name: "0", color: 7 }], - entities: [ - { kind: "line", layer: "0", from: [0, 0], to: [10, 0], id: "a" }, - { - kind: "polyline", - layer: "0", - points: kinds.polyline.points, - closed: true, - id: "b", - linetype: "ByLayer", - lineweight: "ByLayer", - }, - { kind: "circle", layer: "0", center: [5, 5], radius: 2 }, - { kind: "arc", layer: "0", center: [5, 5], radius: 3, startAngle: 0, endAngle: 90 }, - { kind: "text", layer: "0", at: [0, 4], height: 1, rotation: 0, value: "T-0" }, - ], -}; - -type Path = readonly (string | number)[]; - -/** Every path to a value in `value`, at every depth. */ -function paths(value: unknown, at: Path = []): Path[] { - if (typeof value !== "object" || value === null) return []; - return Object.keys(value).flatMap((key) => { - const step = [...at, Array.isArray(value) ? Number(key) : key]; - return [step, ...paths((value as Record)[key], step)]; - }); -} - -const HOLE = Symbol("an empty slot"); - -/** A copy of `drawing` with the value at `path` replaced, or its slot emptied for `HOLE`. */ -function replaced(drawing: unknown, path: Path, value: unknown): unknown { - if (path.length === 0) return value; - const copy = structuredClone(drawing) as Record; - let parent = copy; - for (const step of path.slice(0, -1)) parent = parent[step] as typeof parent; - if (value === HOLE) delete parent[path.at(-1)!]; - else parent[path.at(-1)!] = value; - return copy; -} - -const at = (drawing: unknown, path: Path): unknown => - path.reduce((value, step) => (value as Record)[step], drawing); - -const circular: Record = {}; -circular.self = circular; -const wrong = [undefined, null, 5, "x", {}, [], 1n, circular, { toString: 0 }]; - -/** The values to put in place of the one at `path`. */ -function replacements(drawing: unknown, path: Path): unknown[] { - const parent = at(drawing, path.slice(0, -1)); - const value = at(drawing, path); - return [ - ...wrong, - ...(Array.isArray(value) ? [[null], new Array(2)] : []), - ...(typeof value === "number" ? [0, -1, NaN, Infinity] : []), - ...(Array.isArray(parent) ? [HOLE] : []), - // The same value with a field nobody knows. - ...(typeof value === "object" && !Array.isArray(value) ? [{ ...value, zz: 1 }] : []), - ]; -} - -/** - * A standard whose title block is the full drawing's block `TREE` on its sheet, so that `lint` - * walks every rule of a standard over the drawing, its title block and its fields among them. - */ -const treeStandard = defineStandard({ - id: "tree", - version: "1", - paperUnits: "in", - minTextHeight: 0.05, - layers: { WALL: { color: 1 } }, - textRoles: { note: { font: "Arial", height: 0.1 } }, - titleBlocks: { - tree: { - paper: "ARCH D", - block: { - format: 0, - units: "in", - dxf: "R2018", - layers: [{ name: "0", color: 7 }], - entities: [], - textStyles: full.textStyles, - blocks: full.blocks, - }, - blockName: "TREE", - layer: "WALL", - drawingArea: [0.5, 0.5, 35.5, 23.5], - fields: { TAG: { box: [1, 1, 2, 2] } }, - }, - }, - sheetFormats: { d: { paper: "ARCH D", titleBlock: "tree" } }, +test("the drawings the sweep replaces the values of have nothing for lint to report", () => { + for (const drawing of [full, r12]) assert.deepEqual(lint(fromJSON(toJSON(drawing))), []); }); -const errors = (drawing: Drawing, version?: "R12" | "R2018") => - lint(drawing, version ? { version } : {}).filter((d) => d.severity === "error"); - -/** - * Runs `toSVG` for model space and for each layout, as the command does, and stops it after a - * second, so a drawing that never finishes fails the test. - */ -const draw = new Script( - "toSVG(drawing); if (Array.isArray(drawing?.layouts)) for (const layout of drawing.layouts) toSVG(drawing, { layout: layout.name });", -); -Object.assign(globalThis, { toSVG }); - -/** What `toSVG` does with a drawing: the error it throws, or undefined when it draws it. */ -function drawn(drawing: Drawing): unknown { - Object.assign(globalThis, { drawing }); - try { - draw.runInThisContext({ timeout: timeLimit(1000) }); - return undefined; - } catch (thrown) { - return thrown; - } -} - -const hung = (thrown: unknown): boolean => - (thrown as { code?: unknown } | null)?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT"; - -/** - * Says what `lint` does wrong with a value: it must return, `toSVG` must return or throw in a - * second, a value `lint` reports no error for must be one the writers, `toSVG` and `fromJSON` - * take, and a drawing it reports an error for must be one `toSVG` draws, at least once the - * items the errors name are left out. - */ -function failure(value: unknown): string | undefined { - const drawing = value as Drawing; - let found: Diagnostic[]; - try { - for (const version of ["R12", "R2018"] as const) errors(drawing, version); - lint(drawing, { standard: BUILT_IN_STANDARD }); - lint(drawing, { standard: treeStandard }); - found = errors(drawing); - } catch (thrown) { - return `lint threw ${String(thrown)}`; - } - const refused = drawn(drawing); - if (hung(refused)) return "toSVG does not finish"; - if (found.length > 0) { - // A writer refuses what `lint` reports before it reads the drawing. - try { - toDXF(drawing); - return "lint reports an error, and toDXF writes the drawing"; - } catch (thrown) { - if (!(thrown instanceof DrawingError)) { - return `lint reports an error, and toDXF throws ${String(thrown).split("\n", 1)[0]}`; - } - } - // The command asks for a drawing with a list of layers and one of entities before it lints. - if (!Array.isArray(drawing?.layers) || !Array.isArray(drawing.entities)) return undefined; - if (refused === undefined) return undefined; - const rest = drawn(without(drawing, new Set(found.flatMap((d) => d.item ?? [])))); - return rest === undefined - ? undefined - : `it cannot be drawn without what lint names: ${String(rest).split("\n", 1)[0]}`; - } - try { - if (refused !== undefined) throw refused; - toDXF(drawing); - fromJSON(toJSON(drawing)); - fromJSON(structuredClone(value)); - } catch (thrown) { - return `lint reports no error, and then: ${String(thrown).split("\n", 1)[0]}`; - } - return undefined; -} - -test("lint returns for every value of the wrong type, with an error for what cannot be written", () => { - const failures: string[] = []; - for (const drawing of [full, r12]) { - assert.deepEqual(lint(fromJSON(toJSON(drawing))), []); - for (const path of [[], ...paths(drawing)]) { - for (const value of replacements(drawing, path)) { - const found = failure(replaced(drawing, path, value)); - const shown = inspect(value, { depth: 0, breakLength: Infinity }); - if (found) failures.push(`${drawing.dxf} ${path.join(".")} = ${shown}: ${found}`); - } - } - } - assert.deepEqual(failures, []); +// A share with no file would leave its cases out with nothing said. +test("each share of the sweep has its test file", () => { + const files = readdirSync(join(import.meta.dirname, "shape-sweep")); + const expected = Array.from({ length: SHARES }, (_, index) => `share-${index + 1}.test.ts`); + assert.deepEqual(files.sort(), expected.sort()); }); test("a value of the wrong shape is reported in these words, once", () => { From ab49239f569d74f83a961bb50f2562fda841b487 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 21:47:23 -0500 Subject: [PATCH 31/35] Points: plotted as CAD programs draw them, at the drawing's point style Points, in R2018 drawings. - `d.point(at, { rotation })` marks a location, such as a survey shot or a benchmark. - `createDrawing({ pointStyle })` gives the figure every point plots as: a `"dot"`, `"none"`, a `"plus"`, a `"cross"` or a `"tick"`, with a `circle` or a `square` around it. Its `size` is in drawing units, or `{ percent }` of half the height of the view the point is seen in: the sheet's height on a layout, the view's through a viewport, the picture's in model space. A drawing with no point style plots each point as a dot. - `toDXF` writes each point and the style, as `$PDMODE` and `$PDSIZE`, the way CAD programs save them. - `toSVG` and `toPDF` draw each figure as CAD programs plot it: in the thinnest line, solid whatever the linetype, and turned with the point. In a block, a size in drawing units scales with the insert and a relative one does not, though it turns and mirrors with it. - The extents hold a point's location, not its figure. - `readDXF` reads points, and the header's `pdmode` and `pdsize` as the file holds them. `pointStyleOf(pdmode, pdsize)` gives the style they plot as. - `lint` and the builder refuse a figure that is not one of the five, a size that is not above 0, a rotation outside 0 to 360, and a point or a point style in an R12 drawing. - The site plan example marks the bank's survey shots with points. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 9 + GUIDE.md | 2 + README.md | 12 ++ docs/assets/site-plan-dark.svg | 56 +++++++ docs/assets/site-plan-light.svg | 56 +++++++ docs/format.md | 5 + docs/plotting.md | 2 + docs/points.md | 57 +++++++ docs/reading.md | 5 +- docs/rules.md | 3 + examples/site-plan.ts | 7 + scripts/readme-drawing.ts | 3 +- src/drawing.ts | 107 ++++++++++++ src/dxf-r2018.ts | 15 ++ src/extents.ts | 5 + src/index.ts | 6 + src/lint.ts | 19 +++ src/points.ts | 158 ++++++++++++++++++ src/read/check.ts | 3 + src/read/dxf.ts | 5 + src/read/entities.ts | 13 ++ src/read/model.ts | 12 ++ src/rules.ts | 2 + src/shape.ts | 5 + src/svg.ts | 216 +++++++++++++++++++++++- test/format.test.ts | 2 +- test/points.test.ts | 282 ++++++++++++++++++++++++++++++++ test/read-agreement.ts | 12 ++ test/read-fuzz.ts | 8 + test/shape-sweep.ts | 2 + test/shape.test.ts | 2 +- test/standard-lint.test.ts | 6 +- 32 files changed, 1081 insertions(+), 16 deletions(-) create mode 100644 docs/points.md create mode 100644 src/points.ts create mode 100644 test/points.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2806fb2..3d85789 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,15 @@ `readDWG` read it as `alpha`, from 0 to 255, or `"ByBlock"`. A block a leader places holds every entity ByBlock, as CAD programs read it, and the writers write it so; the leader draws it opaque. +- Points, in R2018 drawings. `d.point(at, { rotation })` marks a location, and + `createDrawing({ pointStyle })` gives the figure every point plots as: a dot, nothing, a +, a × + or a tick, with a circle or a square around it, at a `size` in drawing units or a `{ percent }` + of half the view it is seen in, as CAD programs plot it. `toDXF` writes each point and the style + as `$PDMODE` and `$PDSIZE`, and `toSVG` and `toPDF` draw the figure in the thinnest line, solid, + turned with the point, and under an insert placed as the block's lines are. The extents hold a + point's location. `readDXF` reads points and the two header variables, and `pointStyleOf` gives + the style they plot as. `lint` and the builder refuse a figure that is not one of the five, a + size not above 0, a rotation outside 0 to 360, and a point or a point style in an R12 drawing. - Linetypes with shapes: a fence with its circles along it, and batt insulation. `parseShapes` reads a firm's compiled shape file (`.shx`) into each shape's outlines, and `toSVG`, `toPDF` diff --git a/GUIDE.md b/GUIDE.md index c1e03a8..a436de8 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -68,6 +68,8 @@ inside it, and `donut` a filled ring or dot. [docs/polylines.md](docs/polylines. ratio of its axes; `spline` draws the cubic CAD programs fit through fit points, for a top of bank, a tree line or a contour, and `controlSpline` a spline by its control points. [docs/curves.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/curves.md) has them. +`point` marks a location, which plots as the figure `createDrawing`'s `pointStyle` gives every +point. [docs/points.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/points.md) has it. `image` draws a PNG or a JPEG at a width in drawing units, with the file's `pixels`, which `rasterSize` reads, and an optional `clip`; the command reads the file from the drawing file's folder for the pictures, and warns of one that is missing. diff --git a/README.md b/README.md index 56764ae..8074ad5 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,16 @@ d.controlSpline(controlPoints, { degree: 3 }); [Ellipses and splines](docs/curves.md) has arcs of an ellipse, tangents, closed splines, knots and weights. +A point marks a survey shot or a benchmark. Every point plots as the figure the drawing's point +style gives, at a size in drawing units or as a share of the view: + +```ts +const d = createDrawing({ pointStyle: { figure: "cross", circle: true, size: 0.25 } }); +d.point([10, 5]); +``` + +[Points](docs/points.md) has the figures and their sizes. + A paragraph is one text whose lines wrap at a width, which a CAD user edits as one. A line feed starts a new paragraph, and small helpers write the codes for a numbered list, an underline, bold, a stacked fraction and a superscript: @@ -427,6 +437,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version widths and donuts, how a wide polyline plots, and what `lint` refuses of them. - [Ellipses and splines](docs/curves.md) covers ellipses and their arcs, splines through fit points and by control points, how they plot and dash, and what `lint` refuses of them. +- [Points](docs/points.md) covers points and the point style, how a figure plots and how big, and + what `lint` refuses of them. - [Paragraphs](docs/paragraphs.md) covers paragraph text: its width and box, the codes its value takes, the helpers that write them, how it is laid out, and what `lint` refuses. - [Images](docs/images.md) covers raster images: the path and the pixels, clips, frames, diff --git a/docs/assets/site-plan-dark.svg b/docs/assets/site-plan-dark.svg index 83e82fe..a3b2ab8 100644 --- a/docs/assets/site-plan-dark.svg +++ b/docs/assets/site-plan-dark.svg @@ -60,6 +60,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -217,6 +245,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/site-plan-light.svg b/docs/assets/site-plan-light.svg index dbba44c..03ebd0a 100644 --- a/docs/assets/site-plan-light.svg +++ b/docs/assets/site-plan-light.svg @@ -60,6 +60,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -217,6 +245,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/format.md b/docs/format.md index 466ec6a..6e7b39d 100644 --- a/docs/format.md +++ b/docs/format.md @@ -141,6 +141,11 @@ and for an arc of it its `startParameter` and `endParameter`. A spline is an ent `lineweight` of every entity. A drawing with neither has the JSON it had before they existed. [Ellipses and splines](curves.md) describes them. +A point is an entity of kind `"point"`, with its `layer` and `at`, and where it is set its +`rotation`, with the `linetype` and `lineweight` of every entity. The drawing's `pointStyle` gives +the figure every point plots as. A drawing with neither has the JSON it had before they existed. +[Points](points.md) describes them. + A drawing written by hand needs `format: 0` too. `lint` reports a drawing without it, or with another version, under the rule `format`, and `toDXF` refuses to write it. `lint` takes any plain data and never throws: a list that is not an array, an entity of an unknown `kind`, a diff --git a/docs/plotting.md b/docs/plotting.md index 915eb67..003c84f 100644 --- a/docs/plotting.md +++ b/docs/plotting.md @@ -67,6 +67,8 @@ preview shows it: or one of a higher degree in 32 straight steps to each span of its knots. - A line of lineweight 0 plots as the thinnest line the printer draws, as a viewport's border does. +- A point plots as the figure of the drawing's point style, in the thinnest line and solid, as + [How it plots](points.md#how-it-plots) says. - A wide side of a polyline is filled, at its width whatever its pen, with its joins and its dashes as [How it plots](polylines.md#how-it-plots) says. - An image is drawn from its file's bytes, given as `images`, clipped to its clip, with its frame diff --git a/docs/points.md b/docs/points.md new file mode 100644 index 0000000..573a609 --- /dev/null +++ b/docs/points.md @@ -0,0 +1,57 @@ +# Points + +A point marks a location, such as a survey shot, a benchmark or a control point. Every point of +a drawing plots as the same figure, which the drawing's point style gives: CAD programs keep it in +the file as `$PDMODE` and `$PDSIZE`. + +```ts +const d = createDrawing({ pointStyle: { figure: "cross", circle: true, size: 0.25 } }); +d.point([10, 5]); +d.point([12, 5], { rotation: 30 }); +``` + +Points are R2018 only. + +## The point style + +`pointStyle` takes a `figure`: `"dot"`, `"none"`, `"plus"`, `"cross"` (a ×) or `"tick"` (a short +line up from the point). `circle` and `square` draw a circle and a square around it. A drawing +with no point style plots each point as a dot, as CAD programs do. + +`size` is how far an arm of the + or the × reaches from the point. The tick is half as long, and +the circle and the square are as wide as the size. It is either: + +- a number, in drawing units. In a block it is scaled with the insert, as the block's lines are. +- `{ percent }`, a share of half the height of the view the point is seen in: the sheet's height on + a layout, the view's height in model space through a viewport, and the picture's height in a + picture of model space. Under an insert it is not scaled, but it is turned, mirrored and skewed + with the insert. A point style with no size is `{ percent: 5 }`. + +## A point + +`point(at, { rotation })` turns the figure by `rotation` degrees counterclockwise, brought into 0 +up to 360. A point is the entity `{ kind: "point", layer, at, rotation? }`, with the `linetype` and +`lineweight` of every entity. + +## How it plots + +The figure plots in the thinnest line the printer draws, solid, whatever the point's lineweight +and linetype: the circle first, then the square, then the dot, +, × or tick. A dot is a stroke of +no length at the point. A point drawn as a dot alone, in model space seen through a viewport, +plots a device pixel wide, 1/600 inch, as CAD programs plot it. + +The extents count a point at its location, not its figure, since a relative figure's size takes +the view the extents give. + +## Reading + +`readDXF` reads a point as `{ kind: "point", at, rotation? }`, and the header's `pdmode` and +`pdsize` as the file holds them. `pointStyleOf(pdmode, pdsize)` gives the point style they plot +as: a mode CAD programs do not offer plots as a dot, and a size of 0 as `{ percent: 5 }`. + +## Checks + +`lint` refuses a point style whose figure is not one of the five, whose `circle` or `square` is +not true or false, or whose size or percent is not above 0, is written as 0, or is 1e100 or more; +a point whose location is not finite, or whose rotation is not from 0 up to 360; and a point or a +point style in an R12 drawing. diff --git a/docs/reading.md b/docs/reading.md index 2d57e71..83253ef 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -50,7 +50,8 @@ A `DrawingRead` is not a `Drawing`, and nothing writes it back to a file. It hol states and keeps each object's handle, and it keeps going past what it does not understand: - `sha256` and `bytes` of the file, its `version`, and `header`: `$INSUNITS`, `$MEASUREMENT`, - `$LTSCALE`, `$PSLTSCALE`, `$MSLTSCALE`, `$DIMSCALE` and the current styles. + `$LTSCALE`, `$PSLTSCALE`, `$MSLTSCALE`, `$DIMSCALE`, `$PDMODE`, `$PDSIZE` and the current + styles. `pointStyleOf` gives the point style the last two plot as. - The tables: `layers` with their state, `linetypes`, each with the `marks` it draws as a `Linetype` holds them, a text's `style` by name and its `height` times its style's fixed height, a shape by its number and its `file`, `textStyles` and `dimensionStyles`, each @@ -215,6 +216,8 @@ leader: angle and `centered: false` do not give its mirror image, because its shift does not mirror with the angle. - `wipeout`: its `points` in the world's coordinates, without the first again at the end. +- `point`: its `at`, and its `rotation`, the turn of its figure counterclockwise from 0 up to 360, + which the file holds the other way round in group 50. - `ellipse`: its `center` and `majorAxis`, which the file holds in the world's coordinates, its `ratio`, and for an arc its `startParameter` and `endParameter` in degrees, as `Ellipse` holds them. One the file holds seen from below runs its parameters the other way round, and is read as diff --git a/docs/rules.md b/docs/rules.md index e1f0618..b6c1006 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -87,6 +87,9 @@ it would take `1e+100` for `1e+10` and report nothing. each control point where it has weights. A closed one ends where it starts, the way it arrives. A spline holds at most `SPLINE_ITEMS`, 32,767, knots. [Ellipses and splines](curves.md#checks) has the rest. +- A point and a point style are R2018 only. A point is at finite numbers and turned from 0 up to 360. A point style's figure is one of `"dot"`, `"none"`, `"plus"`, `"cross"` and `"tick"`, and + its size or percent is above 0, not written as 0, and under 1e100. [Points](points.md#checks) + has the rest. - A hatch's `gradient` goes with no `pattern`. Its `name` is one of `GRADIENT_KINDS`, its `angle` a finite number under 1e100 and `centered` true or false, and it has two `colors` or a `color` and a `tint` from 0 to 1, each color three whole numbers from 0 to 255, and no other field. The rule of these is diff --git a/examples/site-plan.ts b/examples/site-plan.ts index abb6974..485aa86 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -110,6 +110,7 @@ export const standard = defineStandard({ "C-ANNO-REVS": { color: 1, pen: "medium", discipline: "C" }, "C-ANNO-IMAG": { color: 8, pen: "fine", discipline: "C" }, "C-TOPO-BANK": { color: 30, linetype: "HIDDEN", pen: "fine", discipline: "C" }, + "V-SURV-SHOT": { color: 30, pen: "fine", discipline: "V" }, }, }); @@ -241,6 +242,8 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee const d = createDrawing({ units: "ft", standard, + // Every point plots as a × a foot across each arm, 1/10 in at 1" = 10'. + pointStyle: { figure: "cross", size: 1 }, fields: { project: project.name, date: project.date, @@ -378,6 +381,10 @@ export function sitePlan(scale: keyof typeof standard.scales = "1in-10ft"): Shee }); // A line that bends with the ground is a spline through the points located on it. d.layer("C-TOPO-BANK", () => d.spline(bank)); + // Each shot the survey located it by, as a point. + d.layer("V-SURV-SHOT", () => { + for (const shot of bank) d.point(shot); + }); // The plan's annotation, in model space with what it describes. A text names the view it is // read in, which sizes it to plot at its role's height. Gaps and offsets are lengths on paper, diff --git a/scripts/readme-drawing.ts b/scripts/readme-drawing.ts index 86cd4a1..85ef067 100644 --- a/scripts/readme-drawing.ts +++ b/scripts/readme-drawing.ts @@ -85,6 +85,7 @@ const pictures: Picture[] = [ "C-PAVE": "muted", "C-ROAD-CNTR": "muted", "C-TOPO-BANK": "muted", + "V-SURV-SHOT": "muted", "V-TREE": "muted", "C-ANNO-DIMS": "accent", "C-ANNO-REVS": "accent", @@ -164,7 +165,7 @@ const PAPER = 'fill="#ffffff" data-paper-sheet=""/>'; * A dimension, a leader or a paragraph is a group that names the layer, and its parts are the * lines after it. */ -const GROUPED = / data-(dimension|leader|paragraph)="/; +const GROUPED = / data-(dimension|leader|paragraph|point)="/; /** A line one pixel wide just inside the edge of the picture, which is the sheet's edge. */ function sheetOutline(x: number, y: number, w: number, h: number, pixel: number, color: string) { diff --git a/src/drawing.ts b/src/drawing.ts index 437d863..ae3644c 100644 --- a/src/drawing.ts +++ b/src/drawing.ts @@ -290,6 +290,7 @@ import { WIPEOUT_POINTS, ORDINATE_AXIS, } from "./rules.ts"; +import { pointStyleProblems } from "./points.ts"; import type { Standard, StandardDimensionStyle, @@ -561,6 +562,17 @@ export interface Circle extends EntityBase { readonly radius: number; } +/** + * A point, which plots as the figure the drawing's `pointStyle` gives every point, turned by + * `rotation`. R2018 only. + */ +export interface PointEntity extends EntityBase { + readonly kind: "point"; + readonly at: Point; + /** How far its figure is turned, in degrees counterclockwise, from 0 up to 360. Defaults to 0. */ + readonly rotation?: number; +} + /** Angles are in degrees from 0 up to 360, counterclockwise from +X, as in DXF. */ export interface Arc extends EntityBase { readonly kind: "arc"; @@ -1257,6 +1269,7 @@ export type Entity = | Line | Polyline | Circle + | PointEntity | Arc | Ellipse | Spline @@ -1677,6 +1690,37 @@ export interface Drawing { readonly wipeoutFrame?: boolean; /** The hatch patterns that hatches name, such as a firm's pattern file's from `parsePatterns`. */ readonly patterns?: readonly HatchPattern[]; + /** What figure every point plots as, and how big. Defaults to a dot. */ + readonly pointStyle?: PointStyle; +} + +/** The figure a point plots as: a dot, nothing, a +, a ×, or a tick up from the point. */ +export type PointFigure = "dot" | "none" | "plus" | "cross" | "tick"; + +/** + * What figure every point of a drawing plots as, and how big: the file's PDMODE and PDSIZE. A + * figure's size is how far an arm of its + or × reaches from the point. The tick is half as long, + * and the circle and the square are as wide as the size. The figure plots in the thinnest line, + * solid, whatever the point's lineweight and linetype. + * + * ```ts + * { figure: "cross", circle: true, size: 0.25 } + * { figure: "plus", size: { percent: 5 } } + * ``` + */ +export interface PointStyle { + readonly figure: PointFigure; + /** A circle around the figure. */ + readonly circle?: boolean; + /** A square around the figure. */ + readonly square?: boolean; + /** + * In drawing units, or `{ percent }` of half the height of the view the point is seen in: the + * sheet's height on a layout, the viewport's view through one, the picture's in model space. In + * a block, a size in drawing units is scaled with the insert and a relative one is not. + * Defaults to `{ percent: 5 }`. + */ + readonly size?: Positive | { readonly percent: Positive

}; } /** @@ -1733,6 +1777,8 @@ export interface DrawingOptions< * before it runs them. */ readonly recordCalls?: boolean; + /** What figure every point plots as, and how big. Defaults to a dot. R2018 only. */ + readonly pointStyle?: PointStyle; } /** A linetype to define: a `Linetype`, whose description may be left out. */ @@ -1901,6 +1947,20 @@ function hatchGradientCopy(given: unknown): HatchGradient { } /** What `ellipse()` takes besides what every entity does. */ +/** What `point` takes beside the point. */ +export interface PointOptions< + V extends DxfVersion = "R2018", + T extends string = string, + W extends number = number, + L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + Z extends Standard | undefined = undefined, + P extends string = string, +> extends EntityOptions { + /** How far the figure is turned, in degrees counterclockwise. Brought into 0 up to 360. */ + readonly rotation?: number; +} + export interface EllipseOptions< V extends DxfVersion = "R2018", T extends string = string, @@ -3302,6 +3362,7 @@ export class DrawingBuilder< readonly units: Units; readonly dxf: V; readonly linetypeScale: number; + readonly #pointStyle: PointStyle | undefined; /** The standard the drawing is drawn to, with its entries by name as the leading CAD app compares them. */ readonly #standard: Drawn | undefined; /** Keyed by `layerKey`, because the leading CAD app ignores case in layer names. */ @@ -3383,6 +3444,22 @@ export class DrawingBuilder< const problem = linetypeScaleProblem(scale); if (problem) throw new Error(`linetypeScale: ${problem}`); } + const pointStyle: unknown = options.pointStyle; + if (pointStyle !== undefined) { + if (dxf === "R12") throw new Error(`pointStyle: ${R12_ONLY.points}`); + const [problem] = pointStyleProblems(pointStyle); + if (problem) throw new Error(capitalized(problem)); + // Only the fields a style has, so that what the writers hash is plain data. + const { figure, circle, square, size } = pointStyle as PointStyle; + this.#pointStyle = { + figure, + ...(circle === undefined ? {} : { circle }), + ...(square === undefined ? {} : { square }), + ...(size === undefined + ? {} + : { size: typeof size === "number" ? size : { percent: size.percent } }), + }; + } this.units = units; this.dxf = dxf as V; this.linetypeScale = standard?.standard.linetypeScale ?? (scale as number | undefined) ?? 1; @@ -4247,6 +4324,35 @@ export class DrawingBuilder< })); } + /** + * A point at `at`, which plots as the figure the drawing's `pointStyle` gives, turned by + * `rotation` degrees counterclockwise. R2018 only. + * + * ```ts + * const d = createDrawing({ pointStyle: { figure: "cross", circle: true, size: 0.25 } }); + * d.point([10, 5]); + * d.point([12, 5], { rotation: 30 }); + * ``` + */ + point< + T extends string = string, + W extends number = number, + const L extends LinetypeValue = LinetypeDefinition, + I extends string = string, + P extends string = string, + >(at: Point, options: PointOptions = {}): this { + return this.#add(DrawingBuilder.prototype.point, options, () => { + if (this.dxf === "R12") refuse("geometry", R12_ONLY.points); + const rotation = options.rotation === undefined ? 0 : turn(num(options.rotation, "rotation")); + return { + kind: "point", + layer: this.#current, + at: pt(at), + ...(rotation === 0 ? {} : { rotation }), + }; + }); + } + /** * Arc from `startAngle` counterclockwise to `endAngle`. Angles are stored * from 0 up to 360, so -90 becomes 270, because the leading CAD app's AUDIT rejects @@ -6729,6 +6835,7 @@ export class DrawingBuilder< ...(this.#patterns.size > 0 ? { patterns: [...this.#patterns.values()].map(([pattern]) => pattern) } : {}), + ...(this.#pointStyle ? { pointStyle: this.#pointStyle } : {}), }; } diff --git a/src/dxf-r2018.ts b/src/dxf-r2018.ts index caf3839..05b116a 100644 --- a/src/dxf-r2018.ts +++ b/src/dxf-r2018.ts @@ -197,6 +197,7 @@ import { } from "./leaders.ts"; import { entityLinetype, layerLinetype, lineweightCode, patternLength } from "./linetypes.ts"; import { idKey, isStandardTextStyle, shown, TEXT_ALIGNS, TEXT_VERTICAL_ALIGNS } from "./rules.ts"; +import { pointMode, pointSize } from "./points.ts"; import { shapeFileKey } from "./shapes.ts"; /** `$INSUNITS` codes from the DXF Reference. */ @@ -1127,6 +1128,12 @@ export function toDXFR2018( h(9, "$LTSCALE"); h(40, drawing.linetypeScale); } + if (drawing.pointStyle !== undefined) { + h(9, "$PDMODE"); + h(70, pointMode(drawing.pointStyle)); + h(9, "$PDSIZE"); + h(40, pointSize(drawing.pointStyle)); + } // A drawing saved from this file then refuses in-place editing through a reference to it. h(9, "$XEDIT"); h(290, 0); @@ -1617,6 +1624,14 @@ function writeEntity( point(g, 10, ...e.center); g(40, e.radius); return; + case "point": { + begin("POINT", "AcDbPoint"); + point(g, 10, ...e.at); + // The file holds the angle the figure is turned clockwise by. + const turned = written(e.rotation ?? 0) % 360; + if (turned !== 0) g(50, 360 - turned); + return; + } case "arc": begin("ARC", "AcDbCircle"); point(g, 10, ...e.center); diff --git a/src/extents.ts b/src/extents.ts index 45a448f..5660213 100644 --- a/src/extents.ts +++ b/src/extents.ts @@ -334,6 +334,11 @@ export function boxer( add(box[2], box[3]); break; } + case "point": + // Its figure is not counted: a relative size takes the view, which the extents give. + if (Array.isArray(e.at) && Number.isFinite(e.at[0]) && Number.isFinite(e.at[1])) + add(e.at[0], e.at[1]); + break; case "circle": case "arc": add(e.center[0] - e.radius, e.center[1] - e.radius); diff --git a/src/index.ts b/src/index.ts index cf7eca3..015486f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -72,6 +72,10 @@ export { type CloudOptions, type ControlSplineOptions, type EllipseOptions, + type PointOptions, + type PointEntity, + type PointStyle, + type PointFigure, type SplineOptions, type ControlSpline, type Ellipse, @@ -253,6 +257,7 @@ export { type GradientWritten, } from "./fills.ts"; export { bulgeThrough, polylineBox, type PolylineBox } from "./polylines.ts"; +export { pointStyleOf } from "./points.ts"; export { clamped, ellipseBox, @@ -491,6 +496,7 @@ export { type DrawingRead, type ReadArc, type ReadEllipse, + type ReadPoint, type ReadSpline, type ReadAttribute, type ReadAttributeDefinition, diff --git a/src/lint.ts b/src/lint.ts index f94992e..7ddac4a 100644 --- a/src/lint.ts +++ b/src/lint.ts @@ -245,6 +245,7 @@ import { ORDINATE_ACROSS, ORDINATE_AXIS, } from "./rules.ts"; +import { pointStyleProblems } from "./points.ts"; import { hatchSpread, lineSizes, @@ -853,6 +854,11 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) item: "imageFrame", }); } + const pointStyle: unknown = drawing.pointStyle; + if (pointStyle !== undefined) { + for (const problem of r12 ? [R12_ONLY.points] : pointStyleProblems(pointStyle)) + out.push({ rule: "geometry", severity: "error", message: problem, item: "pointStyle" }); + } const underlayFrame: unknown = drawing.underlayFrame; if ( underlayFrame !== undefined && @@ -2463,6 +2469,10 @@ export function lintWithin(drawing: Drawing, options: LintOptions, most: number) add("geometry", "error", R12_ONLY.curves); return; } + if (r12 && entity.kind === "point") { + add("geometry", "error", R12_ONLY.points); + return; + } if (entity.kind === "hatch" || entity.kind === "wipeout") { if (r12) { add(entity.kind, "error", R12_ONLY.hatches); @@ -3093,6 +3103,14 @@ function geometryProblems(e: Entity): string[] { finite("its center", ...e.center); size("radius", e.radius); break; + case "point": + finite("its point", ...e.at); + if ( + e.rotation !== undefined && + !(Number.isFinite(e.rotation) && e.rotation >= 0 && e.rotation < 360) + ) + out.push("its rotation must be from 0 up to 360"); + break; case "arc": finite("its center", ...e.center); size("radius", e.radius); @@ -3241,6 +3259,7 @@ function zeroLength(e: Entity): string | undefined { ? `the arc has no length ${rounded}` : undefined; case "circle": + case "point": case "text": case "paragraph": case "insert": diff --git a/src/points.ts b/src/points.ts new file mode 100644 index 0000000..c510143 --- /dev/null +++ b/src/points.ts @@ -0,0 +1,158 @@ +// A drawing's point style: what figure every point plots as, and how big, as the file holds it +// in PDMODE and PDSIZE and as the leading CAD app draws it. +import type { Point, PointFigure, PointStyle } from "./drawing.ts"; +import { sizeProblem } from "./rules.ts"; +import { isRecord } from "./shape.ts"; + +/** The figures, in the order PDMODE numbers them from 0. */ +export const POINT_FIGURES: readonly PointFigure[] = ["dot", "none", "plus", "cross", "tick"]; + +/** The PDMODE that holds a point style. */ +export function pointMode(style: PointStyle): number { + return POINT_FIGURES.indexOf(style.figure) + (style.circle ? 32 : 0) + (style.square ? 64 : 0); +} + +/** The PDSIZE that holds a point style's size: a relative size is negative, and none is 0. */ +export function pointSize(style: PointStyle): number { + const size = style.size; + return size === undefined ? 0 : typeof size === "number" ? size : -size.percent; +} + +/** + * The point style a file's PDMODE and PDSIZE give, as the leading CAD app plots them. A PDMODE + * that is none of the 20 the app offers plots as a dot, and a PDSIZE of 0, or none, as 5% of the + * view. + * + * ```ts + * pointStyleOf(35, -10); // { figure: "cross", circle: true, size: { percent: 10 } } + * ``` + */ +export function pointStyleOf(pdmode?: number, pdsize?: number): PointStyle { + const mode = Number.isInteger(pdmode) ? pdmode! : 0; + const figure = mode & 31; + const known = mode >= 0 && mode <= 100 && (mode & ~(31 | 32 | 64)) === 0 && figure <= 4; + const size = Number.isFinite(pdsize) ? pdsize! : 0; + return { + figure: known ? POINT_FIGURES[figure]! : "dot", + ...(known && mode & 32 ? { circle: true } : {}), + ...(known && mode & 64 ? { square: true } : {}), + size: size > 0 ? size : { percent: size === 0 ? 5 : -size }, + }; +} + +/** What is wrong with a value given as a point style, each as a sentence. */ +export function pointStyleProblems(style: unknown): string[] { + if (!isRecord(style)) return ["pointStyle must be a plain object"]; + const s = style; + const out: string[] = []; + // The first field it does not know, cut short, keeps the message small whatever the key. + const extra = Object.keys(s).find((key) => !["figure", "circle", "square", "size"].includes(key)); + if (extra !== undefined) + out.push( + `pointStyle has a field it does not know, ${JSON.stringify(extra.length > 40 ? `${extra.slice(0, 40)}…` : extra)}`, + ); + if (!POINT_FIGURES.includes(s.figure as PointFigure)) + out.push(`pointStyle's figure must be one of ${POINT_FIGURES.map((f) => `"${f}"`).join(", ")}`); + for (const flag of ["circle", "square"]) + if (s[flag] !== undefined && typeof s[flag] !== "boolean") + out.push(`pointStyle's ${flag} must be true or false`); + const size = s.size; + if (size === undefined) return out; + if (typeof size === "number") { + const problem = Number.isFinite(size) ? sizeProblem(size) : "it must be a finite number"; + if (problem) out.push(`pointStyle's size: ${problem}`); + } else if (isRecord(size) && Object.keys(size).length === 1 && "percent" in size) { + const percent = size.percent; + const problem = + typeof percent === "number" && Number.isFinite(percent) + ? sizeProblem(percent) + : "it must be a finite number"; + if (problem) out.push(`pointStyle's size in percent: ${problem}`); + } else out.push("pointStyle's size must be a number, or { percent } of the view"); + return out; +} + +/** + * How far a point's figure reaches from the point: its size, the length of an arm of its + or ×. + * A relative size is that share of half `height`, the height of the view the point is seen in, in + * its units. Undefined when the figure has no size to draw, and is drawn as a dot. + */ +export function pointReach(style: PointStyle, height: number): number | undefined { + const size = style.size ?? { percent: 5 }; + const reach = typeof size === "number" ? size : (size.percent / 100) * (height / 2); + return reach > 0 && Number.isFinite(reach) ? reach : undefined; +} + +/** A part of a point's figure: a circle of a radius, or a path, one point long for a dot. */ +export type PointPart = { readonly radius: number } | { readonly points: readonly Point[] }; + +/** + * The parts of a point's figure about the origin, before it is turned, in the order the leading + * CAD app plots them: the circle from its point at 0 degrees counterclockwise, the square from its + * lower left corner clockwise, then the dot, the +, the × or the tick. `reach` is `pointReach`'s. + */ +export function pointFigure(style: PointStyle, reach: number | undefined): PointPart[] { + if (reach === undefined) return style.figure === "none" ? [] : [{ points: [[0, 0]] }]; + const h = reach / 2; + const out: PointPart[] = []; + if (style.circle) out.push({ radius: h }); + if (style.square) + out.push({ + points: [ + [-h, -h], + [-h, h], + [h, h], + [h, -h], + [-h, -h], + ], + }); + const a = reach / Math.SQRT2; + switch (style.figure) { + case "dot": + out.push({ points: [[0, 0]] }); + break; + case "plus": + out.push( + { + points: [ + [-reach, 0], + [reach, 0], + ], + }, + { + points: [ + [0, -reach], + [0, reach], + ], + }, + ); + break; + case "cross": + out.push( + { + points: [ + [-a, -a], + [a, a], + ], + }, + { + points: [ + [-a, a], + [a, -a], + ], + }, + ); + break; + case "tick": + out.push({ + points: [ + [0, 0], + [0, h], + ], + }); + break; + case "none": + break; + } + return out; +} diff --git a/src/read/check.ts b/src/read/check.ts index 0e1c335..6f68865 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -160,6 +160,7 @@ const ENTITY: Readonly> = { "linetypeGeneration?": "boolean", }, circle: { ...BASE, kind: { oneOf: ["circle"] }, center: "point", radius: "number" }, + point: { ...BASE, kind: { oneOf: ["point"] }, at: "point", "rotation?": "number" }, arc: { ...BASE, kind: { oneOf: ["arc"] }, @@ -485,6 +486,8 @@ const DRAWING_READ: Fields = { "psltscale?": "number", "msltscale?": "number", "dimscale?": "number", + "pdmode?": "number", + "pdsize?": "number", "dimstyle?": "string", "textstyle?": "string", "wipeoutFrame?": "number", diff --git a/src/read/dxf.ts b/src/read/dxf.ts index 70fab19..fca2ec3 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -207,6 +207,7 @@ const BLOCK_READS = new Set([ "MTEXT", "MULTILEADER", "PDFUNDERLAY", + "POINT", "POLYLINE", "SEQEND", "SOLID", @@ -430,6 +431,8 @@ const HEADER = new Set([ "$PSLTSCALE", "$MSLTSCALE", "$DIMSCALE", + "$PDMODE", + "$PDSIZE", "$DIMSTYLE", "$TEXTSTYLE", "$TILEMODE", @@ -1597,6 +1600,8 @@ class DxfReader { ["psltscale", "$PSLTSCALE"], ["msltscale", "$MSLTSCALE"], ["dimscale", "$DIMSCALE"], + ["pdmode", "$PDMODE"], + ["pdsize", "$PDSIZE"], ] as const) { const n = numberOf(key); if (n !== undefined) header[field] = n; diff --git a/src/read/entities.ts b/src/read/entities.ts index 5f2e510..bf64018 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -223,6 +223,18 @@ export function readingOf( switch (r.type) { case "LINE": return { entity: { ...base, kind: "line", from: point(r, 10), to: point(r, 11) } }; + case "POINT": { + // Group 50 is the angle the figure is turned clockwise by. + const rotation = degrees(-(num(r, 50) ?? 0)); + return { + entity: { + ...base, + kind: "point", + at: point(r, 10), + ...(rotation === 0 ? {} : { rotation }), + }, + }; + } case "CIRCLE": if (face === 0) return { other: "CIRCLE in 3D" }; return { @@ -1424,6 +1436,7 @@ export function costOf(e: ReadEntity): number { switch (e.kind) { case "line": return own + 2; + case "point": case "circle": case "arc": case "ellipse": diff --git a/src/read/model.ts b/src/read/model.ts index b62acbd..9997ae5 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -108,6 +108,10 @@ export interface ReadHeader { readonly psltscale?: number; readonly msltscale?: number; readonly dimscale?: number; + /** `$PDMODE`, the figure points plot as. `pointStyleOf` says what it and `pdsize` draw. */ + readonly pdmode?: number; + /** `$PDSIZE`, the size of a point's figure: in drawing units above 0, a share of the view below. */ + readonly pdsize?: number; /** `$DIMSTYLE`, the current dimension style. */ readonly dimstyle?: string; /** `$TEXTSTYLE`, the current text style. */ @@ -963,6 +967,13 @@ export interface ReadWipeout extends ReadEntityBase { readonly points: readonly Point[]; } +/** A point, as `PointEntity` holds it: its figure's turn counterclockwise, from 0 up to 360. */ +export interface ReadPoint extends ReadEntityBase { + readonly kind: "point"; + readonly at: Point; + readonly rotation?: number; +} + /** * An ellipse, or an arc of one, as `Ellipse` holds it: in the world's coordinates, with its * parameters in degrees counterclockwise. One the file holds seen from below, which runs its @@ -1008,6 +1019,7 @@ export type ReadEntity = | ReadLine | ReadPolyline | ReadCircle + | ReadPoint | ReadArc | ReadEllipse | ReadSpline diff --git a/src/rules.ts b/src/rules.ts index 66347b8..55c6c98 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -226,6 +226,7 @@ const UNDERLAY_PLACED = const R12_TABLES = 'tsdraft writes no tables to R12 drawings. Use DXF version "R2018" for a table'; const R12_HATCHES = 'tsdraft writes no hatches or wipeouts to R12 drawings. Use DXF version "R2018" for a fill'; +const R12_POINTS = 'tsdraft writes no points to R12 drawings. Use DXF version "R2018" for a point'; const R12_CURVES = 'tsdraft writes no ellipses or splines to R12 drawings. Use DXF version "R2018" for a curve'; const IMAGE_PATH_EMPTY = "An image's path cannot be empty. The leading CAD app finds no file by it"; @@ -2039,6 +2040,7 @@ export const R12_ONLY = { hatches: R12_HATCHES, tables: R12_TABLES, curves: R12_CURVES, + points: R12_POINTS, } as const; /** The highest degree of a spline by its control points. */ diff --git a/src/shape.ts b/src/shape.ts index 0a138b2..50e4894 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -39,6 +39,7 @@ import type { LinetypeText, Paragraph, PatternLine, + PointEntity, Polyline, Text, TextStyle, @@ -72,6 +73,7 @@ const KINDS = [ "line", "polyline", "circle", + "point", "arc", "ellipse", "spline", @@ -538,6 +540,7 @@ function shapes(all: boolean, typed = all): Shapes { }, ), circle: fields({ kind, layer: string, center: point, radius: number }, shared), + point: fields({ kind, layer: string, at: point }, { ...shared, rotation: number }), arc: fields( { kind, layer: string, center: point, radius: number, startAngle: number, endAngle: number }, shared, @@ -1029,6 +1032,8 @@ function shapes(all: boolean, typed = all): Shapes { underlayFrame: LEFT, wipeoutFrame: ruled(boolean), patterns: ruled(table(pattern)), + // lint judges the style whole, as the builder does. + pointStyle: LEFT, }, ); return { diff --git a/src/svg.ts b/src/svg.ts index 5501e9e..caa2062 100644 --- a/src/svg.ts +++ b/src/svg.ts @@ -37,6 +37,8 @@ import { type Rgb, type Paragraph, type Point, + type PointEntity, + type PointStyle, type Polyline, type Spline, type Text, @@ -63,6 +65,7 @@ import { writtenPoint, } from "./fills.ts"; import { patternPieces } from "./patterns.ts"; +import { pointFigure, pointReach, pointStyleProblems } from "./points.ts"; import { arcPoint, hasArcsOrWidths, @@ -1646,15 +1649,26 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): * block. */ let boxed: - | { shown: [number, Entity]; box: readonly [number, number, number, number]; slack: number }[] + | { + shown: [number, Entity]; + box: readonly [number, number, number, number]; + slack: number; + figure: FigureReach; + }[] | undefined; + const figures = figureReaches(drawing); /** How many times model space has been looked through. */ let views = 0; /** * The entities of model space that may reach into a rectangle of it, `[x0, y0, x1, y1]`, with * a pen that reaches `pen` past an entity's box. The test errs on the side of drawing. */ - const reaching = (rect: readonly number[], pen: number, where: string): [number, Entity][] => { + const reaching = ( + rect: readonly number[], + pen: number, + where: string, + height: number, + ): [number, Entity][] => { if (!boxed) { boxed = shownOf(drawing.entities).flatMap((shown) => { const box = boxOf([shown[1]], (e) => entityAt(shown[0], e, "model space")); @@ -1671,13 +1685,16 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): shown[1].kind === "underlay" ? missingReach(shown[1]) : 0; - return [{ shown, box, slack }]; + return [{ shown, box, slack, figure: figures(shown[1]) }]; }); } if (++views > FREE_VIEWS && !spend(Math.floor(boxed.length / 64))) refuse(where); + // A point's figure reaches past its point, by a share of the view for a relative size. + const reach = pointReach(pointStyle, height) ?? 0; + const relative = typeof pointStyle.size !== "number"; return boxed - .filter(({ box: b, slack }) => { - const by = pen + slack; + .filter(({ box: b, slack, figure }) => { + const by = pen + slack + reach * (relative ? figure.relative : figure.absolute); return ( b[0] - by <= rect[2]! && b[2] + by >= rect[0]! && @@ -1693,6 +1710,11 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // That app reads a scale of 0 or less as 1, and so is one that is not a finite number here. const stated = drawing.linetypeScale ?? 1; const linetypeScale = stated > 0 && Number.isFinite(stated) ? stated : 1; + // A style `lint` refuses plots each point as a dot. + const pointStyle: PointStyle = + drawing.pointStyle !== undefined && pointStyleProblems(drawing.pointStyle).length === 0 + ? drawing.pointStyle + : { figure: "dot" }; if (options.layout !== undefined) { const layout = findLayout(drawing, options.layout); const paper = layout && paperInfo(layout.paper); @@ -1708,17 +1730,18 @@ 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. */ - const plotted = (scale: number, indent: string): Look => ({ + const plotted = (scale: number, indent: string, points: PointLook): Look => ({ color, dashScale: linetypeScale / scale, chord: (paper.units === "in" ? 1 : 25.4) / 1200 / scale, indent, + points, stroke: (lineweight) => pen !== undefined || lineweight === DEFAULT_LINEWEIGHT ? "" : ` stroke-width="${precise((Math.max(lineweight, 5) * perHundredth) / scale)}"${lineweight === 0 ? THINNEST : ""}`, }); - const onPaper = plotted(1, " "); + const onPaper = plotted(1, " ", { style: pointStyle, height: paper.height, up: [0, 1] }); // A viewport's border plots as the thinnest line, or as the one pen a table gives every line. const thin = fmt((pen ?? 5) * perHundredth); const thinnest = pen === undefined ? THINNEST : ""; @@ -1826,11 +1849,17 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): // Only what may reach into it is drawn: an entity's box, which for an arc is its // circle's, with the widest pen there is and the slack of its letters around it. const widest = (LINEWEIGHTS.at(-1)! * 100 * perHundredth) / view.scale; - const reached = visible ? reaching(shows, widest, at) : []; + const reached = visible ? reaching(shows, widest, at, view.height / view.scale) : []; const near = frozenHere ? reached.filter(([, e]) => !frozenHere({ name: e.layer })) : reached; const inside = elements( near, - plotted(view.scale, " "), + plotted(view.scale, " ", { + style: pointStyle, + height: view.height / view.scale, + // Up the sheet, in model space: the view's twist turned back. + up: [Math.sin((view.twist * Math.PI) / 180), Math.cos((view.twist * Math.PI) / 180)], + dot: ` stroke-width="${precise((perHundredth * (2540 / 600)) / view.scale)}"`, + }), `model space in ${at}`, frozenHere, ); @@ -1904,6 +1933,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): [x, -(y + h), x + w, -y], Math.max(w, h) * Math.max(1, stroke), "the view of model space", + h, ) : all; // On a screen each layer draws in its own color, and every line keeps its width in pixels @@ -1913,6 +1943,7 @@ export function svgWithin(drawing: Drawing, options: SvgOptions, most: number): dashScale: linetypeScale, chord: 1 / 1200, indent: " ", + points: { style: pointStyle, height: h, up: [0, 1] }, stroke: (lineweight) => `${ lineweight === DEFAULT_LINEWEIGHT @@ -1978,6 +2009,23 @@ interface Look { readonly stroke: (lineweight: number) => string; /** The white space before an element, which what an insert holds is set in from. */ readonly indent: string; + /** How the space's points plot: the drawing's style, and the view they are seen in. */ + readonly points: PointLook; +} + +/** + * A space's points: the drawing's point style, the height of the view they are seen in and the + * direction up that view, in the space's units, which a relative size is measured by. + */ +interface PointLook { + readonly style: PointStyle; + readonly height: number; + readonly up: Point; + /** + * The stroke of a point drawn as a dot alone, where it is not the thinnest line: through a + * viewport the leading CAD app plots one a device pixel wide, 1/600 inch. + */ + readonly dot?: string; } /** What a drawing's entities name: its layers, its dash patterns and its text styles. */ @@ -2640,6 +2688,153 @@ function rounded( return { rx, ry, turn: ((Math.atan2(g, f) + Math.atan2(h, e)) * 90) / Math.PI, sweep }; } +/** + * How many times its figure's reach a point's figure may reach past an entity's box: 1 for a + * point, and for an insert what the points of its block reach once placed. A size in drawing units + * grows with each insert's larger scale; a relative one is not scaled but skewed, which stretches + * it by at most the larger scale over the smaller. Each block is walked once. + */ +interface FigureReach { + readonly absolute: number; + readonly relative: number; +} + +function figureReaches(drawing: Drawing): (e: Entity) => FigureReach { + const NONE: FigureReach = { absolute: 0, relative: 0 }; + const blocks = blocksByKey(drawing.blocks); + const key = layerKeys(); + // By each block's list of entities, so that blocks sharing one walk it once. + const known = new Map(); + /** The larger scale of an insert and the larger over the smaller, or undefined for none. */ + const scaleOf = (e: Insert): readonly [number, number] | undefined => { + const scale: unknown = e.scale ?? [1, 1]; + if (!Array.isArray(scale)) return undefined; + const [x, y]: unknown[] = [scale[0], scale[1]]; + if (typeof x !== "number" || typeof y !== "number") return undefined; + const [most, least] = [Math.max(Math.abs(x), Math.abs(y)), Math.min(Math.abs(x), Math.abs(y))]; + return least > 0 && Number.isFinite(most) ? [most, most / least] : undefined; + }; + interface Walk { + readonly list: unknown; + readonly items: readonly unknown[]; + readonly scale: readonly [number, number]; + i: number; + absolute: number; + relative: number; + } + const into = ( + to: { absolute: number; relative: number }, + r: FigureReach, + by: readonly number[], + ) => { + to.absolute = Math.max(to.absolute, r.absolute * by[0]!); + to.relative = Math.max(to.relative, r.relative * by[1]!); + }; + // A stack of its own, so that blocks nested however deep do not run out of the call stack. + const ofInsert = (e: Insert): FigureReach => { + const out = { absolute: 0, relative: 0 }; + const stack: Walk[] = []; + let at: { absolute: number; relative: number } = out; + let insert: Insert | undefined = e; + for (;;) { + if (insert !== undefined) { + const scale = scaleOf(insert); + const name = insert.block; + const list = + scale && typeof name === "string" ? blocks.get(key(name))?.entities : undefined; + const had = list === undefined ? NONE : known.get(list); + if (had) into(at, had, scale ?? [0, 0]); + else { + // A block inside itself reaches nothing more. + known.set(list, NONE); + const walk = { list, items: filled(list), scale: scale!, i: 0, absolute: 0, relative: 0 }; + stack.push(walk); + at = walk; + } + insert = undefined; + } + const top = stack.at(-1); + if (!top) return out; + if (top.i >= top.items.length) { + const found = { absolute: top.absolute, relative: top.relative }; + known.set(top.list, found); + stack.pop(); + at = stack.at(-1) ?? out; + into(at, found, top.scale); + continue; + } + const item = top.items[top.i++]; + if (typeof item !== "object" || item === null) continue; + const kind = (item as Entity).kind; + if (kind === "point") into(top, { absolute: 1, relative: 1 }, [1, 1]); + else if (kind === "insert") insert = item as Insert; + } + }; + const of = (e: Entity): FigureReach => + typeof e !== "object" || e === null + ? NONE + : e.kind === "point" + ? { absolute: 1, relative: 1 } + : e.kind === "insert" + ? ofInsert(e) + : NONE; + return of; +} + +/** + * A point's figure, in the thinnest line and solid, whatever its pen's lineweight and linetype. + * Under an insert it is placed as the block's lines are, and a relative size is measured in the + * block's units along the view's up direction taken back through the insert, so the insert's + * scale does not change it. + */ +function pointToSvg( + e: PointEntity, + mark: string, + pen: Pen, + look: Look, + matrix: Matrix | undefined, +): string { + const { style, height, up } = look.points; + // A point `lint` refuses draws nothing. + const [x0, y0] = Array.isArray(e.at) ? e.at : [NaN, NaN]; + const turn = e.rotation ?? 0; + if (![x0, y0, turn].every((n) => typeof n === "number" && Number.isFinite(n))) + return ``; + let reach = pointReach(style, height); + if (reach !== undefined && typeof style.size !== "number" && matrix) { + const [a, b, c, d] = matrix; + const det = a * d - b * c; + const back = Math.hypot(d * up[0] - c * up[1], a * up[1] - b * up[0]) / Math.abs(det); + reach = Number.isFinite(back) && back > 0 ? reach * back : undefined; + } + const parts = pointFigure(style, reach); + if (parts.length === 0) return ``; + const turned = rad(e.rotation ?? 0); + const [cos, sin] = [Math.cos(turned), Math.sin(turned)]; + const at = ([x, y]: Point): string => { + const local: Point = [e.at[0] + x * cos - y * sin, e.at[1] + x * sin + y * cos]; + const [px, py] = matrix ? mapPoint(matrix, local) : local; + return `${fmt(px)} ${fmt(py)}`; + }; + const alone = style.figure === "dot" && !style.circle && !style.square; + const s = `stroke="${pen.color}"${(alone && look.points.dot) || look.stroke(0)} data-part="figure"`; + const paths = parts.map((part) => { + if ("radius" in part) { + // Two halves, from the point the figure's turn puts at 0 degrees, as the circle plots. + const r = part.radius; + const round = rounded(r, matrix); + const arc = `A ${fmt(round.rx)} ${fmt(round.ry)} ${fmt(round.turn)} 0 ${round.sweep}`; + return ``; + } + const [first, ...rest] = part.points; + // A dot is a path of no length, which a round cap draws. + if (rest.length === 0) + return ``; + return ``; + }); + return `\n${look.indent} ${paths.join(`\n${look.indent} `)}\n${look.indent}`; +} + /** * @param mark - The data attributes of the element. * @param matrix - Where an insert puts the entity, for one that a block holds. @@ -2659,6 +2854,7 @@ function entityToSvg( // A lineweight of 0 draws as the thinnest line, as in the leading CAD app. const s = `stroke="${pen.color}"${look.stroke(pen.lineweight)} ${mark}`; const at = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + if (e.kind === "point") return pointToSvg(e, mark, pen, look, matrix); const plan = e.kind === "polyline" ? planOf(e, sides) : undefined; if (e.kind === "polyline" && plan) { return polylineToSvg(e, plan, mark, pen, look, matrix, room, sides); @@ -3198,6 +3394,8 @@ function dashedPath( ok = true; break; } + case "point": + return undefined; case "circle": { // A circle holds the whole number of patterns nearest its length, each stretched or // shrunk alike to go round it exactly, from a dash at its angle 0. One shorter than its diff --git a/test/format.test.ts b/test/format.test.ts index 2f9a10e..64c894f 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -39,7 +39,7 @@ function refusal(value: unknown): readonly Diagnostic[] { return assert.fail("fromJSON took the value"); } -const kinds = ` An entity's kind is "line", "polyline", "circle", "arc", "ellipse", "spline", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader", "image", "underlay", "hatch" or "wipeout"`; +const kinds = ` An entity's kind is "line", "polyline", "circle", "point", "arc", "ellipse", "spline", "text", "paragraph", "insert", "linear-dimension", "aligned-dimension", "leader", "image", "underlay", "hatch" or "wipeout"`; test("a drawing goes to JSON and back unchanged", () => { const drawing = sample(); diff --git a/test/points.test.ts b/test/points.test.ts new file mode 100644 index 0000000..626a30a --- /dev/null +++ b/test/points.test.ts @@ -0,0 +1,282 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + createDrawing, + lint, + pointStyleOf, + readDXF, + toDXF, + toSVG, + type Drawing, + type PointStyle, +} from "../src/index.ts"; +import { extents } from "../src/extents.ts"; +import { readProblems } from "./read-agreement.ts"; + +/** The groups of the `n`th record of `type` in a DXF from its subclass on, as `code=value`. */ +function point(dxf: string, n = 0): string[] { + const lines = dxf.split("\r\n"); + let at = -1; + for (let k = 0; k <= n; k++) + at = lines.findIndex((line, i) => i > at && line === "POINT" && lines[i - 1]!.trim() === "0"); + const out: string[] = []; + for (let i = at + 1; i + 1 < lines.length && lines[i]!.trim() !== "0"; i += 2) + out.push(`${lines[i]!.trim()}=${lines[i + 1]}`); + return out.slice(out.indexOf("100=AcDbPoint") + 1); +} + +const header = (dxf: string, name: string): string | undefined => { + const lines = dxf.split("\r\n"); + const at = lines.indexOf(name); + return at < 0 ? undefined : lines[at + 2]; +}; + +/** Each path of a point's figure in an SVG, as its numbers. */ +function figure(svg: string): number[][] { + return [...svg.matchAll(/]*data-part="figure"/g)].map((m) => + m[1]! + .split(/[ MLA]+/) + .filter((t) => t !== "") + .map(Number), + ); +} + +const sheet = (style: PointStyle, draw: (d: ReturnType) => void): Drawing => { + const d = createDrawing({ pointStyle: style }); + d.layout("A", { paper: "ANSI B" }, () => draw(d)); + return d.build(); +}; + +test("toDXF writes a point and the point style as the leading CAD app saves them", () => { + const d = createDrawing({ pointStyle: { figure: "cross", circle: true, size: { percent: 10 } } }); + d.point([1, 2]); + d.point([3, 4], { rotation: 30 }); + const dxf = toDXF(d.build()); + assert.deepEqual(point(dxf), ["10=1", "20=2", "30=0"]); + // The file holds the angle the figure turns clockwise by. + assert.deepEqual(point(dxf, 1), ["10=3", "20=4", "30=0", "50=330"]); + assert.equal(header(dxf, "$PDMODE"), "35"); + assert.equal(header(dxf, "$PDSIZE"), "-10"); + assert.equal(header(toDXF(createDrawing().build()), "$PDMODE"), undefined); +}); + +test("pointStyleOf reads PDMODE and PDSIZE as the leading CAD app plots them", () => { + assert.deepEqual(pointStyleOf(35, -10), { + figure: "cross", + circle: true, + size: { percent: 10 }, + }); + assert.deepEqual(pointStyleOf(100, 0.25), { + figure: "tick", + circle: true, + square: true, + size: 0.25, + }); + // A mode the app does not offer plots as a dot, and a size of 0 as 5% of the view. + assert.deepEqual(pointStyleOf(5, 0), { figure: "dot", size: { percent: 5 } }); + assert.deepEqual(pointStyleOf(131), { figure: "dot", size: { percent: 5 } }); + assert.deepEqual(pointStyleOf(), { figure: "dot", size: { percent: 5 } }); +}); + +test("the builder and lint refuse a point style and a point the file cannot hold", () => { + assert.throws(() => createDrawing({ pointStyle: { figure: "star" as "dot" } }), /figure must be/); + assert.throws(() => createDrawing({ pointStyle: { figure: "plus", size: -1 as 1 } }), /size/); + assert.throws( + () => createDrawing({ pointStyle: { figure: "plus", size: { percent: 0 as 1 } } }), + /percent/, + ); + assert.throws(() => createDrawing({ dxf: "R12", pointStyle: { figure: "plus" } }), /R12/); + assert.throws(() => createDrawing({ dxf: "R12" }).point([0, 0]), /R12/); + assert.equal(createDrawing().point([0, 0], { rotation: -30 }).build().entities[0]!.kind, "point"); + assert.deepEqual(createDrawing().point([0, 0], { rotation: 390 }).build().entities[0], { + kind: "point", + layer: "0", + at: [0, 0], + rotation: 30, + }); + + const built = createDrawing().point([1, 1]).build(); + const messages = (drawing: Drawing) => lint(drawing).map((d) => d.message); + assert.deepEqual(messages({ ...built, pointStyle: { figure: "plus", size: 1e100 as 1 } }), [ + "pointStyle's size: This value must be under 1e100, because the leading CAD app reads only two exponent digits from DXF and would take 1e+100 for 1e+10", + ]); + assert.ok( + messages({ ...built, entities: [{ kind: "point", layer: "0", at: [0, 0], rotation: 360 }] }) + .join() + .includes("rotation must be from 0 up to 360"), + ); + assert.ok( + messages({ ...built, dxf: "R12" }) + .join() + .includes("no points to R12"), + ); +}); + +test("readDXF reads a point and the point style back as they were drawn", async () => { + const d = createDrawing({ pointStyle: { figure: "plus", square: true, size: 0.5 } }); + d.point([1, 2]); + d.point([3, 4], { rotation: 12.345678 }); + const built = d.build(); + const read = await readDXF(toDXF(built), { geometry: true }); + assert.deepEqual(readProblems(built, read, "tsdraft"), []); + assert.deepEqual([read.header.pdmode, read.header.pdsize], [66, 0.5]); + assert.deepEqual(pointStyleOf(read.header.pdmode, read.header.pdsize), built.pointStyle); +}); + +test("a point's figure is its style's size, or a share of half the view it is seen in", () => { + const style: PointStyle = { figure: "plus", size: 0.25 }; + assert.deepEqual( + figure( + toSVG( + sheet(style, (d) => d.point([2, 3])), + { layout: "A" }, + ), + ), + [ + [1.75, 3, 2.25, 3], + [2, 2.75, 2, 3.25], + ], + ); + // 10% of half the 11-inch sheet, and turned 90 degrees. + const relative = sheet({ figure: "tick", size: { percent: 10 } }, (d) => + d.point([2, 3], { rotation: 90 }), + ); + const [x0, y0, x1, y1] = figure(toSVG(relative, { layout: "A" }))[0]!; + assert.deepEqual([x0, y0], [2, 3]); + assert.ok(Math.abs(x1! - (2 - 0.275)) < 1e-6 && Math.abs(y1! - 3) < 1e-6); +}); + +test("under an insert a sized figure scales with it and a relative one does not", () => { + const draw = (style: PointStyle) => { + const d = createDrawing({ pointStyle: style }); + d.block("MARK", {}, () => d.point([0, 0])); + d.layout("A", { paper: "ANSI B" }, () => d.insert("MARK", [2, 3], { scale: 2 })); + return figure(toSVG(d.build(), { layout: "A" })); + }; + // The tick runs from the point up half the size, in the block's units, scaled by 2. + assert.deepEqual(draw({ figure: "tick", size: 0.25 }), [[2, 3, 2, 3.25]]); + const [, , , top] = draw({ figure: "tick", size: { percent: 10 } })[0]!; + assert.ok(Math.abs(top! - (3 + 0.275)) < 1e-6, String(top)); +}); + +test("a dot alone plots a device pixel wide through a viewport, and the thinnest line on paper", () => { + const d = createDrawing(); + d.point([5, 5]); + d.layout("A", { paper: "ANSI B" }, (sheet) => { + d.point([1, 1]); + sheet.viewport([2, 2], 4, 4, { center: [5, 5], ratio: 2 }); + }); + const svg = toSVG(d.build(), { layout: "A" }); + const strokes = [...svg.matchAll(/]*data-part="figure"[^>]*>/g)].map((m) => m[0]); + assert.equal(strokes.length, 2); + assert.ok(strokes.some((s) => s.includes("data-thinnest"))); + // 1/600 inch on the sheet, in model units at a ratio of 2. + assert.ok( + strokes.some((s) => /stroke-width="0\.00333333/.test(s)), + strokes.join("\n"), + ); +}); + +test("a point counts in the extents at its point alone", () => { + const d = createDrawing({ pointStyle: { figure: "plus", circle: true, size: 10 } }); + d.point([1, 2]); + d.point([3, 5]); + assert.deepEqual(extents(d.build().entities), [1, 2, 3, 5]); +}); + +test("a figure that reaches into a view is drawn, from an insert and in a cropped sheet", () => { + const count = (svg: string) => (svg.match(/data-part="figure"/g) ?? []).length; + const d = createDrawing({ pointStyle: { figure: "plus", size: 1 } }); + d.block("MARK", {}, () => d.point([0, 0])); + // Its arm, 2 long under the scale, reaches the viewport's edge at x = 7 from 5.75. + d.insert("MARK", [7.75, 6], { scale: 2 }); + d.layout("A", { paper: "ANSI B" }, (s) => s.viewport([1, 1], 4, 4, { center: [5, 5], ratio: 1 })); + assert.equal(count(toSVG(d.build(), { layout: "A" })), 2); + + // A quarter of half the viewport's 8, whatever part of the sheet the picture shows. + const r = createDrawing({ pointStyle: { figure: "plus", size: { percent: 25 } } }); + r.point([5, 4.8]); + r.layout("A", { paper: "ANSI B" }, (s) => + s.viewport([2, 2], 10, 8, { center: [5, 4], ratio: 1 }), + ); + assert.equal(count(toSVG(r.build(), { layout: "A", view: [2, 2, 12, 6] })), 2); +}); + +test("a point or a point style lint refuses is no throw for the writers", () => { + const built = createDrawing().build(); + const broken = { ...built, entities: [{ kind: "point", layer: "0", at: null }] } as never; + assert.doesNotThrow(() => toSVG(broken)); + const odd = { figure: "plus", metadata: 0n } as unknown as PointStyle; + assert.deepEqual( + lint({ ...built, pointStyle: odd }).map((d) => d.message), + ['pointStyle has a field it does not know, "metadata"'], + ); + assert.throws(() => createDrawing({ pointStyle: odd }), /does not know/); + // The builder keeps a copy of the style, not the object it was given. + const size = { percent: 5 }; + const style = createDrawing({ pointStyle: { figure: "plus", size } }).build().pointStyle!; + assert.notEqual(style.size, size); +}); + +test("hostile points, styles and block chains are no throw and no runaway work", () => { + const built = createDrawing().build(); + for (const at of [ + [0n, 0], + [{}, 0], + ]) { + const svg = toSVG({ ...built, entities: [{ kind: "point", layer: "0", at }] } as never); + assert.ok(!svg.includes("NaN")); + } + const listed = { figure: "plus", size: Object.assign(Array(1), { percent: 5 }) }; + assert.equal(lint({ ...built, pointStyle: listed } as never).length, 1); + const [long] = lint({ + ...built, + pointStyle: { figure: "plus", ["\0".repeat(100_000)]: 1 }, + } as never); + assert.ok(long!.message.length < 400, long!.message.slice(0, 200)); + + // A chain of blocks deeper than the call stack, and a frozen insert whose scale is no number. + const blocks = Array.from({ length: 10_000 }, (_, i) => ({ + name: `B${i}`, + base: [0, 0], + entities: [ + i === 9_999 + ? { kind: "point", layer: "0", at: [0, 0] } + : { kind: "insert", layer: "0", block: `B${i + 1}`, at: [0, 0] }, + ], + })); + const odd = { + kind: "insert", + layer: "OFF", + block: "B9999", + at: [0, 0], + scale: [Object.create(null), 1], + }; + const deep = { + ...built, + layers: [...built.layers, { name: "OFF", frozen: true }], + blocks, + entities: [ + { kind: "line", layer: "0", from: [0, 0], to: [1, 1] }, + odd, + { kind: "insert", layer: "0", block: "B0", at: [50, 50] }, + ], + } as never; + assert.doesNotThrow(() => toSVG(deep, { view: [0, 0, 1, 1] })); + + // Many inserts of one long name work out its key once. + const name = "N".repeat(100_000); + const many = { + ...built, + blocks: [{ name, base: [0, 0], entities: [{ kind: "point", layer: "0", at: [0, 0] }] }], + entities: Array.from({ length: 2_000 }, () => ({ + kind: "insert", + layer: "0", + block: name, + at: [50, 50], + })), + } as never; + const start = performance.now(); + toSVG(many, { view: [0, 0, 1, 1] }); + assert.ok(performance.now() - start < 3_000); +}); diff --git a/test/read-agreement.ts b/test/read-agreement.ts index eec6467..108dedb 100644 --- a/test/read-agreement.ts +++ b/test/read-agreement.ts @@ -388,6 +388,18 @@ export function readProblems( say(`${label}: center ${got.center}, radius ${got.radius}`); } return; + case "point": + if (!kind("point") || got.kind !== "point") return; + if ( + !nearPoint(got.at, point(want.at)) || + // The file holds the turn the other way, as 360 less it, which comes back within bits. + Math.abs( + (((((got.rotation ?? 0) - written(want.rotation ?? 0)) % 360) + 540) % 360) - 180, + ) > 1e-9 + ) { + say(`${label}: at ${got.at}, turned ${got.rotation ?? 0}`); + } + return; case "arc": if (!kind("arc") || got.kind !== "arc") return; if ( diff --git a/test/read-fuzz.ts b/test/read-fuzz.ts index 67786fd..d1cecb3 100644 --- a/test/read-fuzz.ts +++ b/test/read-fuzz.ts @@ -177,6 +177,13 @@ export function seedFiles(): Uint8Array[] { }); underlays.insert("SEAL", [0, 10], { scale: [2, 1] }); }); + const points = createDrawing({ + pointStyle: { figure: "plus", circle: true, size: { percent: 5 } }, + }); + points.block("MARK", {}, () => points.point([0, 0])); + points.point([1, 2]); + points.point([3, 4], { rotation: 30 }); + points.insert("MARK", [5, 5], { scale: 2 }); return [ ...[ toDXF(sheet), @@ -186,6 +193,7 @@ export function seedFiles(): Uint8Array[] { toDXF(tables.build()), toDXF(curves.build()), toDXF({ ...underlays.build(), underlayFrame: "screen" }), + toDXF(points.build()), ].map((t) => encoder.encode(t)), leaderFile(), ]; diff --git a/test/shape-sweep.ts b/test/shape-sweep.ts index fe0797f..e99c59b 100644 --- a/test/shape-sweep.ts +++ b/test/shape-sweep.ts @@ -391,6 +391,7 @@ export const kinds: { textBelow: "MIN.", id: "h-o", }, + point: { kind: "point", layer: "0", at: [6, 5], rotation: 30, id: "w8", ...styled }, }; /** A polyline of one width, with every field the polyline of `kinds` leaves out. */ @@ -525,6 +526,7 @@ export const full: Required & { imageFrame: false, underlayFrame: "screen", wipeoutFrame: false, + pointStyle: { figure: "cross", circle: true, square: true, size: { percent: 10 } }, linetypes: [ { name: "DD", diff --git a/test/shape.test.ts b/test/shape.test.ts index 25e3be1..66dc80d 100644 --- a/test/shape.test.ts +++ b/test/shape.test.ts @@ -24,7 +24,7 @@ test("a value of the wrong shape is reported in these words, once", () => { { toString: 0 }, [ "xref: Xref a value of type object: A block's name must be a string", - `undefined-block: insert #23: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, + `undefined-block: insert #24: Block "BASE" is not defined. The leading CAD app's AUDIT reports an insert of a block the drawing does not have, and that app cannot save the drawing as DXF`, ], ], [ diff --git a/test/standard-lint.test.ts b/test/standard-lint.test.ts index 87a317c..0397266 100644 --- a/test/standard-lint.test.ts +++ b/test/standard-lint.test.ts @@ -175,8 +175,8 @@ test("a text plots at its role's height in each viewport that shows it, and at l assert.deepEqual( lint(half, { standard }).map((d) => d.message), [ - `text #53: This text of the role "note" plots 0.047 in tall in viewport "plan" at 1" = 10', and the role is 0.094 in: it was sized for another scale. Draw it in the view of the viewport that shows it`, - `text #53: This text plots 0.047 in tall in viewport "plan" at 1" = 10', below the standard's least height of 0.0625 in`, + `text #60: This text of the role "note" plots 0.047 in tall in viewport "plan" at 1" = 10', and the role is 0.094 in: it was sized for another scale. Draw it in the view of the viewport that shows it`, + `text #60: This text plots 0.047 in tall in viewport "plan" at 1" = 10', below the standard's least height of 0.0625 in`, ], ); // The model of the sheet at 1" = 10', shown at 1" = 20': every text and dimension is off. @@ -259,7 +259,7 @@ test("a dimension is shown at its style's scale", () => { assert.equal(found.length, 7); assert.match( found[0]!.message, - /^linear-dimension #29: It is in the dimension style "DIMS-1in-20ft", for 1" = 20', and is shown in viewport "plan" at 1" = 10'/, + /^linear-dimension #36: It is in the dimension style "DIMS-1in-20ft", for 1" = 20', and is shown in viewport "plan" at 1" = 10'/, ); }); From 4af6905192eec1e179e5671a2e89533966084b43 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sat, 21 Nov 2026 23:05:47 -0500 Subject: [PATCH 32/35] 3D solids, regions and bodies: read by their edges, drawn in plan - `readDXF` and `readDWG` read 3D solids, regions and bodies as `3dsolid`, `region` and `body`, each with its `edges` in 3D: lines, ellipses and arcs of them, and splines, in the world's coordinates. They read the data a file before 2013 keeps in the entity, as text in a DXF and binary in a DWG. A file of 2013 or later keeps the data apart from the entity, and a read of one says `dataUnread` until a later release reads it. An edge on no curve and a seam are left out, as CAD programs show neither; a solid with no body has no edges. - `edgesInPlan(solid)` turns a read solid into the lines, circles, arcs, ellipses and splines it shows from above, with its pen, for a drawing `toSVG` and `toPDF` draw. A circle seen at an angle is an ellipse, one seen edge on a line, and an edge that shows as one point is left out. - `satEdges`, `sabEdges` and `decipherSat` read the modeler data on its own. - Neither writer writes a solid, and the lines CAD programs draw along curved faces are not drawn yet. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 7 + docs/reading.md | 16 + src/index.ts | 8 + src/read/check.ts | 57 +++- src/read/dxf.ts | 3 + src/read/entities.ts | 52 +++- src/read/groups.ts | 2 +- src/read/model.ts | 65 ++++- src/read/modeler.ts | 682 +++++++++++++++++++++++++++++++++++++++++++ src/read/plan.ts | 202 +++++++++++++ test/modeler.test.ts | 208 +++++++++++++ 11 files changed, 1295 insertions(+), 7 deletions(-) create mode 100644 src/read/modeler.ts create mode 100644 src/read/plan.ts create mode 100644 test/modeler.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d85789..a5c479c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- 3D solids, regions and bodies are read. `readDXF` and `readDWG` read each as a `3dsolid`, + `region` or `body` with its `edges` in 3D, from the modeler data a file before 2013 holds in the + entity, as text or binary; a file of 2013 or later keeps the data apart from the entity, and a + read of one says `dataUnread` until a later release reads it. `edgesInPlan` turns a read solid + into the lines, arcs, ellipses and splines it shows from above, which `toSVG` and `toPDF` draw. + `satEdges`, `sabEdges` and `decipherSat` read the data on its own. Neither writer writes a + solid, and the lines CAD programs draw along curved faces are not drawn yet. - `readDWG` reads drawings saved in the 2004, 2007, 2010 and 2013 formats as well as 2018's, into the same read model, as CAD programs read them when they open the file: a 2004 file's text in its code page, each `\U+XXXX` in it as its character, a table of the 2004 or 2007 format as one of diff --git a/docs/reading.md b/docs/reading.md index 83253ef..7744961 100644 --- a/docs/reading.md +++ b/docs/reading.md @@ -248,6 +248,22 @@ leader: of the plane is counted under `other`. - An `mtext` with a background holds `mask`: its `offsetFactor`, and its `color` or `trueColor` where it is not in the drawing's background. +- `3dsolid`, `region` and `body`, which CAD programs keep as modeler data: their `edges`, in the + order the data holds them, in the world's coordinates and in 3D, each a `line` from one point to + another, an `ellipse` with its `center`, `normal`, `majorAxis`, `ratio` and, for an arc of one, + its `startParameter` and `endParameter` in degrees, or a `spline` cut to the edge, with its + `degree`, `knots`, `controlPoints` and `weights`. An edge on no curve, such as a cone's apex, + and a seam, where a face meets itself, are left out, as CAD programs show neither. A solid with + no body has no edges. `edgesUnread` counts the edges on a curve the reader does not follow, and + `dataUnread` says the reader does not read the data at all, which a file of 2013 or later keeps + apart from the entity. `satEdges` and `sabEdges` read the data's text and binary forms, and + `decipherSat` the cipher a file before 2013 keeps the text in. + `edgesInPlan` turns one into the lines, circles, arcs, ellipses and splines it shows from above, + with its pen, for a drawing that `toSVG` and `toPDF` draw: a circle seen at an angle is an + ellipse, one seen edge on a line, and an edge that shows as one point, such as a vertical line, + is left out. CAD programs also draw lines along a solid's curved faces, which tsdraft does not + draw yet. Adding the result to a drawing you write gives plain linework: neither writer writes + a solid. `header.wipeoutFrame` is the file's dictionary variable `WIPEOUTFRAME`, which CAD programs read of whether wipeouts' frames show: 0 neither shown nor plotted, 1 both, 2 shown and not plotted. A diff --git a/src/index.ts b/src/index.ts index 015486f..07c26c9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -486,6 +486,8 @@ export { checkDrawingRead } from "./read/check.ts"; export { readDXF } from "./read/dxf.ts"; 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 { BLOCK_ITEMS, CENSUS_LIMIT, @@ -514,6 +516,10 @@ export { type ReadOrdinateDimension, type ReadDimensionStyle, type ReadDrawingFile, + type ReadEdge, + type ReadEdgeEllipse, + type ReadEdgeLine, + type ReadEdgeSpline, type ReadEntity, type ReadColorBook, type ReadEntityBase, @@ -534,10 +540,12 @@ export { type ReadLinetype, type ReadLinetypeMark, type ReadMask, + type ReadModelerGeometry, type ReadMtext, type ReadPatternLine, type ReadMultileader, type ReadOptions, + type Point3, type ReadPolyline, type ReadSolid, type ReadSpace, diff --git a/src/read/check.ts b/src/read/check.ts index 6f68865..dbb2d17 100644 --- a/src/read/check.ts +++ b/src/read/check.ts @@ -10,6 +10,8 @@ type Type = | "number" | "boolean" | "point" + /** A point in space: three finite numbers. */ + | "point3" | "count" /** An entity's opacity: a whole number from 0 to 255, or `"ByBlock"`. */ | "alpha" @@ -147,7 +149,43 @@ const INSERT: Fields = { "attributes?": { list: { fields: ATTRIBUTE } }, }; +/** An edge of a solid, a region or a body. */ +const EDGE: Type = { + either: [ + { kind: { oneOf: ["line"] }, from: "point3", to: "point3" }, + { + kind: { oneOf: ["ellipse"] }, + center: "point3", + normal: "point3", + majorAxis: "point3", + ratio: "number", + "startParameter?": "number", + "endParameter?": "number", + }, + { + kind: { oneOf: ["spline"] }, + degree: "count", + knots: { list: "number" }, + controlPoints: { list: "point3" }, + "weights?": { list: "number" }, + }, + ], + named: "a line, an ellipse or a spline edge", +}; + +/** A solid, a region or a body, by its kind. */ +const MODELER = (kind: string): Fields => ({ + ...BASE, + kind: { oneOf: [kind] }, + edges: { list: EDGE }, + "edgesUnread?": "count", + "dataUnread?": "boolean", +}); + const ENTITY: Readonly> = { + "3dsolid": MODELER("3dsolid"), + region: MODELER("region"), + body: MODELER("body"), line: { ...BASE, kind: { oneOf: ["line"] }, from: "point", to: "point" }, polyline: { ...BASE, @@ -716,14 +754,14 @@ function onlyItems(v: unknown[]): boolean { } /** - * The items of a plain list whose every slot holds a value, read without running a getter, or - * `undefined` for anything else. + * The items of a plain list of at most `most` whose every slot holds a value, read without running + * a getter, or `undefined` for anything else. */ -function plainList(v: unknown): unknown[] | undefined { +function plainList(v: unknown, most = 2): unknown[] | undefined { if ( !Array.isArray(v) || Object.getPrototypeOf(v) !== Array.prototype || - v.length > 2 || + v.length > most || !onlyItems(v) ) { return undefined; @@ -780,6 +818,17 @@ export function checkDrawingRead(value: unknown): string[] { say(at, 'must be a whole number from 0 to 255, or "ByBlock"'); } return; + case "point3": { + const xyz = plainList(v, 3); + if ( + xyz === undefined || + xyz.length !== 3 || + !xyz.every((n) => typeof n === "number" && Number.isFinite(n)) + ) { + say(at, "must be three finite numbers"); + } + return; + } case "point": { const xy = plainList(v); if ( diff --git a/src/read/dxf.ts b/src/read/dxf.ts index fca2ec3..f677b29 100644 --- a/src/read/dxf.ts +++ b/src/read/dxf.ts @@ -189,10 +189,12 @@ const CENSUS: ReadonlySet = new Set([5, 6, 8, 60, 62, 67, 102, 330, 370, const VISIBILITY: ReadonlySet = new Set([60]); /** The kinds a block's definition reads whole, and a space's with `geometry`. */ const BLOCK_READS = new Set([ + "3DSOLID", "ACAD_TABLE", "ARC", "ATTDEF", "ATTRIB", + "BODY", "CIRCLE", "DIMENSION", "ELLIPSE", @@ -209,6 +211,7 @@ const BLOCK_READS = new Set([ "PDFUNDERLAY", "POINT", "POLYLINE", + "REGION", "SEQEND", "SOLID", "SPLINE", diff --git a/src/read/entities.ts b/src/read/entities.ts index bf64018..010c175 100644 --- a/src/read/entities.ts +++ b/src/read/entities.ts @@ -2,7 +2,8 @@ // coordinates with the pen it sets for itself. import type { ParagraphColumns } from "../paragraphs.ts"; import type { Point } from "../drawing.ts"; -import { textOnce, textTwice } from "./groups.ts"; +import { carets, textOnce, textTwice } from "./groups.ts"; +import { decipherSat, satEdges } from "./modeler.ts"; import { readAlpha } from "../transparency.ts"; import { wholeImageClip } from "../images.ts"; import { UNDERLAY_CONTRAST_DEFAULT, UNDERLAY_FADE_DEFAULT } from "../underlays.ts"; @@ -10,6 +11,7 @@ import type { ReadAttribute, ReadAttributeParagraph, ReadDimension, + ReadEdge, ReadRadialDimension, ReadAngularDimension, ReadArcLengthDimension, @@ -291,6 +293,10 @@ export function readingOf( return hatch(r, base, face); case "WIPEOUT": return wipeout(r, base); + case "3DSOLID": + case "REGION": + case "BODY": + return modeler(r, base); case "SOLID": { if (face === 0) return { other: "SOLID in 3D" }; const corner = (code: number): Point => @@ -302,6 +308,34 @@ export function readingOf( } } +/** + * A solid, a region or a body by the edges of its modeler data. A file before 2013 holds the data + * in its record, as lines of groups 1 and 3 in a cipher with DXF's carets; a later one holds it in + * the file's data storage, which is not read, and says so with group 290. + */ +function modeler(r: Rec, base: ReadEntityBase): Reading { + const kind = r.type === "3DSOLID" ? "3dsolid" : r.type === "REGION" ? "region" : "body"; + const s = inSubclass(r, "AcDbModelerGeometry"); + // A long line is held as groups 3, its first parts, and then a group 1, its end. + const lines: string[] = []; + let start = ""; + for (let i = 0; i < s.codes.length && s.codes[i] !== 1001; i++) { + const code = s.codes[i]; + if (code === 3) start += decipherSat(carets(s.values[i]!)); + else if (code === 1) { + lines.push(start + decipherSat(carets(s.values[i]!))); + start = ""; + } + } + if (lines.length === 0) { + const stored = s.codes.includes(290); + return { entity: { ...base, kind, edges: [], ...(stored && { dataUnread: true as const }) } }; + } + const { edges, unread } = satEdges(lines.join("\n") + "\n"); + if (unread < 0) return { entity: { ...base, kind, edges: [], dataUnread: true } }; + return { entity: { ...base, kind, edges, ...(unread > 0 && { edgesUnread: unread }) } }; +} + /** * An image as its file places it. Its clip is held in the image's pixels, as the file holds it, * a polygon without its first point again at its end, and its path is the definition's, which @@ -1422,6 +1456,18 @@ export const attributeCost = (a: ReadAttribute): number => (a.colorBook ? chars(a.colorBook.book) + chars(a.colorBook.name) : 0) + (a.paragraph ? 2 + chars(a.paragraph.style) : 0); +/** What an edge of a solid costs: one for each point or vector it holds, and each knot and weight. */ +function edgeCost(e: ReadEdge): number { + switch (e.kind) { + case "line": + return 2; + case "ellipse": + return 4; + case "spline": + return 1 + e.knots.length + e.controlPoints.length + (e.weights?.length ?? 0); + } +} + /** * What an entity costs against `BLOCK_ITEMS` or `GEOMETRY_ITEMS`: one, and one more for each of * its points, bulges and pairs of widths, each attribute or tag, and each 32 characters of its @@ -1505,6 +1551,10 @@ export function costOf(e: ReadEntity): number { } case "wipeout": return own + e.points.length; + case "3dsolid": + case "region": + case "body": + return own + e.edges.reduce((sum, edge) => sum + edgeCost(edge), 0); case "table": return ( own + diff --git a/src/read/groups.ts b/src/read/groups.ts index 846bdcb..6c81db4 100644 --- a/src/read/groups.ts +++ b/src/read/groups.ts @@ -225,7 +225,7 @@ function latin1(bytes: Uint8Array): string { * A value with its carets worked out: a caret and a space is a caret, and a caret before a * character from `@` on is the control character 64 below it, so `^J` is a line feed. */ -function carets(value: string): string { +export function carets(value: string): string { if (!value.includes("^")) return value; return value.replace(/\^([\s\S])/g, (whole, c: string) => { if (c === " ") return "^"; diff --git a/src/read/model.ts b/src/read/model.ts index 9997ae5..8295dcc 100644 --- a/src/read/model.ts +++ b/src/read/model.ts @@ -1014,6 +1014,68 @@ export interface ReadSpline extends ReadEntityBase { readonly knotSpacing?: KnotSpacing; } +/** A point in space: x, y and z, in the world's coordinates. */ +export type Point3 = readonly [x: number, y: number, z: number]; + +/** A straight edge from one point to another. */ +export interface ReadEdgeLine { + readonly kind: "line"; + readonly from: Point3; + readonly to: Point3; +} + +/** + * An edge on an ellipse or a circle in any plane: the point at a parameter t is + * `center + cos(t) * majorAxis + sin(t) * ratio * (normal × majorAxis)`. + */ +export interface ReadEdgeEllipse { + readonly kind: "ellipse"; + readonly center: Point3; + /** Of length 1. Seen from its tip, the parameters run counterclockwise. */ + readonly normal: Point3; + /** From the center to the end of the longer axis. */ + readonly majorAxis: Point3; + /** The shorter axis over the longer, above 0 and at most 1: 1 for a circle. */ + readonly ratio: number; + /** + * For an arc, in degrees from 0 up to 360, and the end a turn at most past the start. Left out, + * with `endParameter`, for a whole ellipse. + */ + readonly startParameter?: number; + readonly endParameter?: number; +} + +/** An edge on a B-spline in space, cut to the edge: clamped at both its ends. */ +export interface ReadEdgeSpline { + readonly kind: "spline"; + readonly degree: number; + readonly knots: readonly number[]; + readonly controlPoints: readonly Point3[]; + /** One for each control point, for a rational spline. */ + readonly weights?: readonly number[]; +} + +/** An edge of a solid, a region or a body. */ +export type ReadEdge = ReadEdgeLine | ReadEdgeEllipse | ReadEdgeSpline; + +/** + * A 3D solid, a region or a body: the entities CAD programs keep as modeler data. It reads as its + * edges, in the world's coordinates and in 3D, which `edgesInPlan` turns into the lines, arcs, + * ellipses and splines it shows from above. + */ +export interface ReadModelerGeometry extends ReadEntityBase { + readonly kind: "3dsolid" | "region" | "body"; + /** Its edges, in the order its data holds them. None for one whose data holds no body. */ + readonly edges: readonly ReadEdge[]; + /** + * How many edges its data holds that the reader does not follow, such as one on a curve of a + * kind it does not know. Left out at 0. + */ + readonly edgesUnread?: number; + /** True when the reader does not read its data at all, so `edges` is empty whatever it holds. */ + readonly dataUnread?: true; +} + /** What a space or a block draws, of the kinds the writers write. */ export type ReadEntity = | ReadLine @@ -1038,7 +1100,8 @@ export type ReadEntity = | ReadUnderlay | ReadHatch | ReadWipeout - | ReadTable; + | ReadTable + | ReadModelerGeometry; export interface ReadBlock { /** The handle of the block's record, which an insert's block record points to. */ diff --git a/src/read/modeler.ts b/src/read/modeler.ts new file mode 100644 index 0000000..01b0365 --- /dev/null +++ b/src/read/modeler.ts @@ -0,0 +1,682 @@ +// The edges of a 3D solid, a region or a body, from the modeler data a file keeps for it in the +// text form (SAT) that DXF files and DWG files before 2013 hold. The data is a list of records, +// each ending at `#`, that point at each other by their place in the list as `$n`. Each `edge` +// record names the two vertices it runs between, its range of parameters, the curve it lies on and +// whether it runs along the curve or against it. The body's `transform`, when it has one, places +// all of it in the world. +import type { Point3, ReadEdge } from "./model.ts"; + +/** The edges read from a solid's data, and how many it holds that the reader does not follow. */ +export interface ModelerEdges { + readonly edges: ReadEdge[]; + readonly unread: number; +} + +/** The oldest version of the text form read: the one files of the 2004 format hold. */ +const OLDEST = 20800; + +/** The most records read of one solid's data. A record takes at least 2 characters. */ +const MOST_RECORDS = 1 << 22; + +/** A record: its name, and its fields after the name as the text holds them. */ +interface SatRecord { + readonly name: string; + readonly fields: readonly string[]; + /** The subtype data between braces, for the curves that hold it. */ + readonly braces?: readonly string[]; +} + +/** What starts a string of the data, so that none reads as a brace or a record's end. */ +const STRING = "\u0002"; + +/** Splits the text into its tokens: words, `{`, `}`, `#`, and `@n` strings, each one token. */ +function tokens(text: string, from: number): string[] { + const out: string[] = []; + let at = from; + const n = text.length; + while (at < n) { + const c = text.charCodeAt(at); + if (c <= 32) { + at++; + continue; + } + if (c === 64 /* @ */) { + let end = at + 1; + while (end < n && text.charCodeAt(end) >= 48 && text.charCodeAt(end) <= 57) end++; + const length = Number(text.slice(at + 1, end)); + const start = end + 1; + out.push(STRING + text.slice(start, Math.min(n, start + length))); + at = start + length; + continue; + } + if (c === 35 /* # */ || c === 123 /* { */ || c === 125 /* } */) { + out.push(text[at]!); + at++; + continue; + } + let end = at + 1; + while (end < n) { + const d = text.charCodeAt(end); + if (d <= 32 || d === 35 || d === 123 || d === 125) break; + end++; + } + out.push(text.slice(at, end)); + at = end; + } + return out; +} + +/** The records of the text, or undefined for a text of a version or a form not read. */ +function satRecords(text: string): { version: number; list: SatRecord[] } | undefined { + // The header: a line of the version and counts, a line of the product's names, and a line of + // the units and the tolerances. + let at = 0; + const lines: string[] = []; + for (let i = 0; i < 3; i++) { + const end = text.indexOf("\n", at); + if (end < 0) return undefined; + lines.push(text.slice(at, end)); + at = end + 1; + } + const version = Number(lines[0]!.trim().split(/\s+/)[0]); + if (!Number.isInteger(version) || version < OLDEST) return undefined; + return { version, list: recordsOf(tokens(text, at)) }; +} + +/** What a true flag of the binary form reads as, which no word of the text form is. */ +const TRUE = "\u0001"; + +/** Whether a flag is set: `reversed` and `shear` in the text form, true in the binary form. */ +const set = (field: string | undefined): boolean => + field === TRUE || field === "reversed" || field === "shear"; + +/** + * The records of the binary form (SAB), or undefined for one of a version or a form not read. It + * holds the text form's tokens, each after a byte that says its kind: a number of 4 or 8 bytes, a + * pointer, a string, a part of a record's name, a point or a vector of three numbers, a flag, a + * brace, or a record's end. Its header is a line of 15 characters and four numbers of 4 bytes, the + * version first; the product's names and the units follow as tokens before the first record. + */ +function sabRecords(bytes: Uint8Array): { version: number; list: SatRecord[] } | undefined { + if (bytes.length < 31) return undefined; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const version = view.getInt32(15, true); + if (version < OLDEST) return undefined; + const latin = (from: number, n: number): string => { + let s = ""; + for (let i = from; i < from + n; i++) s += String.fromCharCode(bytes[i]!); + return s; + }; + const all: string[] = []; + let name = ""; + let started = false; + let at = 31; + const n = bytes.length; + while (at < n) { + const tag = bytes[at++]!; + const need = (k: number): boolean => at + k <= n; + switch (tag) { + case 0x04: + case 0x0c: + case 0x15: { + if (!need(4)) return undefined; + const v = view.getInt32(at, true); + all.push(tag === 0x0c ? `$${v}` : tag === 0x15 ? `E${v}` : String(v)); + at += 4; + break; + } + case 0x06: + if (!need(8)) return undefined; + all.push(String(view.getFloat64(at, true))); + at += 8; + break; + case 0x13: + case 0x14: + if (!need(24)) return undefined; + for (let k = 0; k < 3; k++) all.push(String(view.getFloat64(at + 8 * k, true))); + at += 24; + break; + case 0x07: + case 0x0d: + case 0x0e: { + if (!need(1)) return undefined; + const length = bytes[at++]!; + if (!need(length)) return undefined; + const word = latin(at, length); + at += length; + if (tag === 0x07) all.push(STRING + word); + else if (tag === 0x0e) name += `${word}-`; + else { + // The tokens before the first record's name are the header's: names and units. + if (!started) { + all.length = 0; + started = true; + } + all.push(name + word); + name = ""; + } + break; + } + case 0x0a: + case 0x0b: + all.push(tag === 0x0a ? TRUE : "F"); + break; + case 0x0f: + all.push("{"); + break; + case 0x10: + all.push("}"); + break; + case 0x11: + all.push("#"); + break; + default: + return undefined; + } + if (all.length > 8 * MOST_RECORDS) return undefined; + } + return { version, list: recordsOf(all) }; +} + +/** The records of a list of tokens, each its name and its tokens up to its `#`. */ +function recordsOf(all: readonly string[]): SatRecord[] { + const list: SatRecord[] = []; + let i = 0; + while (i < all.length && list.length < MOST_RECORDS) { + const name = all[i]!; + if (name.startsWith("End-of-")) break; + const fields: string[] = []; + let braces: string[] | undefined; + let depth = 0; + i++; + for (; i < all.length; i++) { + const t = all[i]!; + if (t === "#" && depth === 0) break; + if (t === "{") { + depth++; + braces ??= []; + braces.push(t); + continue; + } + if (t === "}") { + depth = Math.max(0, depth - 1); + braces?.push(t); + continue; + } + if (depth > 0) braces!.push(t); + else fields.push(t); + } + i++; + list.push(braces === undefined ? { name, fields } : { name, fields, braces }); + } + return list; +} + +/** Whether a record is of a kind, or of a kind made from it, as `tedge-edge` is an edge. */ +const isKind = (name: string, kind: string): boolean => name === kind || name.endsWith(`-${kind}`); + +/** + * Whether an edge is a seam: one where a face meets itself, whose two coedges lie on one face, as + * where a swept tube closes. CAD programs show no seam. + */ +function seam(list: readonly SatRecord[], edge: SatRecord): boolean { + const coedge = list[pointer(edge.fields[7])]; + if (coedge === undefined || !isKind(coedge.name, "coedge")) return false; + const partner = list[pointer(coedge.fields[5])]; + if (partner === undefined || partner === coedge || !isKind(partner.name, "coedge")) return false; + const face = (c: SatRecord) => { + const loop = list[pointer(c.fields[8])]; + return loop?.name === "loop" ? pointer(loop.fields[5]) : -1; + }; + return face(coedge) >= 0 && face(coedge) === face(partner); +} + +const pointer = (field: string | undefined): number => + field !== undefined && field.startsWith("$") ? Number(field.slice(1)) : -1; + +const numbers = (fields: readonly string[], from: number, count: number): number[] | undefined => { + const out: number[] = []; + for (let i = from; i < from + count; i++) { + const v = Number(fields[i]); + if (fields[i] === undefined || !Number.isFinite(v)) return undefined; + out.push(v); + } + return out; +}; + +/** How a body is placed in the world: a point's row times `rows`, times `scale`, plus `move`. */ +interface Placement { + readonly rows: readonly [Point3, Point3, Point3]; + readonly move: Point3; + readonly scale: number; +} + +const placePoint = (p: Point3, t: Placement | undefined): Point3 => + t === undefined + ? p + : [ + (p[0] * t.rows[0][0] + p[1] * t.rows[1][0] + p[2] * t.rows[2][0]) * t.scale + t.move[0], + (p[0] * t.rows[0][1] + p[1] * t.rows[1][1] + p[2] * t.rows[2][1]) * t.scale + t.move[1], + (p[0] * t.rows[0][2] + p[1] * t.rows[1][2] + p[2] * t.rows[2][2]) * t.scale + t.move[2], + ]; + +const placeVector = (v: Point3, t: Placement | undefined): Point3 => + t === undefined + ? v + : [ + (v[0] * t.rows[0][0] + v[1] * t.rows[1][0] + v[2] * t.rows[2][0]) * t.scale, + (v[0] * t.rows[0][1] + v[1] * t.rows[1][1] + v[2] * t.rows[2][1]) * t.scale, + (v[0] * t.rows[0][2] + v[1] * t.rows[1][2] + v[2] * t.rows[2][2]) * t.scale, + ]; + +const cross = (a: Point3, b: Point3): Point3 => [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], +]; +const length = (a: Point3): number => Math.hypot(a[0], a[1], a[2]); +const unit = (a: Point3): Point3 | undefined => { + const l = length(a); + return l > 0 && Number.isFinite(l) ? [a[0] / l, a[1] / l, a[2] / l] : undefined; +}; + +/** The placement of the first body's `transform`, or undefined when it has none. */ +function placementOf(list: readonly SatRecord[]): Placement | undefined | null { + const body = list.find((r) => r.name === "body"); + if (body === undefined) return undefined; + const at = pointer(body.fields[5]); + if (at < 0) return undefined; + const t = list[at]; + if (t?.name !== "transform") return null; + const v = numbers(t.fields, 2, 13); + if (v === undefined) return null; + // A shear is not a placement this reader follows. + if (set(t.fields[17])) return null; + return { + rows: [ + [v[0]!, v[1]!, v[2]!], + [v[3]!, v[4]!, v[5]!], + [v[6]!, v[7]!, v[8]!], + ], + move: [v[9]!, v[10]!, v[11]!], + scale: v[12]!, + }; +} + +/** The point a vertex record names, by its last pointer. */ +function vertexPoint(list: readonly SatRecord[], at: number): Point3 | undefined { + const v = list[at]; + if (v === undefined || !isKind(v.name, "vertex")) return undefined; + // The point is the last pointer, among the last few fields. + for (let i = v.fields.length - 1; i >= Math.max(0, v.fields.length - 4); i--) { + const p = pointer(v.fields[i]); + if (p >= 0) { + const r = list[p]; + if (r?.name !== "point") return undefined; + const xyz = numbers(r.fields, 3, 3); + return xyz === undefined ? undefined : [xyz[0]!, xyz[1]!, xyz[2]!]; + } + } + return undefined; +} + +/** A B-spline as the modeler data holds it, its knots with their end knots added once more. */ +interface Bspline { + readonly degree: number; + readonly knots: number[]; + readonly points: Point3[]; + readonly weights?: number[]; +} + +/** + * The B-spline that opens a curve's subtype data: `nubs` or `nurbs`, the degree, `open`, `closed` + * or `periodic`, the count of distinct knots, each knot and how many times it repeats, then each + * control point, with its weight for `nurbs`. Each end knot repeats one time fewer than a clamped + * B-spline's, so each is added once more. + */ +function bsplineAt(data: readonly string[], from: number, end = data.length): Bspline | undefined { + const kind = data[from]; + if (kind !== "nubs" && kind !== "nurbs") return undefined; + const degree = Number(data[from + 1]); + const count = Number(data[from + 3]); + if (!Number.isInteger(degree) || degree < 1 || degree > 25) return undefined; + if (!Number.isInteger(count) || count < 2 || from + 4 + 2 * count > end) return undefined; + const knots: number[] = []; + let at = from + 4; + for (let i = 0; i < count; i++) { + const k = Number(data[at]); + const times = Number(data[at + 1]); + at += 2; + if (!Number.isFinite(k) || !Number.isInteger(times) || times < 1 || times > degree + 1) + return undefined; + if (knots.length > 0 && k < knots[knots.length - 1]!) return undefined; + for (let j = 0; j < times; j++) knots.push(k); + } + knots.unshift(knots[0]!); + knots.push(knots[knots.length - 1]!); + const n = knots.length - degree - 1; + const rational = kind === "nurbs"; + const per = rational ? 4 : 3; + if (n < degree + 1 || at + n * per > end) return undefined; + const points: Point3[] = []; + const weights: number[] = []; + for (let i = 0; i < n; i++) { + const v = numbers(data, at, per); + if (v === undefined) return undefined; + points.push([v[0]!, v[1]!, v[2]!]); + if (rational) { + if (!(v[3]! > 0)) return undefined; + weights.push(v[3]!); + } + at += per; + } + return rational ? { degree, knots, points, weights } : { degree, knots, points }; +} + +/** A subtype's data: its tokens, from `from` up to `to`, in its record's braces. */ +interface Subtype { + readonly tokens: readonly string[]; + readonly from: number; + readonly to: number; +} + +/** The subtypes the data defines, by the number `ref n` names: each brace not of a `ref`, in order. */ +function subtypes(list: readonly SatRecord[]): Subtype[] { + const out: Subtype[] = []; + for (const r of list) { + const b = r.braces; + if (b === undefined) continue; + const opens: [start: number, index: number][] = []; + for (let i = 0; i < b.length; i++) { + if (b[i] === "{") { + if (b[i + 1] === "ref") opens.push([i, -1]); + else { + opens.push([i, out.length]); + out.push({ tokens: b, from: i + 1, to: i + 1 }); + } + } else if (b[i] === "}") { + const open = opens.pop(); + if (open !== undefined && open[1] >= 0) + out[open[1]] = { tokens: b, from: open[0] + 1, to: i }; + } + } + } + return out; +} + +/** The B-spline of an intcurve's subtype: within its first tokens, after `full` or its version. */ +function curveSpline( + data: Subtype, + shared: readonly Subtype[], + read: Map, + work: { left: number }, + depth = 0, +): Bspline | undefined { + const t = data.tokens; + if (t[data.from] === "ref") { + const target = shared[Number(t[data.from + 1])]; + return target === undefined || depth > 8 + ? undefined + : curveSpline(target, shared, read, work, depth + 1); + } + // A subtype many curves name is read once, and each read is paid for, whether or not it reads. + if (read.has(data)) return read.get(data); + work.left -= data.to - data.from; + let s: Bspline | undefined; + for (let at = data.from; at < Math.min(data.to, data.from + 5); at++) { + if (t[at] === "nubs" || t[at] === "nurbs") { + s = bsplineAt(t, at, data.to); + break; + } + } + read.set(data, s); + return s; +} + +/** The subtype a curve record opens: the data from its first brace to its match. */ +function ownSubtype(r: SatRecord): Subtype | undefined { + const b = r.braces; + if (b === undefined || b[0] !== "{") return undefined; + let depth = 0; + for (let i = 0; i < b.length; i++) { + if (b[i] === "{") depth++; + else if (b[i] === "}" && --depth === 0) return { tokens: b, from: 1, to: i }; + } + return undefined; +} + +/** Inserts the knot `u` into a B-spline in homogeneous form until it repeats `times` times. */ +function insertKnot( + degree: number, + knots: number[], + points: number[][], + u: number, + times: number, +): void { + for (let r = 0; r < times; r++) { + let k = degree; + while (k + 1 < knots.length - degree - 1 && knots[k + 1]! <= u) k++; + const out: number[][] = []; + for (let i = 0; i < points.length + 1; i++) { + if (i <= k - degree) out.push(points[i]!); + else if (i > k) out.push(points[i - 1]!); + else { + const a = (u - knots[i]!) / (knots[i + degree]! - knots[i]!); + out.push(points[i]!.map((c, j) => (1 - a) * points[i - 1]![j]! + a * c)); + } + } + knots.splice(k + 1, 0, u); + points.length = 0; + for (const q of out) points.push(q); + } +} + +/** The B-spline cut to its parameters from `a` to `b`, clamped at both ends. */ +function cut(s: Bspline, a: number, b: number): Bspline | undefined { + const p = s.degree; + const knots = [...s.knots]; + const lo = knots[p]!; + const hi = knots[knots.length - p - 1]!; + const from = Math.max(lo, Math.min(a, b)); + const to = Math.min(hi, Math.max(a, b)); + if (!(to > from)) return undefined; + const w = s.weights; + const points = s.points.map((q, i) => { + const wi = w?.[i] ?? 1; + return [q[0] * wi, q[1] * wi, q[2] * wi, wi]; + }); + const times = (u: number) => knots.filter((k) => k === u).length; + if (from > lo || times(from) < p + 1) insertKnot(p, knots, points, from, p + 1 - times(from)); + if (to < hi || times(to) < p + 1) insertKnot(p, knots, points, to, p + 1 - times(to)); + const first = knots.indexOf(from); + const last = knots.lastIndexOf(to); + const kept = knots.slice(first, last + 1); + const cp = points.slice(first, last - p); + return { + degree: p, + knots: kept, + points: cp.map((h) => [h[0]! / h[3]!, h[1]! / h[3]!, h[2]! / h[3]!] as Point3), + ...(w === undefined ? {} : { weights: cp.map((h) => h[3]!) }), + }; +} + +const TURN = 2 * Math.PI; + +/** Whether every number an edge holds is finite. */ +function finite(edge: ReadEdge): boolean { + const ok = (q: readonly number[]) => q.every(Number.isFinite); + switch (edge.kind) { + case "line": + return ok(edge.from) && ok(edge.to); + case "ellipse": + return ( + ok(edge.center) && + ok(edge.normal) && + ok(edge.majorAxis) && + ok([edge.ratio, edge.startParameter ?? 0, edge.endParameter ?? 0]) + ); + case "spline": + return ok(edge.knots) && edge.controlPoints.every(ok) && ok(edge.weights ?? []); + } +} + +/** An edge with each -0 as 0, which the text form writes as `-0` and the binary form as 0. */ +function signless(edge: ReadEdge): ReadEdge { + const n = (v: number): number => v + 0; + const p = (q: Point3): Point3 => [q[0] + 0, q[1] + 0, q[2] + 0]; + switch (edge.kind) { + case "line": + return { ...edge, from: p(edge.from), to: p(edge.to) }; + case "ellipse": + return { + ...edge, + center: p(edge.center), + normal: p(edge.normal), + majorAxis: p(edge.majorAxis), + }; + case "spline": + return { + ...edge, + knots: edge.knots.map(n), + controlPoints: edge.controlPoints.map(p), + ...(edge.weights && { weights: edge.weights.map(n) }), + }; + } +} +const degrees = (radians: number): number => (radians * 180) / Math.PI; + +/** + * The edges of the modeler data in its text form: lines, ellipses and splines in the world, and a + * count of the edges it holds on a curve the reader does not follow. A text of an older version, or + * one that does not read as records, gives no edges and `unread` -1. + */ +export function satEdges(text: string): ModelerEdges { + return edgesOf(satRecords(text)); +} + +/** The edges of the modeler data in its binary form, as `satEdges` reads the text form. */ +export function sabEdges(bytes: Uint8Array): ModelerEdges { + return edgesOf(sabRecords(bytes)); +} + +function edgesOf(read: { version: number; list: SatRecord[] } | undefined): ModelerEdges { + if (read === undefined) return { edges: [], unread: -1 }; + const { list } = read; + const place = placementOf(list); + if (place === null) + return { edges: [], unread: list.filter((r) => isKind(r.name, "edge")).length }; + const shared = subtypes(list); + // Each curve's B-spline is read once, however many edges lie on it. + const splines = new Map(); + const subtypeSplines = new Map(); + // Cutting a B-spline to an edge takes time in its points: past a budget in the data's size, + // the edges left are not followed. + let tokens = 0; + for (const r of list) tokens += 1 + r.fields.length + (r.braces?.length ?? 0); + const work = { left: 1_000_000 + 16 * tokens }; + const edges: ReadEdge[] = []; + let unread = 0; + for (const r of list) { + if (!isKind(r.name, "edge")) continue; + const edge = + work.left > 0 ? edgeOf(list, r, place, shared, splines, subtypeSplines, work) : undefined; + // An edge with a number past the doubles, such as from a scale past them, is not followed. + if (edge === undefined || (edge !== null && !finite(edge))) unread++; + else if (edge !== null) edges.push(signless(edge)); + } + return { edges, unread }; +} + +/** One edge record in the world, null for one of no length, or undefined for one not read. */ +function edgeOf( + list: readonly SatRecord[], + r: SatRecord, + place: Placement | undefined, + shared: readonly Subtype[], + splines: Map, + read: Map, + work: { left: number }, +): ReadEdge | null | undefined { + // The fields after the name: attributes, history, a pointer, the start vertex and parameter, + // the end vertex and parameter, a coedge, the curve and the sense. + const f = r.fields; + const start = vertexPoint(list, pointer(f[3])); + const end = vertexPoint(list, pointer(f[5])); + const [t0, t1] = [Number(f[4]), Number(f[6])]; + // An edge on no curve is a point, such as a cone's apex; a seam does not show. + if (pointer(f[8]) < 0 || seam(list, r)) return null; + const curve = list[pointer(f[8])]; + const reversed = set(f[9]); + if (start === undefined || end === undefined || curve === undefined) return undefined; + if (!Number.isFinite(t0) || !Number.isFinite(t1)) return undefined; + // The edge's parameters run along the curve, or against it for a reversed edge. + const [u0, u1] = reversed ? [-t1, -t0] : [t0, t1]; + switch (curve.name) { + case "straight-curve": { + const [from, to] = [placePoint(start, place), placePoint(end, place)]; + return { kind: "line", from, to }; + } + case "ellipse-curve": { + const v = numbers(curve.fields, 3, 10); + if (v === undefined) return undefined; + const center: Point3 = [v[0]!, v[1]!, v[2]!]; + const normal = unit([v[3]!, v[4]!, v[5]!]); + const major: Point3 = [v[6]!, v[7]!, v[8]!]; + const ratio = v[9]!; + if (normal === undefined || !(length(major) > 0) || !(ratio > 0 && ratio <= 1)) + return undefined; + const minor = cross(normal, major); + const placedMajor = placeVector(major, place); + const placedNormal = unit(cross(placedMajor, placeVector(minor, place))); + if (placedNormal === undefined) return undefined; + const span = u1 - u0; + const base = { + kind: "ellipse" as const, + center: placePoint(center, place), + normal: placedNormal, + majorAxis: placedMajor, + ratio, + }; + if (!(span > 0)) return undefined; + if (span >= TURN - 1e-12) return base; + const from = ((u0 % TURN) + TURN) % TURN; + return { ...base, startParameter: degrees(from), endParameter: degrees(from + span) }; + } + case "intcurve-curve": { + let s = splines.get(curve); + if (!splines.has(curve)) { + const data = ownSubtype(curve); + s = data === undefined ? undefined : curveSpline(data, shared, read, work); + splines.set(curve, s); + } + if (s === undefined) return undefined; + work.left -= s.knots.length * (s.degree + 2); + // A reversed curve runs its B-spline backward: its parameter t is the B-spline's -t. + const [v0, v1] = set(curve.fields[3]) ? [-u1, -u0] : [u0, u1]; + const piece = cut(s, v0, v1); + if (piece === undefined) return null; + return { + kind: "spline", + degree: piece.degree, + knots: piece.knots, + controlPoints: piece.points.map((q) => placePoint(q, place)), + ...(piece.weights === undefined ? {} : { weights: piece.weights }), + }; + } + default: + return undefined; + } +} + +/** + * The text of modeler data as a file before 2013 holds it: each character from `!` to `~` is + * 159 less itself, and a tab is a space. + */ +export function decipherSat(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i++) { + const c = text.charCodeAt(i); + out += c > 32 && c < 127 ? String.fromCharCode(159 - c) : c === 9 ? " " : text[i]; + } + return out; +} diff --git a/src/read/plan.ts b/src/read/plan.ts new file mode 100644 index 0000000..c3134c2 --- /dev/null +++ b/src/read/plan.ts @@ -0,0 +1,202 @@ +// `edgesInPlan`: the edges of a read solid, region or body as seen from above, as the lines, +// circles, arcs, ellipses and splines a `Drawing` holds, so that `toSVG` and `toPDF` draw them. +import type { + Arc, + Circle, + ControlSpline, + Ellipse, + EntityColor, + EntityTransparency, + Line, + Point, +} from "../drawing.ts"; +import { written } from "../format.ts"; +import { SPLINE_DEGREE_MOST } from "../rules.ts"; +import type { Point3, ReadEdge, ReadEdgeEllipse, ReadModelerGeometry } from "./model.ts"; + +/** What `edgesInPlan` gives for an edge. */ +export type PlanEdge = Line | Circle | Arc | Ellipse | ControlSpline; + +/** A ratio this near 1 draws a circle. */ +const ROUND = 1e-9; +/** A projected axis this much shorter than the other draws as a line. */ +const EDGE_ON = 1e-9; + +const TURN = 2 * Math.PI; +const toDegrees = (r: number): number => { + const d = (r * 180) / Math.PI; + const turned = ((d % 360) + 360) % 360; + return turned >= 360 ? 0 : turned; +}; + +/** The pen the solid sets for itself, as a drawing's entity holds it. */ +function penOf(s: ReadModelerGeometry): { + layer: string; + color?: EntityColor; + transparency?: EntityTransparency; + linetype?: string; + lineweight?: number | "ByBlock" | "Default"; +} { + const color: EntityColor | undefined = + s.trueColor !== undefined + ? [(s.trueColor >> 16) & 255, (s.trueColor >> 8) & 255, s.trueColor & 255] + : s.color === 0 + ? "ByBlock" + : s.color; + const transparency: EntityTransparency | undefined = + s.alpha === undefined + ? undefined + : s.alpha === "ByBlock" + ? "ByBlock" + : Math.round(100 - s.alpha / 2.55); + const lineweight = + s.lineweight === undefined || s.lineweight === -1 + ? undefined + : s.lineweight === -2 + ? ("ByBlock" as const) + : s.lineweight === -3 + ? ("Default" as const) + : s.lineweight / 100; + return { + layer: s.layer, + ...(color !== undefined && { color }), + ...(transparency !== undefined && { transparency }), + ...(s.linetype !== undefined && { linetype: s.linetype }), + ...(lineweight !== undefined && { lineweight }), + }; +} + +const flat = (p: Point3): Point => [p[0], p[1]]; +const samePoint = (a: Point, b: Point): boolean => + written(a[0]) === written(b[0]) && written(a[1]) === written(b[1]); + +/** + * The edges of a solid, a region or a body as seen from above, in the order it holds them, each + * with the solid's layer and its own pen. A line edge stays a line, and a spline edge a spline by + * its control points; an edge on an ellipse or a circle becomes the circle, arc or ellipse it + * shows from above, and a line where it is seen edge on. An edge that shows as one point, such as + * a vertical line, is left out. + */ +export function edgesInPlan(solid: ReadModelerGeometry): PlanEdge[] { + const pen = penOf(solid); + const out: PlanEdge[] = []; + for (const edge of solid.edges) { + const drawn = edgeInPlan(edge); + if (drawn !== undefined) out.push({ ...pen, ...drawn } as PlanEdge); + } + return out; +} + +type Shape = + | Omit + | Omit + | Omit + | Omit + | Omit; + +function edgeInPlan(edge: ReadEdge): Shape | undefined { + switch (edge.kind) { + case "line": { + const [from, to] = [flat(edge.from), flat(edge.to)]; + return samePoint(from, to) ? undefined : { kind: "line", from, to }; + } + case "ellipse": + return ellipseInPlan(edge); + case "spline": { + if (edge.degree > SPLINE_DEGREE_MOST) return undefined; + const controlPoints = edge.controlPoints.map(flat); + if (controlPoints.every((p) => samePoint(p, controlPoints[0]!))) return undefined; + return { + kind: "spline", + degree: edge.degree, + knots: edge.knots, + controlPoints, + ...(edge.weights !== undefined && { weights: edge.weights }), + }; + } + } +} + +/** + * An ellipse edge seen from above. Its points are `c + a cos t + b sin t`, where `a` and `b` are + * its two axes seen from above: two conjugate half diameters of the ellipse it shows, which turn by + * the phase `phi` into its own axes, at right angles. + */ +function ellipseInPlan(e: ReadEdgeEllipse): Shape | undefined { + const n = e.normal; + const A = e.majorAxis; + const minor: Point3 = [ + e.ratio * (n[1] * A[2] - n[2] * A[1]), + e.ratio * (n[2] * A[0] - n[0] * A[2]), + e.ratio * (n[0] * A[1] - n[1] * A[0]), + ]; + const c = flat(e.center); + const a = flat(A); + const b = flat(minor); + const whole = e.startParameter === undefined || e.endParameter === undefined; + const t0 = whole ? 0 : (e.startParameter! * Math.PI) / 180; + const t1 = whole ? TURN : (e.endParameter! * Math.PI) / 180; + // The phase that makes the axes square: tan 2φ = 2 a·b / (|a|² - |b|²). + const ab = a[0] * b[0] + a[1] * b[1]; + const phi = 0.5 * Math.atan2(2 * ab, a[0] ** 2 + a[1] ** 2 - b[0] ** 2 - b[1] ** 2); + const [cos, sin] = [Math.cos(phi), Math.sin(phi)]; + // p = c + u cos(t - φ) + v sin(t - φ). + let u: Point = [a[0] * cos + b[0] * sin, a[1] * cos + b[1] * sin]; + let v: Point = [-a[0] * sin + b[0] * cos, -a[1] * sin + b[1] * cos]; + let shift = phi; + if (Math.hypot(...v) > Math.hypot(...u)) { + // The longer axis is v: with s = t - φ - 90°, p = c + v cos s - u sin s. + [u, v] = [v, [-u[0], -u[1]]]; + shift += Math.PI / 2; + } + const major = Math.hypot(...u); + const minorLength = Math.hypot(...v); + if (!(major > 0)) return undefined; + let [s0, s1] = [t0 - shift, t1 - shift]; + // Seen from above it runs clockwise when v is a quarter turn clockwise of u: run it backward. + if (u[0] * v[1] - u[1] * v[0] < 0) { + v = [-v[0], -v[1]]; + [s0, s1] = [-s1, -s0]; + } + const ratio = minorLength / major; + const at = (s: number): Point => [ + c[0] + u[0] * Math.cos(s) + v[0] * Math.sin(s), + c[1] + u[1] * Math.cos(s) + v[1] * Math.sin(s), + ]; + // A ratio the writers would write as 0 draws a line, as one seen exactly edge on does. + if (ratio < EDGE_ON || written(ratio) === 0) { + // Seen edge on: the line over the furthest the parameters reach along the axis. + let [lo, hi] = [Math.min(Math.cos(s0), Math.cos(s1)), Math.max(Math.cos(s0), Math.cos(s1))]; + // It reaches the axis's tip where it passes a whole turn, and its other end where it passes + // a half turn past one. + const passes = (offset: number): boolean => + Math.floor((s1 - offset) / TURN) >= Math.ceil((s0 - offset) / TURN); + if (whole || s1 - s0 >= TURN) [lo, hi] = [-1, 1]; + else { + if (passes(0)) hi = 1; + if (passes(Math.PI)) lo = -1; + } + let from: Point = [c[0] + u[0] * lo, c[1] + u[1] * lo]; + let to: Point = [c[0] + u[0] * hi, c[1] + u[1] * hi]; + // A short arc at the tip moves across the axis more than along it: its own two ends. + if (samePoint(from, to)) [from, to] = [at(s0), at(s1)]; + return samePoint(from, to) ? undefined : { kind: "line", from, to }; + } + if (1 - ratio < ROUND) { + const radius = (major + minorLength) / 2; + if (whole) return { kind: "circle", center: c, radius }; + const angle = Math.atan2(u[1], u[0]); + const [start, end] = [at(s0), at(s1)]; + if (samePoint(start, end) && s1 - s0 < 1) return undefined; + return { + kind: "arc", + center: c, + radius, + startAngle: toDegrees(angle + s0), + endAngle: toDegrees(angle + s1), + }; + } + const base = { kind: "ellipse" as const, center: c, majorAxis: u, ratio }; + if (whole) return base; + return { ...base, startParameter: toDegrees(s0), endParameter: toDegrees(s1) }; +} diff --git a/test/modeler.test.ts b/test/modeler.test.ts new file mode 100644 index 0000000..4094851 --- /dev/null +++ b/test/modeler.test.ts @@ -0,0 +1,208 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + decipherSat, + edgesInPlan, + sabEdges, + satEdges, + type ReadEdge, + type ReadModelerGeometry, +} from "../src/index.ts"; +import { random } from "./read-fuzz.ts"; + +/** A small body in the text form: a line, a whole circle and a B-spline, moved 10 along X. */ +const RECORDS = [ + "asmheader $-1 -1 @5 1.0.0 #", + "body $-1 -1 $-1 $-1 $-1 $2 #", + "transform $-1 -1 1 0 0 0 1 0 0 0 1 10 0 0 1 no_rotate no_reflect no_shear #", + "point $-1 -1 $-1 0 0 0 #", + "point $-1 -1 $-1 2 0 0 #", + "vertex $-1 -1 $-1 $-1 0 $3 #", + "vertex $-1 -1 $-1 $-1 0 $4 #", + "straight-curve $-1 -1 $-1 0 0 0 1 0 0 I I #", + "edge $-1 -1 $-1 $5 0 $6 2 $-1 $7 forward @7 unknown #", + "ellipse-curve $-1 -1 $-1 0 0 0 0 0 1 2 0 0 1 I I #", + "edge $-1 -1 $-1 $6 0 $6 6.283185307179586 $-1 $9 forward @7 unknown #", + "intcurve-curve $-1 -1 $-1 forward { exact_int_cur 22800 full nubs 1 open 2 0 1 1 1 0 0 0 0 1 0 } I I #", + "edge $-1 -1 $-1 $5 0 $5 1 $-1 $11 forward @7 unknown #", +]; +const SAT = `21500 ${RECORDS.length} 1 0\n4 test 0 \n1 1e-06 1e-10\n${RECORDS.join("\n")}\nEnd-of-ACIS-data\n`; + +/** The same records in the binary form, each token after the byte that says its kind. */ +function sab(): Uint8Array { + const out: number[] = [...new TextEncoder().encode("ACIS BinaryFile")]; + const int = (v: number) => { + const b = new DataView(new ArrayBuffer(4)); + b.setInt32(0, v, true); + out.push(...new Uint8Array(b.buffer)); + }; + const double = (v: number) => { + const b = new DataView(new ArrayBuffer(8)); + b.setFloat64(0, v, true); + out.push(...new Uint8Array(b.buffer)); + }; + const word = (tag: number, w: string) => out.push(tag, w.length, ...new TextEncoder().encode(w)); + [21500, 0, 1, 0].forEach(int); + for (const record of RECORDS) { + const tokens = record.split(" "); + const [name, ...rest] = tokens; + const parts = name!.split("-"); + for (const part of parts.slice(0, -1)) word(0x0e, part); + word(0x0d, parts.at(-1)!); + for (let i = 0; i < rest.length; i++) { + const t = rest[i]!; + if (t === "#") out.push(0x11); + else if (t === "{") out.push(0x0f); + else if (t === "}") out.push(0x10); + else if (t.startsWith("$")) (out.push(0x0c), int(Number(t.slice(1)))); + else if (t.startsWith("@")) word(0x07, rest[++i]!); + else if (t === "forward" || t.startsWith("no_") || t === "I") out.push(0x0b); + else if (/^-?\d+$/.test(t) && !/^(0|1|2)$/.test(t)) (out.push(0x04), int(Number(t))); + else if (Number.isFinite(Number(t))) (out.push(0x06), double(Number(t))); + else word(0x0d, t); + } + } + word(0x0e, "End"); + word(0x0e, "of"); + word(0x0e, "ACIS"); + word(0x0d, "data"); + return Uint8Array.from(out); +} + +test("modeler data reads as the body's edges in the world, from either form", () => { + const { edges, unread } = satEdges(SAT); + assert.equal(unread, 0); + assert.deepEqual(edges, [ + { kind: "line", from: [10, 0, 0], to: [12, 0, 0] }, + { kind: "ellipse", center: [10, 0, 0], normal: [0, 0, 1], majorAxis: [2, 0, 0], ratio: 1 }, + { + kind: "spline", + degree: 1, + knots: [0, 0, 1, 1], + controlPoints: [ + [10, 0, 0], + [10, 1, 0], + ], + }, + ]); + assert.deepEqual(sabEdges(sab()), { edges, unread }); +}); + +test("a file's cipher of the text form is its own inverse", () => { + const plain = "edge $-1 -1 $5 0.5 forward #\n"; + assert.notEqual(decipherSat(plain), plain); + assert.equal(decipherSat(decipherSat(plain)), plain); +}); + +test("hostile modeler data reads as edges or as data not read, in bounded time", () => { + const next = random(13); + const bytes = sab(); + for (let run = 0; run < 2000; run++) { + const text = [...SAT]; + const b = Uint8Array.from(bytes); + for (let k = 0; k < 1 + Math.floor(next() * 6); k++) { + const at = Math.floor(next() * text.length); + text[at] = String.fromCharCode(32 + Math.floor(next() * 95)); + b[Math.floor(next() * b.length)] = Math.floor(next() * 256); + } + for (const read of [satEdges(text.join("")), sabEdges(b)]) { + assert.ok(read.unread >= -1); + for (const e of read.edges) assert.ok(["line", "ellipse", "spline"].includes(e.kind)); + } + } + // Braces nested deep, and many edges on one long curve, read in time in proportion to the data. + const deep = SAT.replace( + "exact_int_cur", + `${"{ ".repeat(100_000)}${"} ".repeat(100_000)}exact_int_cur`, + ); + const long = `nubs 3 open 2000 ${Array.from({ length: 2000 }, (_, i) => `${i} ${i === 0 || i === 1999 ? 3 : 1}`).join(" ")} ${"1 2 3 ".repeat(2002)}`; + const many = SAT.replace("nubs 1 open 2 0 1 1 1 0 0 0 0 1 0", long).replace( + "End-of-ACIS-data", + `${"edge $-1 -1 $-1 $5 10 $5 1500 $-1 $11 forward @7 unknown #\n".repeat(20_000)}End-of-ACIS-data`, + ); + const started = performance.now(); + satEdges(deep); + assert.ok(satEdges(many).unread > 0); + assert.ok(performance.now() - started < 5000); + // Many long distinct splines all read: the budget is in the data's size. + const k = 1000; + const spaced = Array.from({ length: k }, (_, i) => `${i} ${i === 0 || i === k - 1 ? 3 : 1}`); + let profile = SAT.replace("End-of-ACIS-data\n", ""); + for (let c = 0; c < 120; c++) { + profile += `intcurve-curve $-1 -1 $-1 forward { exact_int_cur 22800 full nubs 3 open ${k} ${spaced.join(" ")} ${"1 2 3 ".repeat(k + 2)}0 } I I #\n`; + profile += `edge $-1 -1 $-1 $5 1.5 $5 997.5 $-1 $${RECORDS.length + 2 * c} forward @7 unknown #\n`; + } + assert.equal(satEdges(`${profile}End-of-ACIS-data\n`).unread, 0); + // A B-spline that says it holds far more knots than the data does. + const huge = SAT.replace("nubs 1 open 2", "nubs 1 open 999999999"); + assert.equal(satEdges(huge).unread, 1); +}); + +const solid = (edges: ReadEdge[]): ReadModelerGeometry => ({ + kind: "3dsolid", + layer: "SOLID", + color: 3, + edges, +}); + +test("edgesInPlan draws each edge as it shows from above", () => { + const tilt = Math.PI / 3; + const drawn = edgesInPlan( + solid([ + { kind: "line", from: [0, 0, 0], to: [0, 0, 5] }, + { kind: "line", from: [0, 0, 0], to: [3, 4, 5] }, + // A circle of radius 2 turned 60 degrees about X: an ellipse half as tall. + { + kind: "ellipse", + center: [0, 0, 1], + normal: [0, -Math.sin(tilt), Math.cos(tilt)], + majorAxis: [2, 0, 0], + ratio: 1, + }, + // A circle seen edge on: a line across it. + { kind: "ellipse", center: [5, 0, 0], normal: [0, 1, 0], majorAxis: [2, 0, 0], ratio: 1 }, + ]), + ); + assert.equal(drawn.length, 3); + assert.deepEqual(drawn[0], { layer: "SOLID", color: 3, kind: "line", from: [0, 0], to: [3, 4] }); + const ellipse = drawn[1]!; + assert.equal(ellipse.kind, "ellipse"); + if (ellipse.kind === "ellipse") { + assert.ok(Math.abs(Math.hypot(...ellipse.majorAxis) - 2) < 1e-12); + assert.ok(Math.abs(ellipse.ratio - 0.5) < 1e-12); + } + // Nearly edge on, at a ratio the writers would write as 0: a line too. + const nearly = edgesInPlan( + solid([ + { + kind: "ellipse", + center: [0, 0, 0], + normal: [0, Math.sqrt(1 - 1e-14), 1e-7], + majorAxis: [1000, 0, 0], + ratio: 1, + }, + ]), + ); + assert.equal(nearly[0]?.kind, "line"); + // A short arc at the tip of such a circle: a line across the axis, between its own ends. + const d = (4e-7 * 180) / Math.PI; + const tip = edgesInPlan( + solid([ + { + kind: "ellipse", + center: [0, 0, 0], + normal: [0, Math.sqrt(1 - 1.6e-13), 4e-7], + majorAxis: [4e6, 0, 0], + ratio: 1, + startParameter: 360 - d, + endParameter: 360 + d, + }, + ]), + ); + assert.equal(tip[0]?.kind, "line"); + const line = drawn[2]!; + assert.equal(line.kind, "line"); + if (line.kind === "line") { + assert.ok(Math.abs(Math.abs(line.to[0] - line.from[0]) - 4) < 1e-12); + } +}); From 30523f9b30d5e1b696015f64ed7edddc483881af Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sun, 22 Nov 2026 01:32:05 -0500 Subject: [PATCH 33/35] Agent notes: the rules of each part of the library in a page of its own `AGENTS.md` keeps the rules that hold for every change, with a table of the page to read before changing each part of the library. The rules of one part, such as handles and blocks, the standard or the bounded walks, moved to pages under `docs/agents/`. No rule changed in meaning. Co-authored-by: Claude Fable 5.2 Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 445 ++---------------------------------- docs/agents/bounded.md | 80 +++++++ docs/agents/checks.md | 35 +++ docs/agents/handles.md | 72 ++++++ docs/agents/images-fills.md | 40 ++++ docs/agents/pdf.md | 25 ++ docs/agents/pictures.md | 77 +++++++ docs/agents/reading.md | 22 ++ docs/agents/sheets.md | 54 +++++ docs/agents/standard.md | 52 +++++ docs/development.md | 3 +- 11 files changed, 482 insertions(+), 423 deletions(-) create mode 100644 docs/agents/bounded.md create mode 100644 docs/agents/checks.md create mode 100644 docs/agents/handles.md create mode 100644 docs/agents/images-fills.md create mode 100644 docs/agents/pdf.md create mode 100644 docs/agents/pictures.md create mode 100644 docs/agents/reading.md create mode 100644 docs/agents/sheets.md create mode 100644 docs/agents/standard.md diff --git a/AGENTS.md b/AGENTS.md index ba4e6c6..ade0d63 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,22 @@ # Agent notes +These rules hold for every change. The rules of one part of the library are in a page of its +own, and each is as binding as these: before you change a part, read its page. A change to +`lint`, to `toSVG` or to a writer often touches several. + +| Part | Its files, among them | Page | +| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Handles from ids and names, blocks, inserts, attributes and xrefs | `src/handles.ts`, `src/blocks.ts` | [handles.md](docs/agents/handles.md) | +| The DXF writers: what each kind of thing writes, and which handles must never change | `src/dxf.ts`, `src/dxf-r2018.ts`, `src/dxf-r12.ts` | [handles.md](docs/agents/handles.md), then the page of each kind written | +| Layouts, viewports, papers, dimensions, leaders and arrowheads | `src/layouts.ts`, `src/papers.ts`, `src/dimensions.ts`, `src/leaders.ts`, `src/arrowheads.ts` | [sheets.md](docs/agents/sheets.md) | +| What `toSVG` draws: a view's clip and cull, the measure of a text, paragraphs, fonts, dashes, marks and shapes | `src/svg.ts`, `src/extents.ts`, `src/measure.ts`, `src/paragraphs.ts`, `src/fonts.ts`, `src/linetypes.ts`, `src/shapes.ts` | [pictures.md](docs/agents/pictures.md); for a sheet's picture also [pdf.md](docs/agents/pdf.md) | +| The text warnings and the checks of intent | `src/inspect.ts`, `src/intent.ts` | [checks.md](docs/agents/checks.md) | +| A standard, and what the builder and `lint` do under one | `src/standard/` | [standard.md](docs/agents/standard.md); for `styleNameAt` also [sheets.md](docs/agents/sheets.md) | +| Any walk of a drawing, which must stay bounded, and data of the wrong shape | `src/lint.ts`, `src/shape.ts`, `src/inspect.ts`, `src/extents.ts`, `src/svg.ts` | [bounded.md](docs/agents/bounded.md) | +| The readers | `src/read/` | [reading.md](docs/agents/reading.md); images and fills also [images-fills.md](docs/agents/images-fills.md), paragraphs also [pictures.md](docs/agents/pictures.md) | +| Images, PDF underlays, hatches, gradients, wipeouts and masks | `src/images.ts`, `src/raster.ts`, `src/underlays.ts`, `src/fills.ts` | [images-fills.md](docs/agents/images-fills.md) | +| The plot to PDF and the TrueType reader | `src/pdf.ts`, `src/truetype.ts` | [pdf.md](docs/agents/pdf.md); fills and masks in a plot also [images-fills.md](docs/agents/images-fills.md) | + - Run `pnpm verify` before finishing a change. It checks formatting, lints, type checks, runs the tests and runs the package smoke test, which builds. Run `pnpm fmt` to fix formatting. @@ -19,422 +36,18 @@ - AC1032 needs every handle unique, every owner (330) and pointer (340, 350, 390) to resolve, and `$HANDSEED` above the highest handle. The leading CAD app also discards the whole file if a LAYER has no 390 plot style pointer. The tests check all of this. -- An entity with an id takes the handle `idHandle` in `src/handles.ts` gives the id, from - 2^52 up to 2^53, and a drawing that has ids has a `$HANDSEED` of 2^53. Every other object - is counted up from 1. Another drawing that dimensions the entity through an xref holds that - handle, so never change what `idHandle` returns for an id, nor `idKey`, which it hashes: - every such dimension would come loose, and the leading CAD app would report nothing. -- The range from 2^52 to 2^53 is for every handle that comes from a name, not only an - entity's id. Another kind of object, such as a block, hashes its key with a prefix that no - id can contain, such as `block:NAME`, since an id cannot hold `:` or `/`. It hashes into - the same range, and two keys that give one handle are refused as two ids are. A key that can - hold characters outside ASCII, as a block's name can, is hashed as its UTF-8 bytes. A - counted handle cannot reach 2^52, because a drawing cannot hold that many objects. Nothing - uses the handles from 2^32 up to 2^52. Keep them for a later scheme. -- `src/blocks.ts` holds the keys of the handles blocks need: a block's record and the two - objects of its definition from its name, an attribute definition from its block and tag, and - the attributes of an insert that has an id from the id and each tag. Never change a key, or - `keyHandle`, which hashes it. A key holds a name with A to Z in lower case and a tag as - written. Neither `layerKey` nor any table that can grow may be part of a key, because a - change to the table would move every handle it touches. An insert without an id and its - attributes are counted. -- The leading CAD app takes two block names for one wherever its `AUDIT` would call two layer names - duplicates, and merges the two blocks without a word. So a second block is refused by - `layerAuditKey`, and an insert finds its block by `layerKey`. -- An entity on layer `0` of a block draws as its insert's layer does. `eachDrawn` in - `src/blocks.ts` walks what an insert draws, with the layer and the matrix of each entity, - for `toSVG` and `inspectText`. It keeps its own stack, so a chain of any depth is walked, - does not enter an insert on a frozen layer, reads each list up to its first empty slot, and - asks `spend` before each block it enters and each item it reads. The extents never walk an - entity of a block: `boxer` in `src/extents.ts` keeps the box of each block's own entities, in - the block's coordinates, worked out once for each drawing it is in and whether its layer `0` - is hidden. A placement walks the blocks it inserts, with their matrices composed as - `eachDrawn` composes them, and maps the corners of each block's own box: each side takes the - corner that rounds no nearer than any point inside, so the box holds the walk's to the last - bit, is the walk's where no insert is turned, and for a turned insert may be larger. Each walk - enters its first 64 blocks free and all walks the boxer's `walking` more, which `lint` gives - the writer's whole limit, so the two take one path, and `lint` boxes model space when it holds - anything whose box can cost: an insert, a dimension, a leader or a text past `KEYED`. Past that, a placement - maps the corners of the box of all its block draws, widened by what rounding can move a number - on the way, so the extents never come out smaller than a walk's. Where a number on the way - overflowed or a product underflowed, which the slack cannot cover, it walks the blocks within - the walks left, and past them the boxer stops. A box that - depends on a block of a cycle being open is not kept for another way in. What many places share is read once a boxer: the box of a list of entities, - of a long list of points and of a leader, a long value's measure, and the inserts of a list. - An insert's attributes are written as texts in the insert's - own coordinates, which `placeAttribute` works out from the numbers as they are written. One of - paragraph text is the paragraph `attributeParagraph` gives in those coordinates, mirrored where - X runs the other way, which `eachDrawn` draws with the matrix of the space the insert is in, and - the boxer keeps apart from a block's other attributes, in the coordinates of its insert's - space, since an uneven scale lays it out again rather than stretching it. An - attribute is stored on its definition's layer, and one on layer `0` draws as its insert's - layer does. An insert on a frozen layer, or in a plot on a layer that does not plot, draws - nothing of its block. -- An xref is a block record with a path: `Drawing.xrefs` holds a name and a path, and an - insert places one by its name. It shares the blocks' names and the keys of their handles, - `block:KEY` and the two beside it, and is written as an overlay, unless `attach` is true. That - app reads the path of a BLOCK once, so the DXF writes it with `dxfOnce`. `eachDrawn` walks the - drawing a caller gives for an xref as it walks a block, with each layer as a `LayerRef` that - says which drawing's layer it is. `src/` opens no file: `toSVG` draws only the drawings it is - given. `referencedTree` in `src/blocks.ts` is the one reading of what is given in `xrefs`: a - tree of `Referenced`, one for each place, each with the drawings of its own attachments, - never of an overlay, cut where a drawing on the chain above comes again and past `XREF_DEPTH` - drawings down, with why in its problems, which `lint` reports with `xrefs`. Past `XREF_LOOKS` - names looked for inside referenced drawings it follows none, so the same given with drawings - left out cuts nothing the whole did not, which the command relies on; `drawnXrefs` gives the - tree in the form given. `eachDrawn` and the boxer read that tree, the boxer keeping a block's - box for each drawing and the drawings given for its attachments. `inspectText` reads the - drawings given for the drawing's own xrefs alone, once each, and checks no text of their - attachments: a cut for each place cost work outside its limit. -- A layout is a sheet: `Drawing.layouts` holds each with its paper, its viewports and the - entities drawn on it in paper units. `src/papers.ts` is the one list of papers and of plot - style tables, with the name the leading CAD app stores for each paper. Add a paper only when - `DWG To PDF.pc3` has it, and with the name the plotter gives it. `src/layouts.ts` holds the - keys of a layout's handles, `layout:KEY` and the four beside it, from its name with A to Z - in lower case: never change one. That app compares layout names by a table of its own, - `layoutNameKey` in `src/layers.ts`, which is not `layerKey`. The DXF holds the first layout - in `*Paper_Space`, with its entities among model space's and marked with group 67, and - every other in a block `*Paper_Space0` and on. A viewport holds the height of its view and - no scale: `validViewportView` works it out from the numbers as they are written. -- A dimension holds its two points, its style and its text, and both writers add the block of - its picture, `*D` and a number, which the leading CAD app shows and which an xref or an insert of - the file needs: that app draws nothing for a dimension inside another drawing's block. - `src/dimensions.ts` is the one place that says what that app draws, `dimensionPicture`, and - what string it writes, `measurementText`: the writers, `toSVG`, the extents and the command - all read it, from the numbers as they are written. What a dimension reads, group 42, and the - direction of its text are written with 15 significant digits: near enough to the leading CAD app's - own, and few enough that the double that app reads from them can be worked out exactly. Every - number of a picture must stay under 1e100, which `dimensionDrawnProblem` checks for the builder - and `lint` alike. A style's sizes are paper sizes and its `scale` is that app's overall scale. The - text is always above the line and between the extension lines, so the one case that depends on a - font's widths, closed filled arrowheads that may not fit, is refused by `arrowRoom`. The keys of - the handles are `dimension-style:NAME`, with A to Z in lower case, `arrowhead:NAME` for the stroke - in an arrowhead's block, whose own handles are the block's, and `dimension-picture:WHO/PART` for - the block of a picture and what it holds, where WHO is the dimension's id with A to Z in - lower case, or `@LAYOUT/INDEX` for one without an id: never change one. A dimension is - refused inside a block, where that app draws nothing for it. -- A leader holds its note, its point, its shafts and its own sizes, and the R2018 writer writes it - as a multileader with no picture. `src/leaders.ts` is the one place that says what the leading CAD - app draws, `leaderPicture`, which the writers, `toSVG`, the extents and `inspectText` all read. - Its note is a `Paragraph`, laid out by `layoutParagraph` and held where the multileader holds it, - so the note's lines follow every rule of a paragraph's. A mask is drawn first in the leader's - group, so it hides what is drawn before the leader and none of the leader. A block in place of - the note is placed from its own outline, read once for each list of a block's entities and cut - at `OUTLINE_ITEMS`; `toSVG` draws it as an insert after the leader, so the insert walk draws it - and its attributes. A curved shaft is solved as three diagonals, in time in proportion to its - points. A style's - sizes are paper sizes times its `scale`, and the file holds them multiplied out with a scale of 1. - The writers add that app's own `Standard` and the dictionary `ACAD_MLEADERSTYLE` with the first - style. The keys of the handles are `leader-style:NAME`, with A to Z in lower case, - `dictionary:acad_mleaderstyle`, and `arrowhead:NAME` and `arrowhead:NAME/N` for the strokes of - the blocks `_Open`, `_Dot` and `_None`: never change one. A leader is refused inside a block. -- A style in architectural units, `DIMLUNIT` 4, writes feet and inches with the fraction on the - line, `DIMFRAC` 2, and `feetInchZeros` is `DIMZIN` 0 to 3. `feetAndInches` in - `src/dimensions.ts` is the string, and the dimension holds no text of its own, so the leading CAD - app measures it again when its points move. A standard's style is named in that app by - `styleNameAt` in `src/standard/rules.ts`, which the builder, `lint` and `defineStandard` share: - a `layoutName` or a name in `scaleNames` where the standard gives one, and the id's name - otherwise. - `examples/site-plan.ts` is the sheet an agent copies, so it must read as a model: the site in model space at its true size, with the annotation that is read in the plan sized by the view it names, and everything that belongs to the paper inside `d.layout`, in paper units. Its layout is on its standard's sheet format and laid out by its zones, and its border and title block are the standard's, placed by `sheet.titleBlock()`. Never draw a sheet in model space there. -- A view is drawn only where it can be seen. The clip of a view, the hidden rectangle and - the cull all use one rectangle: the viewport, cut to the paper, cut to the picture `toSVG` - is drawing (its `viewBox`), with every number as it will be written. If that rectangle has - no width or no height as written, the view is the empty group with no clip. `toSVG` also - takes it to have none when its two sides are one number in single precision, which is how - a renderer may read them. -- The first element of every clipped group is that rectangle, hidden. Never write a clipped - group without it. resvg, the command's PNG renderer, takes the box of a clipped group's - elements before it clips them, and stops the whole process when that box lies wholly more - than two widths of the picture left or right of it, or two heights above or below. The - hidden rectangle is in the picture and counts in that box, so the box always meets the - picture, whatever else the group holds. A viewport `lint` refuses is drawn as its border - alone. -- Leaving out of a view what cannot show in it must never leave out what shows. The cull - keeps an entity whose box, from `boxer` in `src/extents.ts`, reaches the - rectangle when the box is made larger by the widest lineweight and, for a text or an - insert, by the larger side of the box, since a letter may reach past the box of its text. - A `view` of model space is culled the same way, but its pens are as wide in pixels at any - size, so a pen is taken to reach the picture's larger side, times `strokeWidth` above 1. - The box holds the lean of a text whose style has an oblique angle: the leading CAD app slants a - text after it widens it, so the lean is the height times the tangent of the angle and the - width factor has no part in it. `toSVG` writes `skewX` before `scale` for that reason. - Build `boxer` once for a drawing: it reads every block and text style when it is made, and - keeps each block's box. `toSVG` and the DXF writer each build one for a call. -- `measureText` in `src/measure.ts` is the one measure of a text: its length from the widths - in `src/font-metrics.ts`, where its justification puts it, and the one rule for its - baseline. The extents, `toSVG` and `inspectText` all take a text's box from it, so a - warning's box is the box the picture draws. Never work a text's length or place out - anywhere else. `src/font-metrics.ts` holds, for each font of `FONTS` and each character - from U+0020 to U+007E and U+00A0 to U+00FF, the numbers of a text of height 1. It is data: - never edit a number by hand, and keep its header to what the numbers are. -- `src/paragraphs.ts` is the one layout of a paragraph, `layoutParagraph` and `measureParagraph`: - where each line and each run sits, its strokes and its box, from the font tables' advances and - their paragraph columns, each letter's ink and each bold face. - The extents, `toSVG`, `inspectText`, the writers' boxes and `src/read/mtext.ts` all take a - paragraph from it, and every rule of where a line goes is in the block at its top. Its value is - read only by `parseParagraph` in `src/paragraph-codes.ts`, in one pass with a stack of its own - and at most `PARAGRAPH_NESTING` formats, and `ParagraphValue` in `src/rules.ts` is the same - grammar as a type, which gives up past a fixed number of steps and leaves the rest to the - runtime check. Two rules only the runtime check holds: `%%c` in the style's font, which the type - does not know, and a character above U+FFFF, since TypeScript never splits the surrogate pair - that holds one. A code it does not lay out is refused by `lint`, never drawn as a guess. -- `toSVG` draws a text with no `text-anchor`, and holds it to a length with `textLength` and - `lengthAdjust="spacingAndGlyphs"`, so every renderer draws it as long in whatever typeface it - has. A text or a paragraph's run in a TrueType font is drawn from its first point and held to - its characters' advances, which the leading CAD app's PDF sets at `100 Tz`; one in an SHX - font, which plots as strokes, from where `measureText` starts it and held to the length it - plots. `xml:space="preserve"` keeps its - spaces. `data-height` follows `font-family` directly, and `font-size` comes before both: - the command finds the three together to size a text for the typeface it draws. -- `inspectText` in `src/inspect.ts` warns about text as it plots. It is not `lint`: its rules - and its type are its own, `LintRule` stays closed, and `toDXF` never asks it. It shares - `visibility` in `src/svg.ts` with `toSVG`, so the two leave out the same layers, and walks - inserts with `eachDrawn`. It must stay bounded: boxes are worked out once and found through - a grid, and every box the grid looks at, every point a check reads and each step of the walk - of an insert, a text by its length, and each character a warning quotes, count against one - limit, which ends the checks with `text-check-capped`, saying where, when it is reached. The walk reads blocks and xrefs cut to - what the checks keep, `looked` in `src/inspect.ts`, so linework costs it nothing, and its - steps are free for the first 64 of each insert and for as many more as one walk of every - block and xref takes. -- `checkIntent` in `src/intent.ts` checks a drawing against the intent given beside it: so - far, setbacks. It is not `lint` either, and its rules and type are its own. It finds - entities of model space by id, with `idKey`, and reads no layer's state. It takes any value - as the intent and never throws: a field it does not know, an id that names nothing or a - count that does not match is an `intent-unchecked` warning, never a pass with nothing said. - Unlike `lint`, it measures the points as the drawing holds them, not as written: rounding - the points and then the distance makes a footprint on its setback line warn, and hides a - real shortfall. It measures from the property line's first corner, and compares with one - tolerance, `toleranceOf`, for the arithmetic alone, never wider than the writers' rounding - moves a coordinate. A test of two outlines must hold when no side meets another exactly, - as on a turned lot: `contained` cuts a footprint's side at every corner of the lot within - the tolerance of it, and a corner of the lot inside the footprint puts it off the lot. It - takes only simple outlines, judged with `turn`, which is exact for the doubles held, and - refuses one that crosses or touches itself, such as a lot - with a hole. Each outline is read once and paid for before it is read, the search for its - sides that meet uses `grid` from `src/inspect.ts`, every point looked at counts against one - limit, what goes past it is one warning for each setback, and the warnings stop at a - number of their own. A warning names the part of the intent it is about - by `item`, a path such as `setbacks[0]`, so a later check of intent gets a field of - `Intent` of its own and adds no field to the warning. -- The leading CAD app sizes dashes on the paper in a viewport, so `toSVG` scales a pattern by the - linetype scale over the viewport's scale there. It fits a pattern to each line, side of a - polyline and arc: the stretch holds as many whole patterns as fit, its first and last dash - are each half of the first dash and of what is left over, and a stretch shorter than its - pattern is solid. A circle holds the whole number of patterns nearest its length, stretched - alike to go round it, from a dash at angle 0. `cut` in `dashedPath` is the one place that - does it. A linetype's `marks` are placed by `markSpots`, with each whole pattern of a fitted - stretch, and `letterAt` sets each text in the frame of the side it lands on, the line's - direction in its own coordinates deciding `upright`; on an arc that frame is the straight piece - the leading CAD app cuts the arc into, `arcFrame`, 1/1200 inch from it on the paper, which - `Look.chord` holds. `shapeAt` draws a shape the same way, from the outlines `parseShapes` reads - of its file, found by `shapeFinder`, which `lint` shares. A pattern that ends with a dash runs - it into its first, `Dashes.trail`, and is fitted to its own first dash, `Dashes.lead`. A polyline's `linetypeGeneration` cuts its sides as one course, `courseOf`, - from its second point when it is closed. `toSVG` draws a layout with `elements`, the - walk it draws model space with, under a `Look` that says how wide and what color a pen is. - A rule the leading CAD app enforces lives in `src/rules.ts` twice: as a type, so a wrong literal is a compile error, and as a runtime check with the same message. The builder calls the runtime check, and `lint()` in `src/lint.ts` repeats it for drawings built another way. `toDXF` refuses to write a drawing with lint errors. Test a new rule with `@ts-expect-error` inside `assert.throws`, as `test/rules.test.ts` does, so both halves are proven. -- `src/standard/` is a firm's standard. `shape.ts` is the one table of a document's fields: each - field's type, the rule of its value, its default and whether the hash reads it. - `scripts/standard-files.ts` writes `standard.schema.json` from it, `standard.json` from the - built-in standard and `src/version.ts` from `package.json`, and `test/standard.test.ts` fails - until `pnpm standard:files` has run after a change to any of them. A rule of a document's - literal is a type in `src/standard/literal.ts` with the runtime check's message, as a rule of a - drawing is in `src/rules.ts`. A default, once released, never changes: a change of behavior - comes as a new field or value. The library makes `BUILT_IN_STANDARD` as it loads without the - checks, with `BUILT_IN_HASH` in `src/standard/define.ts`, and a test resolves its document with - them. A change to what it states raises its version, which the CHANGELOG gives, and sets that - hash. -- A rule of a drawing drawn to a standard, which the builder refuses, is a type in - `src/standard/drawn.ts` with the runtime check's message, and its message names the standard - by the id and version its type carries. The builder finds an entry of the standard in any case, - as the leading CAD app does, and the type compares the exact spelling. `drawing.ts` reads a - standard through `src/standard/made.ts` and never imports `define.ts`, which draws the plain title - block with the builder as it loads. A drawing without a standard is built as it was before - standards. -- Under a standard, a top-level conditional on the standard's type parameter `Z` whose branches - mention `Z`, such as `Z extends Standard ? A : B` as a parameter's type, makes - `DrawingBuilder<…, undefined>` not assignable to `DrawingBuilder<…, Standard | undefined>`, - which a helper typed with `ReturnType` needs. A conditional inside a - field's type, a conditional whose branches do not mention `Z`, and a conditional that is one - member of a union are fine. In a rest tuple, an element whose type is that conditional alone - makes `DrawingBuilder<…, S>` for a standard `S` not assignable to `DrawingBuilder<…, Standard>`, - and so do overloads; `layout()` keeps it one member of a union with `| undefined`. -- Under a standard, a title block's block, the blocks it inserts and their text styles enter the - drawing under their own names when `sheet.titleBlock()` first places it, and one the drawing - has with another definition is refused: never rename one, since its handles come from its - name. The builder fills a title block's scale when the layout's `draw` returns. -- Under a standard, a role's text style and a dimension or leader style of the standard enter - the drawing on first use, under `capitals` of the id, and in model space with the view's scale - id after a dimension or leader style's: `DIMS-1in-10ft`. A view's id is taken when `view()` declares it, and the - one viewport that shows the view takes that id and no other. -- `lint(drawing, { standard })` runs the rules of a standard in `src/standard/lint.ts` after the - others, and without `standard` runs none of them. It takes the standard through `adopted` in - `src/standard/made.ts`, as the builder does, and reads only what `TYPED` in `src/shape.ts` finds - sound. A rule the builder refuses under a standard has the builder's rule name in `lint`, and - its message from `src/standard/drawn.ts` where that fits a `Drawing`. It must stay bounded by - construction: it reads a list up to its first empty slot, reads each item of the drawing once, - and pays for anything it does again, in proportion to its size, before it does it. The walk of - an insert reads blocks made once a drawing, with only what can draw a text and a short token for - each name, and pays for each block it enters. A title block's definition is compared as JSON - cut short at the length of the standard's. `test/standard-lint.test.ts` fuzzes it from a seed. - To time `lint` against a standard given as data, time the standard's own check, `adopted`, - apart from the index and the rules: it checks the whole document and works out its hash again - on each call, so it can hide what the rest costs. -- `lint`, `inspectText`, the extents and `toSVG` must stay bounded on any data, by construction: - each reads a list up to its first empty slot, works out each name's `layerKey` once a call, - follows blocks with a stack of its own, and pays for what it does again, by its size, before - it does it. The data is the value as given, and a drawing made in code may share one list, - object or string among many places, which JSON cannot. So what a walk reads of one of those - and can keep, it keeps for the call, by the object or, for a value of 256 characters or more, - by the string: the extents' boxes, a text's measure through `measurer` in `src/measure.ts`, - `inspectText`'s cut of a list and the outline of a long list of points, and `lint`'s checks of - a long value and an insert's values. What a walk must read again for each place, `lint` pays - for by its size each time after the first: a list of entities or of attribute definitions, a - list of points of 64 or more, an insert's values past the first 64, and a string of 256 - characters or more in a field an entity, a definition or an insert's values has, since a - message quotes it and `toDXF` writes it again. An object of the wrong shape is reported where - it is first met, and its messages pay for their length, so a long key or kind that many objects - share is paid for each time it is quoted. Once `lint` or `inspectText` stops, it reads no entity - past there. `itemsOf` counts a list once. The boxer pays for a list that - another drawing holds too, such as one drawing given for many xrefs, and the standard's checks - pay for a shared list, each error they give from it by its length, and a shared long string. A - walk skips an attribute definition that is no object, as `isDefinition` in `src/blocks.ts` - says. Key no `Map` or `Set` of a walk by strings a drawing holds: V8 hashes a string over - 16,383 characters by its length alone, so a table of many such strings of one length compares - each it looks up with all the others. `Strings` in `src/shape.ts` keys a long one by its length - and 80 of its characters, keeps one string a key, and says when a string takes another's - place, which the walk then pays for by its length. So distinct long strings crafted to agree at - those characters pay as if they were shared. Each insert does its first 64 attributes, and the first 64 steps of its walk, free - of the limit: that is work in proportion to the drawing. `lint` pays for each attribute an - insert places and each handle it takes past those, what a dimension reads from its style's - prefix and suffix, the search for the way back through a cycle, which finds cycles first in - one pass, and the extents of model space, which the DXF writer works out within the same - limit; past its limit, 500,000 units and 16 more for each entity and attribute definition the - drawing holds, it ends with `check-capped`, which `toDXF` refuses. `lint` boxes model space - and then each layout with one boxer, as the writer does, so the writer stops on nothing `lint` - passed. What a drawing repeats is paid for and what it holds is not: a value an insert holds - is free, a definition's value it repeats is paid for by its length. Whatever is read for each - placement reads only the fields it needs, as `inStyle` and `attributeText` do, never a copy - of all an object holds, and a measured text takes only its font, width factor and oblique - angle from its style. `toSVG` writes at most 500 million characters, and walks through - inserts at most 2,000,000 blocks and entities that draw nothing, and refuses an insert whose - walk would spend more than is left before it walks it, from the boxer's `walkCost`; what it draws counts against - the characters, so drawing an entity may cost only in proportion to what it writes: a dashed - polyline's sides that have a length are found once a picture, for each list of points. Past - either it throws a `RangeError` that names where it stopped. It joins an insert's elements as - it makes them, so the memory it holds stays near its characters. Looking a long string up in - an object can take time in proportion to its length, so a name is looked up in a table of - tsdraft's, such as `FONTS` or `ARROWHEADS`, only when it is no longer than the table's - longest, and a walk that looks a definition's tag up among an insert's values pays a unit for - each 256 characters of it, `lookupCost` in `src/blocks.ts`. - `test/bounded.test.ts` fuzzes the four from a seed under a vm timeout, with limits given to - `lintWithin`, `inspectWithin` and `svgWithin`, and with lists and values that many places - share. Every walk but `lint` may throw a `RangeError` there, and nothing else. -- `lint` takes any plain data and never throws, since a `Drawing` can be written by hand. A - `Proxy` is code, not data, and `src/`, which imports no `node:` module, has no way to tell one - from data without calling its traps. So `lint`, like the rest of the library, reads one as the - data its traps give, calling them in proportion to what it reads, and a trap that throws or - never returns does so inside the call. `test/bounded.test.ts` holds both: the traps of one that - returns are called a bounded number of times, and data a proxy makes up as it is read is - refused where its shape is wrong. The command, which runs a drawing file's code, ends a build - past its timeout. - `src/shape.ts` holds the fields of each object and their types, once, for `fromJSON` and for - `lint`. `lint` checks an object's shape there before a rule reads it, and skips the rules for - an object that fails, but still records its name, so that nothing that names it gets a - second error. A field under `ruled` is left to the rule that reports its type with a message - of its own. A message shows a value from the drawing only through `shown` in `src/rules.ts`, - and a diagnostic's field holds a name only when it is a string. An error about a value of - the wrong type carries `item`, the path of what a reader has to leave out. - `test/shape-sweep.ts` replaces every field of a full drawing with values of other types, and - its drawing is typed so that a new field or entity kind is a compile error there. Each value - runs every check on the whole drawing, so the work grows with the square of the drawing: the - test files `test/shape-sweep/share-1.test.ts` and on share the cases, and `node --test` runs - one file fewer at once than the machine has cores. `pnpm test` runs them after every other - test, in a run of their own: beside the others they fill every core for a minute, and a test - with a time limit, as in `test/bounded.test.ts`, then fails at a limit tuned to a machine - with room. Raise `SHARES` and add a file only where the machines that run the tests have the - cores for one more. -- `src/read/` reads a file into a `DrawingRead`, the read model, which is not a `Drawing` and is - never written back. `readDXF` reads as the bytes arrive and must never hold the whole file or - a list that grows with entities past its limits, `CENSUS_LIMIT`, `BLOCK_ITEMS` and - `GEOMETRY_ITEMS`; a record's binary groups are dropped as they arrive. Without `geometry` it - keeps no text of model space or a layout and no attribute value. It throws only a - `ReadError`, for a file it cannot read at all, and counts the rest it does not understand under - `unread`. A group's default, such as the text style `Standard`, is filled in, since the leading - CAD app leaves a default out. `src/read/entities.ts` reads each kind of `ReadEntity`, for blocks - and spaces alike, and `costOf` there is what each costs against a budget. A string holds what - that app holds after reading the file, by the passes `src/read/groups.ts` makes, and a justified - text whose file stores its alignment point as its start is placed from `layoutText` only where - the layout is exact. No map of a read is keyed by a name longer than a DXF value holds, since - V8 hashes a long string by its length alone. `src/read/document.ts` is the document of a DXF: - where each record is in bytes, so the records copied in order give the file back. It is - internal. `checkDrawingRead` holds a reader's answer to the model's fields: change both - together, and the reading page, `docs/reading.md`. `test/read-fuzz.ts` fuzzes the reader from - a seed, and `test/read-agreement.ts` holds a read with geometry to the `Drawing` it came from. -- `src/images.ts` is the one place of where an image's pixels go, its clip as the file holds it - and its frame: the writers, the plots, the extents and the readers all take an image from it. - A file is keyed by its path with `exactKey`, never `Strings`, since a lost key writes a file - twice. A file's bytes are untrusted input: `src/raster.ts` reads them as `src/truetype.ts` reads - a font, and decodes a PNG only up to `RASTER_PIXELS`. A browser drops the colors of a pixel of - no alpha, which the leading CAD app plots for an image not marked transparent, so `toSVG` holds - such a PNG again without its transparency, up to `OPAQUE_PIXELS`; past them it holds the file - as it is and marks the `` `data-opaque`, which `toPDF` reads. That is the one place the - preview and the plot part. A PNG the plot must decode and cannot is drawn by neither, as a file - not given. -- `src/underlays.ts` is the one place of where an underlay's page goes, its clip as the file holds - it, its frame, its colors and its definitions: the writers, the plots, the extents and the - readers all take an underlay from it. A page is one drawing unit to an inch of it at scale 1, - whatever the units. `src/` draws no PDF: `toSVG` draws a page from the PNG the caller gives in - `underlays`, its colors changed by `underlayColor` and held again in stored deflate blocks, and - `pdfPageSize` in `src/pdf-pages.ts` reads only a page's size, from untrusted bytes. The DXF - leaves out a scale of 1, as the leading CAD app saves it, and always writes the contrast and the - fade: that app saves no contrast of 75 and no fade of 25, but reads a file without them as other - values, so a reader takes a file without them as 75 and 25 and the writers never leave them out. -- `src/fills.ts` is the one place of what a hatch, a wipeout and a text's mask draw: a hatch's loops - and their sides, filled by parity, which the writers make the leading CAD app's rule too by island - style normal and polyline loops; a wipeout's square picture of one pixel and its clip; a mask's box - and factor, a paragraph's and a dimension style's. The writers, `toSVG`, the extents, `lint` and - the readers take them from it. The wipeout frame is the dictionary variable `WIPEOUTFRAME`, which is - what that app reads, beside `WIPEOUTVARIABLES`, which it does not. A hatch is drawn as one path - with `fill-rule="evenodd"`, which `toPDF` writes as `f*`. tsdraft ships no hatch pattern: a - firm's pattern file gives them. A hatch finds its pattern by `layerKey` of its name, the first of - a name, and `patternDrawnProblem` is the one check of what its lines draw, which `lint`, the - builder and `toSVG` share: a pattern that would draw more than `HATCH_LINES` lines across the - box of its loops, or place a number of 1e100 or more, is refused, and `toSVG` draws none of its - lines. A gradient is `gradientPicture`, from its loops and numbers as written: colors along a - line or out from a point in a frame mapped onto the hatch, which `toSVG` writes as a - `linearGradient` or `radialGradient` in the picture's definitions and `toPDF` as a shading in the - loops' clip. It plots in its own colors whatever the plot style table, and black is written as - `0,0,1`, since the leading CAD app reads a 421 of 0 as no color. -- `src/pdf.ts` plots layouts to PDF from the pictures `toSVG` draws of them, and decides - nothing about a drawing: every rule of what a sheet plots stays in `toSVG`, so the preview - and the plot cannot part. It reads the closed set of elements and attributes `toSVG` writes - for a layout, and refuses any other with a `RangeError` that names it, so a new element in - `toSVG` is drawn in the PDF in the same pull request or fails `test/pdf.test.ts`. It reads - each picture once, with a sticky pattern that refuses what it cannot read, and writes in - proportion to it. Each point is mapped to the page and written in points with three - decimals, never with an exponent. A text in a TrueType font whose file the caller passes in - `fonts` is set in that file, embedded as a subset; any other in Helvetica, Times or Courier - with widths from `src/font-metrics.ts`. Either way it is stretched with `Tz` to the length - `toSVG` holds it to. The library has no zlib, so a caller passes `deflate`. The same pictures give the same bytes. A picture of - a layout says its format in `data-picture`, `SHEET_PICTURE` in `src/svg.ts`, and `svgToPDF` - reads no other: raise it in the pull request that changes what an element or an attribute of - such a picture means, since the closed list catches a new one and not a changed one. -- `src/truetype.ts` reads a TrueType file for `toPDF` and cuts it to a subset. A font file is - untrusted input: every offset and count is held to the bytes before it is read, each glyph is - read once when the file is, and a file it does not take is refused with the reason as a - string, never a throw. A composite glyph built of itself, or nested deeper than 16, is refused, - so cutting a font it took always ends. `test/truetype.test.ts` mutates the shipped font from a - seed. - The writers print numbers with 6 decimals. `written` in `src/format.ts` is that rounding, and `lint` judges sizes, points and arc angles as written. A new check on a number must do the same. One exception: a paragraph's line-spacing factor is judged @@ -447,19 +60,10 @@ - `src/layers.ts` holds what the leading CAD app does with layer-name characters: the ones it refuses, the capitals it lower-cases to compare names, and the pairs only `AUDIT` calls duplicates. Never compare layer names with `toLowerCase()`. -- The leading CAD app holds linetype names to the layer-name rules and compares them the - same way, so linetypes use `layerKey`, `layerAuditKey` and the name checks of - layers. -- `src/fonts.ts` is the one list of fonts a text style may have, with the file - the leading CAD app stores for each and, for a TrueType font, its pitch and family. - `lint`, both writers and `toSVG` read the list. A TrueType font also has its `capHeight`, - which `toSVG` and the command read: the top of the font's capital `A` over its units per em, since - 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. -- Text style names use `layerKey`, `layerAuditKey` and the name checks of - layers, as linetype names do. A text holds its own width factor and oblique - angle in the file, so the writers copy them from its style. +- The leading CAD app holds linetype and text style names to the layer-name rules and compares + them the same way, so both use `layerKey`, `layerAuditKey` and the name checks of layers. A + text holds its own width factor and oblique angle in the file, so the writers copy them from + its style. - `layerAuditKey` follows only the kinds of pair `docs/layer-names.md` lists, and must never call two names duplicates when `AUDIT` does not. Add a kind only when `AUDIT` reports every pair of that kind as a duplicate. @@ -477,8 +81,5 @@ - The one dependency is `@resvg/resvg-js`, the command's PNG renderer, and it is optional. The command must keep working without it. Add no other dependency. - Changes reach this repo only through export pull requests, as - `CONTRIBUTING.md` says. Release by bumping `version` and the CHANGELOG, - merging the export pull request that carries them, then publishing a GitHub - release tagged `v` on the commit that merge made. The Release - workflow publishes to npm through trusted publishing. Never publish from a - laptop with a token. + `CONTRIBUTING.md` says, and [docs/development.md](docs/development.md) says how to + release. Never publish from a laptop with a token. diff --git a/docs/agents/bounded.md b/docs/agents/bounded.md new file mode 100644 index 0000000..f1cfdba --- /dev/null +++ b/docs/agents/bounded.md @@ -0,0 +1,80 @@ +# Bounded walks, and data of any shape + +Rules for agents who change `lint`, `inspectText`, the extents or any walk of a drawing, or what +they do with data of the wrong shape. [AGENTS.md](../../AGENTS.md) has the rules that hold for every +change. + +- `lint`, `inspectText`, the extents and `toSVG` must stay bounded on any data, by construction: + each reads a list up to its first empty slot, works out each name's `layerKey` once a call, + follows blocks with a stack of its own, and pays for what it does again, by its size, before + it does it. The data is the value as given, and a drawing made in code may share one list, + object or string among many places, which JSON cannot. So what a walk reads of one of those + and can keep, it keeps for the call, by the object or, for a value of 256 characters or more, + by the string: the extents' boxes, a text's measure through `measurer` in `src/measure.ts`, + `inspectText`'s cut of a list and the outline of a long list of points, and `lint`'s checks of + a long value and an insert's values. What a walk must read again for each place, `lint` pays + for by its size each time after the first: a list of entities or of attribute definitions, a + list of points of 64 or more, an insert's values past the first 64, and a string of 256 + characters or more in a field an entity, a definition or an insert's values has, since a + message quotes it and `toDXF` writes it again. An object of the wrong shape is reported where + it is first met, and its messages pay for their length, so a long key or kind that many objects + share is paid for each time it is quoted. Once `lint` or `inspectText` stops, it reads no entity + past there. `itemsOf` counts a list once. The boxer pays for a list that + another drawing holds too, such as one drawing given for many xrefs, and the standard's checks + pay for a shared list, each error they give from it by its length, and a shared long string. A + walk skips an attribute definition that is no object, as `isDefinition` in `src/blocks.ts` + says. Key no `Map` or `Set` of a walk by strings a drawing holds: V8 hashes a string over + 16,383 characters by its length alone, so a table of many such strings of one length compares + each it looks up with all the others. `Strings` in `src/shape.ts` keys a long one by its length + and 80 of its characters, keeps one string a key, and says when a string takes another's + place, which the walk then pays for by its length. So distinct long strings crafted to agree at + those characters pay as if they were shared. Each insert does its first 64 attributes, and the first 64 steps of its walk, free + of the limit: that is work in proportion to the drawing. `lint` pays for each attribute an + insert places and each handle it takes past those, what a dimension reads from its style's + prefix and suffix, the search for the way back through a cycle, which finds cycles first in + one pass, and the extents of model space, which the DXF writer works out within the same + limit; past its limit, 500,000 units and 16 more for each entity and attribute definition the + drawing holds, it ends with `check-capped`, which `toDXF` refuses. `lint` boxes model space + and then each layout with one boxer, as the writer does, so the writer stops on nothing `lint` + passed. What a drawing repeats is paid for and what it holds is not: a value an insert holds + is free, a definition's value it repeats is paid for by its length. Whatever is read for each + placement reads only the fields it needs, as `inStyle` and `attributeText` do, never a copy + of all an object holds, and a measured text takes only its font, width factor and oblique + angle from its style. `toSVG` writes at most 500 million characters, and walks through + inserts at most 2,000,000 blocks and entities that draw nothing, and refuses an insert whose + walk would spend more than is left before it walks it, from the boxer's `walkCost`; what it draws counts against + the characters, so drawing an entity may cost only in proportion to what it writes: a dashed + polyline's sides that have a length are found once a picture, for each list of points. Past + either it throws a `RangeError` that names where it stopped. It joins an insert's elements as + it makes them, so the memory it holds stays near its characters. Looking a long string up in + an object can take time in proportion to its length, so a name is looked up in a table of + tsdraft's, such as `FONTS` or `ARROWHEADS`, only when it is no longer than the table's + longest, and a walk that looks a definition's tag up among an insert's values pays a unit for + each 256 characters of it, `lookupCost` in `src/blocks.ts`. + `test/bounded.test.ts` fuzzes the four from a seed under a vm timeout, with limits given to + `lintWithin`, `inspectWithin` and `svgWithin`, and with lists and values that many places + share. Every walk but `lint` may throw a `RangeError` there, and nothing else. +- `lint` takes any plain data and never throws, since a `Drawing` can be written by hand. A + `Proxy` is code, not data, and `src/`, which imports no `node:` module, has no way to tell one + from data without calling its traps. So `lint`, like the rest of the library, reads one as the + data its traps give, calling them in proportion to what it reads, and a trap that throws or + never returns does so inside the call. `test/bounded.test.ts` holds both: the traps of one that + returns are called a bounded number of times, and data a proxy makes up as it is read is + refused where its shape is wrong. The command, which runs a drawing file's code, ends a build + past its timeout. + `src/shape.ts` holds the fields of each object and their types, once, for `fromJSON` and for + `lint`. `lint` checks an object's shape there before a rule reads it, and skips the rules for + an object that fails, but still records its name, so that nothing that names it gets a + second error. A field under `ruled` is left to the rule that reports its type with a message + of its own. A message shows a value from the drawing only through `shown` in `src/rules.ts`, + and a diagnostic's field holds a name only when it is a string. An error about a value of + the wrong type carries `item`, the path of what a reader has to leave out. + `test/shape-sweep.ts` replaces every field of a full drawing with values of other types, and + its drawing is typed so that a new field or entity kind is a compile error there. Each value + runs every check on the whole drawing, so the work grows with the square of the drawing: the + test files `test/shape-sweep/share-1.test.ts` and on share the cases, and `node --test` runs + one file fewer at once than the machine has cores. `pnpm test` runs them after every other + test, in a run of their own: beside the others they fill every core for a minute, and a test + with a time limit, as in `test/bounded.test.ts`, then fails at a limit tuned to a machine + with room. Raise `SHARES` and add a file only where the machines that run the tests have the + cores for one more. diff --git a/docs/agents/checks.md b/docs/agents/checks.md new file mode 100644 index 0000000..a32ff5c --- /dev/null +++ b/docs/agents/checks.md @@ -0,0 +1,35 @@ +# `inspectText` and `checkIntent` + +Rules for agents who change the text warnings or the checks of intent. [AGENTS.md](../../AGENTS.md) +has the rules that hold for every change. + +- `inspectText` in `src/inspect.ts` warns about text as it plots. It is not `lint`: its rules + and its type are its own, `LintRule` stays closed, and `toDXF` never asks it. It shares + `visibility` in `src/svg.ts` with `toSVG`, so the two leave out the same layers, and walks + inserts with `eachDrawn`. It must stay bounded: boxes are worked out once and found through + a grid, and every box the grid looks at, every point a check reads and each step of the walk + of an insert, a text by its length, and each character a warning quotes, count against one + limit, which ends the checks with `text-check-capped`, saying where, when it is reached. The walk reads blocks and xrefs cut to + what the checks keep, `looked` in `src/inspect.ts`, so linework costs it nothing, and its + steps are free for the first 64 of each insert and for as many more as one walk of every + block and xref takes. +- `checkIntent` in `src/intent.ts` checks a drawing against the intent given beside it: so + far, setbacks. It is not `lint` either, and its rules and type are its own. It finds + entities of model space by id, with `idKey`, and reads no layer's state. It takes any value + as the intent and never throws: a field it does not know, an id that names nothing or a + count that does not match is an `intent-unchecked` warning, never a pass with nothing said. + Unlike `lint`, it measures the points as the drawing holds them, not as written: rounding + the points and then the distance makes a footprint on its setback line warn, and hides a + real shortfall. It measures from the property line's first corner, and compares with one + tolerance, `toleranceOf`, for the arithmetic alone, never wider than the writers' rounding + moves a coordinate. A test of two outlines must hold when no side meets another exactly, + as on a turned lot: `contained` cuts a footprint's side at every corner of the lot within + the tolerance of it, and a corner of the lot inside the footprint puts it off the lot. It + takes only simple outlines, judged with `turn`, which is exact for the doubles held, and + refuses one that crosses or touches itself, such as a lot + with a hole. Each outline is read once and paid for before it is read, the search for its + sides that meet uses `grid` from `src/inspect.ts`, every point looked at counts against one + limit, what goes past it is one warning for each setback, and the warnings stop at a + number of their own. A warning names the part of the intent it is about + by `item`, a path such as `setbacks[0]`, so a later check of intent gets a field of + `Intent` of its own and adds no field to the warning. diff --git a/docs/agents/handles.md b/docs/agents/handles.md new file mode 100644 index 0000000..7e41ec7 --- /dev/null +++ b/docs/agents/handles.md @@ -0,0 +1,72 @@ +# Handles, blocks and xrefs + +Rules for agents who change handles from ids and names, blocks, inserts, attributes or xrefs. +[AGENTS.md](../../AGENTS.md) has the rules that hold for every change. + +- An entity with an id takes the handle `idHandle` in `src/handles.ts` gives the id, from + 2^52 up to 2^53, and a drawing that has ids has a `$HANDSEED` of 2^53. Every other object + is counted up from 1. Another drawing that dimensions the entity through an xref holds that + handle, so never change what `idHandle` returns for an id, nor `idKey`, which it hashes: + every such dimension would come loose, and the leading CAD app would report nothing. +- The range from 2^52 to 2^53 is for every handle that comes from a name, not only an + entity's id. Another kind of object, such as a block, hashes its key with a prefix that no + id can contain, such as `block:NAME`, since an id cannot hold `:` or `/`. It hashes into + the same range, and two keys that give one handle are refused as two ids are. A key that can + hold characters outside ASCII, as a block's name can, is hashed as its UTF-8 bytes. A + counted handle cannot reach 2^52, because a drawing cannot hold that many objects. Nothing + uses the handles from 2^32 up to 2^52. Keep them for a later scheme. +- `src/blocks.ts` holds the keys of the handles blocks need: a block's record and the two + objects of its definition from its name, an attribute definition from its block and tag, and + the attributes of an insert that has an id from the id and each tag. Never change a key, or + `keyHandle`, which hashes it. A key holds a name with A to Z in lower case and a tag as + written. Neither `layerKey` nor any table that can grow may be part of a key, because a + change to the table would move every handle it touches. An insert without an id and its + attributes are counted. +- The leading CAD app takes two block names for one wherever its `AUDIT` would call two layer names + duplicates, and merges the two blocks without a word. So a second block is refused by + `layerAuditKey`, and an insert finds its block by `layerKey`. +- An entity on layer `0` of a block draws as its insert's layer does. `eachDrawn` in + `src/blocks.ts` walks what an insert draws, with the layer and the matrix of each entity, + for `toSVG` and `inspectText`. It keeps its own stack, so a chain of any depth is walked, + does not enter an insert on a frozen layer, reads each list up to its first empty slot, and + asks `spend` before each block it enters and each item it reads. The extents never walk an + entity of a block: `boxer` in `src/extents.ts` keeps the box of each block's own entities, in + the block's coordinates, worked out once for each drawing it is in and whether its layer `0` + is hidden. A placement walks the blocks it inserts, with their matrices composed as + `eachDrawn` composes them, and maps the corners of each block's own box: each side takes the + corner that rounds no nearer than any point inside, so the box holds the walk's to the last + bit, is the walk's where no insert is turned, and for a turned insert may be larger. Each walk + enters its first 64 blocks free and all walks the boxer's `walking` more, which `lint` gives + the writer's whole limit, so the two take one path, and `lint` boxes model space when it holds + anything whose box can cost: an insert, a dimension, a leader or a text past `KEYED`. Past that, a placement + maps the corners of the box of all its block draws, widened by what rounding can move a number + on the way, so the extents never come out smaller than a walk's. Where a number on the way + overflowed or a product underflowed, which the slack cannot cover, it walks the blocks within + the walks left, and past them the boxer stops. A box that + depends on a block of a cycle being open is not kept for another way in. What many places share is read once a boxer: the box of a list of entities, + of a long list of points and of a leader, a long value's measure, and the inserts of a list. + An insert's attributes are written as texts in the insert's + own coordinates, which `placeAttribute` works out from the numbers as they are written. One of + paragraph text is the paragraph `attributeParagraph` gives in those coordinates, mirrored where + X runs the other way, which `eachDrawn` draws with the matrix of the space the insert is in, and + the boxer keeps apart from a block's other attributes, in the coordinates of its insert's + space, since an uneven scale lays it out again rather than stretching it. An + attribute is stored on its definition's layer, and one on layer `0` draws as its insert's + layer does. An insert on a frozen layer, or in a plot on a layer that does not plot, draws + nothing of its block. +- An xref is a block record with a path: `Drawing.xrefs` holds a name and a path, and an + insert places one by its name. It shares the blocks' names and the keys of their handles, + `block:KEY` and the two beside it, and is written as an overlay, unless `attach` is true. That + app reads the path of a BLOCK once, so the DXF writes it with `dxfOnce`. `eachDrawn` walks the + drawing a caller gives for an xref as it walks a block, with each layer as a `LayerRef` that + says which drawing's layer it is. `src/` opens no file: `toSVG` draws only the drawings it is + given. `referencedTree` in `src/blocks.ts` is the one reading of what is given in `xrefs`: a + tree of `Referenced`, one for each place, each with the drawings of its own attachments, + never of an overlay, cut where a drawing on the chain above comes again and past `XREF_DEPTH` + drawings down, with why in its problems, which `lint` reports with `xrefs`. Past `XREF_LOOKS` + names looked for inside referenced drawings it follows none, so the same given with drawings + left out cuts nothing the whole did not, which the command relies on; `drawnXrefs` gives the + tree in the form given. `eachDrawn` and the boxer read that tree, the boxer keeping a block's + box for each drawing and the drawings given for its attachments. `inspectText` reads the + drawings given for the drawing's own xrefs alone, once each, and checks no text of their + attachments: a cut for each place cost work outside its limit. diff --git a/docs/agents/images-fills.md b/docs/agents/images-fills.md new file mode 100644 index 0000000..8a5460a --- /dev/null +++ b/docs/agents/images-fills.md @@ -0,0 +1,40 @@ +# Images, underlays, hatches and masks + +Rules for agents who change images, PDF underlays, hatches, gradients, wipeouts or masks. +[AGENTS.md](../../AGENTS.md) has the rules that hold for every change. + +- `src/images.ts` is the one place of where an image's pixels go, its clip as the file holds it + and its frame: the writers, the plots, the extents and the readers all take an image from it. + A file is keyed by its path with `exactKey`, never `Strings`, since a lost key writes a file + twice. A file's bytes are untrusted input: `src/raster.ts` reads them as `src/truetype.ts` reads + a font, and decodes a PNG only up to `RASTER_PIXELS`. A browser drops the colors of a pixel of + no alpha, which the leading CAD app plots for an image not marked transparent, so `toSVG` holds + such a PNG again without its transparency, up to `OPAQUE_PIXELS`; past them it holds the file + as it is and marks the `` `data-opaque`, which `toPDF` reads. That is the one place the + preview and the plot part. A PNG the plot must decode and cannot is drawn by neither, as a file + not given. +- `src/underlays.ts` is the one place of where an underlay's page goes, its clip as the file holds + it, its frame, its colors and its definitions: the writers, the plots, the extents and the + readers all take an underlay from it. A page is one drawing unit to an inch of it at scale 1, + whatever the units. `src/` draws no PDF: `toSVG` draws a page from the PNG the caller gives in + `underlays`, its colors changed by `underlayColor` and held again in stored deflate blocks, and + `pdfPageSize` in `src/pdf-pages.ts` reads only a page's size, from untrusted bytes. The DXF + leaves out a scale of 1, as the leading CAD app saves it, and always writes the contrast and the + fade: that app saves no contrast of 75 and no fade of 25, but reads a file without them as other + values, so a reader takes a file without them as 75 and 25 and the writers never leave them out. +- `src/fills.ts` is the one place of what a hatch, a wipeout and a text's mask draw: a hatch's loops + and their sides, filled by parity, which the writers make the leading CAD app's rule too by island + style normal and polyline loops; a wipeout's square picture of one pixel and its clip; a mask's box + and factor, a paragraph's and a dimension style's. The writers, `toSVG`, the extents, `lint` and + the readers take them from it. The wipeout frame is the dictionary variable `WIPEOUTFRAME`, which is + what that app reads, beside `WIPEOUTVARIABLES`, which it does not. A hatch is drawn as one path + with `fill-rule="evenodd"`, which `toPDF` writes as `f*`. tsdraft ships no hatch pattern: a + firm's pattern file gives them. A hatch finds its pattern by `layerKey` of its name, the first of + a name, and `patternDrawnProblem` is the one check of what its lines draw, which `lint`, the + builder and `toSVG` share: a pattern that would draw more than `HATCH_LINES` lines across the + box of its loops, or place a number of 1e100 or more, is refused, and `toSVG` draws none of its + lines. A gradient is `gradientPicture`, from its loops and numbers as written: colors along a + line or out from a point in a frame mapped onto the hatch, which `toSVG` writes as a + `linearGradient` or `radialGradient` in the picture's definitions and `toPDF` as a shading in the + loops' clip. It plots in its own colors whatever the plot style table, and black is written as + `0,0,1`, since the leading CAD app reads a 421 of 0 as no color. diff --git a/docs/agents/pdf.md b/docs/agents/pdf.md new file mode 100644 index 0000000..ad7c3cf --- /dev/null +++ b/docs/agents/pdf.md @@ -0,0 +1,25 @@ +# The plot to PDF + +Rules for agents who change `toPDF`, `svgToPDF` or the TrueType reader. [AGENTS.md](../../AGENTS.md) +has the rules that hold for every change. + +- `src/pdf.ts` plots layouts to PDF from the pictures `toSVG` draws of them, and decides + nothing about a drawing: every rule of what a sheet plots stays in `toSVG`, so the preview + and the plot cannot part. It reads the closed set of elements and attributes `toSVG` writes + for a layout, and refuses any other with a `RangeError` that names it, so a new element in + `toSVG` is drawn in the PDF in the same pull request or fails `test/pdf.test.ts`. It reads + each picture once, with a sticky pattern that refuses what it cannot read, and writes in + proportion to it. Each point is mapped to the page and written in points with three + decimals, never with an exponent. A text in a TrueType font whose file the caller passes in + `fonts` is set in that file, embedded as a subset; any other in Helvetica, Times or Courier + with widths from `src/font-metrics.ts`. Either way it is stretched with `Tz` to the length + `toSVG` holds it to. The library has no zlib, so a caller passes `deflate`. The same pictures give the same bytes. A picture of + a layout says its format in `data-picture`, `SHEET_PICTURE` in `src/svg.ts`, and `svgToPDF` + reads no other: raise it in the pull request that changes what an element or an attribute of + such a picture means, since the closed list catches a new one and not a changed one. +- `src/truetype.ts` reads a TrueType file for `toPDF` and cuts it to a subset. A font file is + untrusted input: every offset and count is held to the bytes before it is read, each glyph is + read once when the file is, and a file it does not take is refused with the reason as a + string, never a throw. A composite glyph built of itself, or nested deeper than 16, is refused, + so cutting a font it took always ends. `test/truetype.test.ts` mutates the shipped font from a + seed. diff --git a/docs/agents/pictures.md b/docs/agents/pictures.md new file mode 100644 index 0000000..437a504 --- /dev/null +++ b/docs/agents/pictures.md @@ -0,0 +1,77 @@ +# What `toSVG` draws: views, text and linetypes + +Rules for agents who change `toSVG`, a view's clip and cull, the measure of a text, paragraphs, +fonts or dashes. [AGENTS.md](../../AGENTS.md) has the rules that hold for every change. + +- A view is drawn only where it can be seen. The clip of a view, the hidden rectangle and + the cull all use one rectangle: the viewport, cut to the paper, cut to the picture `toSVG` + is drawing (its `viewBox`), with every number as it will be written. If that rectangle has + no width or no height as written, the view is the empty group with no clip. `toSVG` also + takes it to have none when its two sides are one number in single precision, which is how + a renderer may read them. +- The first element of every clipped group is that rectangle, hidden. Never write a clipped + group without it. resvg, the command's PNG renderer, takes the box of a clipped group's + elements before it clips them, and stops the whole process when that box lies wholly more + than two widths of the picture left or right of it, or two heights above or below. The + hidden rectangle is in the picture and counts in that box, so the box always meets the + picture, whatever else the group holds. A viewport `lint` refuses is drawn as its border + alone. +- Leaving out of a view what cannot show in it must never leave out what shows. The cull + keeps an entity whose box, from `boxer` in `src/extents.ts`, reaches the + rectangle when the box is made larger by the widest lineweight and, for a text or an + insert, by the larger side of the box, since a letter may reach past the box of its text. + A `view` of model space is culled the same way, but its pens are as wide in pixels at any + size, so a pen is taken to reach the picture's larger side, times `strokeWidth` above 1. + The box holds the lean of a text whose style has an oblique angle: the leading CAD app slants a + text after it widens it, so the lean is the height times the tangent of the angle and the + width factor has no part in it. `toSVG` writes `skewX` before `scale` for that reason. + Build `boxer` once for a drawing: it reads every block and text style when it is made, and + keeps each block's box. `toSVG` and the DXF writer each build one for a call. +- `measureText` in `src/measure.ts` is the one measure of a text: its length from the widths + in `src/font-metrics.ts`, where its justification puts it, and the one rule for its + baseline. The extents, `toSVG` and `inspectText` all take a text's box from it, so a + warning's box is the box the picture draws. Never work a text's length or place out + anywhere else. `src/font-metrics.ts` holds, for each font of `FONTS` and each character + from U+0020 to U+007E and U+00A0 to U+00FF, the numbers of a text of height 1. It is data: + never edit a number by hand, and keep its header to what the numbers are. +- `src/paragraphs.ts` is the one layout of a paragraph, `layoutParagraph` and `measureParagraph`: + where each line and each run sits, its strokes and its box, from the font tables' advances and + their paragraph columns, each letter's ink and each bold face. + The extents, `toSVG`, `inspectText`, the writers' boxes and `src/read/mtext.ts` all take a + paragraph from it, and every rule of where a line goes is in the block at its top. Its value is + read only by `parseParagraph` in `src/paragraph-codes.ts`, in one pass with a stack of its own + and at most `PARAGRAPH_NESTING` formats, and `ParagraphValue` in `src/rules.ts` is the same + grammar as a type, which gives up past a fixed number of steps and leaves the rest to the + runtime check. Two rules only the runtime check holds: `%%c` in the style's font, which the type + does not know, and a character above U+FFFF, since TypeScript never splits the surrogate pair + that holds one. A code it does not lay out is refused by `lint`, never drawn as a guess. +- `toSVG` draws a text with no `text-anchor`, and holds it to a length with `textLength` and + `lengthAdjust="spacingAndGlyphs"`, so every renderer draws it as long in whatever typeface it + has. A text or a paragraph's run in a TrueType font is drawn from its first point and held to + its characters' advances, which the leading CAD app's PDF sets at `100 Tz`; one in an SHX + font, which plots as strokes, from where `measureText` starts it and held to the length it + plots. `xml:space="preserve"` keeps its + spaces. `data-height` follows `font-family` directly, and `font-size` comes before both: + the command finds the three together to size a text for the typeface it draws. +- The leading CAD app sizes dashes on the paper in a viewport, so `toSVG` scales a pattern by the + linetype scale over the viewport's scale there. It fits a pattern to each line, side of a + polyline and arc: the stretch holds as many whole patterns as fit, its first and last dash + are each half of the first dash and of what is left over, and a stretch shorter than its + pattern is solid. A circle holds the whole number of patterns nearest its length, stretched + alike to go round it, from a dash at angle 0. `cut` in `dashedPath` is the one place that + does it. A linetype's `marks` are placed by `markSpots`, with each whole pattern of a fitted + stretch, and `letterAt` sets each text in the frame of the side it lands on, the line's + direction in its own coordinates deciding `upright`; on an arc that frame is the straight piece + the leading CAD app cuts the arc into, `arcFrame`, 1/1200 inch from it on the paper, which + `Look.chord` holds. `shapeAt` draws a shape the same way, from the outlines `parseShapes` reads + of its file, found by `shapeFinder`, which `lint` shares. A pattern that ends with a dash runs + it into its first, `Dashes.trail`, and is fitted to its own first dash, `Dashes.lead`. A polyline's `linetypeGeneration` cuts its sides as one course, `courseOf`, + from its second point when it is closed. `toSVG` draws a layout with `elements`, the + walk it draws model space with, under a `Look` that says how wide and what color a pen is. +- `src/fonts.ts` is the one list of fonts a text style may have, with the file + the leading CAD app stores for each and, for a TrueType font, its pitch and family. + `lint`, both writers and `toSVG` read the list. A TrueType font also has its `capHeight`, + which `toSVG` and the command read: the top of the font's capital `A` over its units per em, since + 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. diff --git a/docs/agents/reading.md b/docs/agents/reading.md new file mode 100644 index 0000000..03f5fdf --- /dev/null +++ b/docs/agents/reading.md @@ -0,0 +1,22 @@ +# The readers + +Rules for agents who change anything under `src/read/`. [AGENTS.md](../../AGENTS.md) has the rules +that hold for every change. + +- `src/read/` reads a file into a `DrawingRead`, the read model, which is not a `Drawing` and is + never written back. `readDXF` reads as the bytes arrive and must never hold the whole file or + a list that grows with entities past its limits, `CENSUS_LIMIT`, `BLOCK_ITEMS` and + `GEOMETRY_ITEMS`; a record's binary groups are dropped as they arrive. Without `geometry` it + keeps no text of model space or a layout and no attribute value. It throws only a + `ReadError`, for a file it cannot read at all, and counts the rest it does not understand under + `unread`. A group's default, such as the text style `Standard`, is filled in, since the leading + CAD app leaves a default out. `src/read/entities.ts` reads each kind of `ReadEntity`, for blocks + and spaces alike, and `costOf` there is what each costs against a budget. A string holds what + that app holds after reading the file, by the passes `src/read/groups.ts` makes, and a justified + text whose file stores its alignment point as its start is placed from `layoutText` only where + the layout is exact. No map of a read is keyed by a name longer than a DXF value holds, since + V8 hashes a long string by its length alone. `src/read/document.ts` is the document of a DXF: + where each record is in bytes, so the records copied in order give the file back. It is + internal. `checkDrawingRead` holds a reader's answer to the model's fields: change both + together, and the reading page, `docs/reading.md`. `test/read-fuzz.ts` fuzzes the reader from + a seed, and `test/read-agreement.ts` holds a read with geometry to the `Drawing` it came from. diff --git a/docs/agents/sheets.md b/docs/agents/sheets.md new file mode 100644 index 0000000..a93e93d --- /dev/null +++ b/docs/agents/sheets.md @@ -0,0 +1,54 @@ +# Layouts, dimensions and leaders + +Rules for agents who change layouts, viewports, papers, dimensions or leaders. +[AGENTS.md](../../AGENTS.md) has the rules that hold for every change. + +- A layout is a sheet: `Drawing.layouts` holds each with its paper, its viewports and the + entities drawn on it in paper units. `src/papers.ts` is the one list of papers and of plot + style tables, with the name the leading CAD app stores for each paper. Add a paper only when + `DWG To PDF.pc3` has it, and with the name the plotter gives it. `src/layouts.ts` holds the + keys of a layout's handles, `layout:KEY` and the four beside it, from its name with A to Z + in lower case: never change one. That app compares layout names by a table of its own, + `layoutNameKey` in `src/layers.ts`, which is not `layerKey`. The DXF holds the first layout + in `*Paper_Space`, with its entities among model space's and marked with group 67, and + every other in a block `*Paper_Space0` and on. A viewport holds the height of its view and + no scale: `validViewportView` works it out from the numbers as they are written. +- A dimension holds its two points, its style and its text, and both writers add the block of + its picture, `*D` and a number, which the leading CAD app shows and which an xref or an insert of + the file needs: that app draws nothing for a dimension inside another drawing's block. + `src/dimensions.ts` is the one place that says what that app draws, `dimensionPicture`, and + what string it writes, `measurementText`: the writers, `toSVG`, the extents and the command + all read it, from the numbers as they are written. What a dimension reads, group 42, and the + direction of its text are written with 15 significant digits: near enough to the leading CAD app's + own, and few enough that the double that app reads from them can be worked out exactly. Every + number of a picture must stay under 1e100, which `dimensionDrawnProblem` checks for the builder + and `lint` alike. A style's sizes are paper sizes and its `scale` is that app's overall scale. The + text is always above the line and between the extension lines, so the one case that depends on a + font's widths, closed filled arrowheads that may not fit, is refused by `arrowRoom`. The keys of + the handles are `dimension-style:NAME`, with A to Z in lower case, `arrowhead:NAME` for the stroke + in an arrowhead's block, whose own handles are the block's, and `dimension-picture:WHO/PART` for + the block of a picture and what it holds, where WHO is the dimension's id with A to Z in + lower case, or `@LAYOUT/INDEX` for one without an id: never change one. A dimension is + refused inside a block, where that app draws nothing for it. +- A leader holds its note, its point, its shafts and its own sizes, and the R2018 writer writes it + as a multileader with no picture. `src/leaders.ts` is the one place that says what the leading CAD + app draws, `leaderPicture`, which the writers, `toSVG`, the extents and `inspectText` all read. + Its note is a `Paragraph`, laid out by `layoutParagraph` and held where the multileader holds it, + so the note's lines follow every rule of a paragraph's. A mask is drawn first in the leader's + group, so it hides what is drawn before the leader and none of the leader. A block in place of + the note is placed from its own outline, read once for each list of a block's entities and cut + at `OUTLINE_ITEMS`; `toSVG` draws it as an insert after the leader, so the insert walk draws it + and its attributes. A curved shaft is solved as three diagonals, in time in proportion to its + points. A style's + sizes are paper sizes times its `scale`, and the file holds them multiplied out with a scale of 1. + The writers add that app's own `Standard` and the dictionary `ACAD_MLEADERSTYLE` with the first + style. The keys of the handles are `leader-style:NAME`, with A to Z in lower case, + `dictionary:acad_mleaderstyle`, and `arrowhead:NAME` and `arrowhead:NAME/N` for the strokes of + the blocks `_Open`, `_Dot` and `_None`: never change one. A leader is refused inside a block. +- A style in architectural units, `DIMLUNIT` 4, writes feet and inches with the fraction on the + line, `DIMFRAC` 2, and `feetInchZeros` is `DIMZIN` 0 to 3. `feetAndInches` in + `src/dimensions.ts` is the string, and the dimension holds no text of its own, so the leading CAD + app measures it again when its points move. A standard's style is named in that app by + `styleNameAt` in `src/standard/rules.ts`, which the builder, `lint` and `defineStandard` share: + a `layoutName` or a name in `scaleNames` where the standard gives one, and the id's name + otherwise. diff --git a/docs/agents/standard.md b/docs/agents/standard.md new file mode 100644 index 0000000..02b455b --- /dev/null +++ b/docs/agents/standard.md @@ -0,0 +1,52 @@ +# The standard + +Rules for agents who change anything under `src/standard/`, or what the builder and `lint` do under +a standard. [AGENTS.md](../../AGENTS.md) has the rules that hold for every change. + +- `src/standard/` is a firm's standard. `shape.ts` is the one table of a document's fields: each + field's type, the rule of its value, its default and whether the hash reads it. + `scripts/standard-files.ts` writes `standard.schema.json` from it, `standard.json` from the + built-in standard and `src/version.ts` from `package.json`, and `test/standard.test.ts` fails + until `pnpm standard:files` has run after a change to any of them. A rule of a document's + literal is a type in `src/standard/literal.ts` with the runtime check's message, as a rule of a + drawing is in `src/rules.ts`. A default, once released, never changes: a change of behavior + comes as a new field or value. The library makes `BUILT_IN_STANDARD` as it loads without the + checks, with `BUILT_IN_HASH` in `src/standard/define.ts`, and a test resolves its document with + them. A change to what it states raises its version, which the CHANGELOG gives, and sets that + hash. +- A rule of a drawing drawn to a standard, which the builder refuses, is a type in + `src/standard/drawn.ts` with the runtime check's message, and its message names the standard + by the id and version its type carries. The builder finds an entry of the standard in any case, + as the leading CAD app does, and the type compares the exact spelling. `drawing.ts` reads a + standard through `src/standard/made.ts` and never imports `define.ts`, which draws the plain title + block with the builder as it loads. A drawing without a standard is built as it was before + standards. +- Under a standard, a top-level conditional on the standard's type parameter `Z` whose branches + mention `Z`, such as `Z extends Standard ? A : B` as a parameter's type, makes + `DrawingBuilder<…, undefined>` not assignable to `DrawingBuilder<…, Standard | undefined>`, + which a helper typed with `ReturnType` needs. A conditional inside a + field's type, a conditional whose branches do not mention `Z`, and a conditional that is one + member of a union are fine. In a rest tuple, an element whose type is that conditional alone + makes `DrawingBuilder<…, S>` for a standard `S` not assignable to `DrawingBuilder<…, Standard>`, + and so do overloads; `layout()` keeps it one member of a union with `| undefined`. +- Under a standard, a title block's block, the blocks it inserts and their text styles enter the + drawing under their own names when `sheet.titleBlock()` first places it, and one the drawing + has with another definition is refused: never rename one, since its handles come from its + name. The builder fills a title block's scale when the layout's `draw` returns. +- Under a standard, a role's text style and a dimension or leader style of the standard enter + the drawing on first use, under `capitals` of the id, and in model space with the view's scale + id after a dimension or leader style's: `DIMS-1in-10ft`. A view's id is taken when `view()` declares it, and the + one viewport that shows the view takes that id and no other. +- `lint(drawing, { standard })` runs the rules of a standard in `src/standard/lint.ts` after the + others, and without `standard` runs none of them. It takes the standard through `adopted` in + `src/standard/made.ts`, as the builder does, and reads only what `TYPED` in `src/shape.ts` finds + sound. A rule the builder refuses under a standard has the builder's rule name in `lint`, and + its message from `src/standard/drawn.ts` where that fits a `Drawing`. It must stay bounded by + construction: it reads a list up to its first empty slot, reads each item of the drawing once, + and pays for anything it does again, in proportion to its size, before it does it. The walk of + an insert reads blocks made once a drawing, with only what can draw a text and a short token for + each name, and pays for each block it enters. A title block's definition is compared as JSON + cut short at the length of the standard's. `test/standard-lint.test.ts` fuzzes it from a seed. + To time `lint` against a standard given as data, time the standard's own check, `adopted`, + apart from the index and the rules: it checks the whole document and works out its hash again + on each call, so it can hide what the rest costs. diff --git a/docs/development.md b/docs/development.md index a3bbb59..487fea7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -28,7 +28,8 @@ route for type-checking drawings in a browser playground. ## Releasing -Bump `version` in `package.json` and add a CHANGELOG entry. After the export +Bump `version` in `package.json`, run `pnpm standard:files`, which writes the version into +`src/version.ts` and into the `$id` of `standard.schema.json`, and add a CHANGELOG entry. After the export pull request that carries them merges, publish a GitHub release tagged `v` on the commit it made. The Release workflow checks that the tag matches the version, runs `pnpm verify` and publishes to npm through From e44cdf7d1599b7ccdb0fdeec4f0bdedf53d81572 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sun, 22 Nov 2026 01:36:09 -0500 Subject: [PATCH 34/35] Remove duplicate shape-sweep cases and share the drawability checks No change to behaviour. Co-authored-by: Claude Opus 5.5 --- cli/src/cli.ts | 73 +++++++++++++++++--------------------- cli/test/render.test.ts | 63 +++++++++++++------------------- cli/test/scratch.ts | 14 ++++++++ cli/test/warm.test.ts | 12 +------ src/images.ts | 42 ++++------------------ src/inspect.ts | 65 +++++++++++---------------------- src/rules.ts | 7 ---- src/shape.ts | 31 ++++++++++++++++ src/underlays.ts | 70 ++++++++---------------------------- test/bounded.test.ts | 9 +---- test/curves.test.ts | 29 ++++----------- test/dxf-groups.ts | 30 ++++++++++++++++ test/export.test.ts | 34 ++++++++---------- test/layouts.test.ts | 18 +--------- test/paragraphs.test.ts | 10 +----- test/points.test.ts | 16 ++------- test/read-fuzz.test.ts | 26 +++----------- test/shape-sweep.ts | 18 ++++++---- test/standard-lint.test.ts | 32 +++++++---------- test/tables.test.ts | 9 +---- test/time-limit.ts | 10 ++++++ 21 files changed, 241 insertions(+), 377 deletions(-) create mode 100644 cli/test/scratch.ts create mode 100644 test/dxf-groups.ts diff --git a/cli/src/cli.ts b/cli/src/cli.ts index b749925..2aa7fef 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -9,7 +9,7 @@ import { Builder, projectRoot, round, toState } from "./build.ts"; import { faces, pdfFonts, pngFonts } from "./fonts.ts"; import { plot } from "./pdf.ts"; import { pngUnavailable, RendererCrashed, startRenderer, toPNG } from "./png.ts"; -import type { BuildError, BuildState, LayoutOutput } from "./state.ts"; +import type { BuildError, BuildState, LayoutOutput, ViewOutput } from "./state.ts"; // A drawing file is TypeScript, which Node runs by stripping its types: from 22.18, or 23.6. const [major = 0, minor = 0] = process.versions.node.split(".").map(Number); @@ -151,7 +151,8 @@ if (command === "dev") { // The machine's fonts are looked for while the drawing is built. faces(); const outcome = (await building)!; - const layouts: { -readonly [K in keyof LayoutOutput]: LayoutOutput[K] }[] = []; + type Mutable = { -readonly [K in keyof T]: T[K] }; + const layouts: Mutable[] = []; /** * Draws a picture's PNG and writes it. When the renderer dies on the picture, gives the * reason, and the rest of the run goes on: the SVG is written, and so is every other picture. @@ -170,7 +171,7 @@ if (command === "dev") { pngMs = (pngMs ?? 0) + performance.now() - t; } }; - const outputs: { -readonly [K in keyof BuildState["outputs"]]: BuildState["outputs"][K] } = { + const outputs: Mutable = { svg: null, png: null, pngError: null, @@ -191,14 +192,14 @@ if (command === "dev") { path = join(dir, `${name}.view.svg`); writeFileSync(path, outcome.view.svg); const unavailable = pngUnavailable(); - const made = { + const made: ViewOutput = { layout: outcome.view.layout, box: { min: [view[0], view[1]], max: [view[2], view[3]] }, svg: path, - png: null as string | null, + png: null, pngError: unavailable, pngFonts: pngFonts(outcome.view.fonts, outcome.view.svg), - } as const; + }; outputs.view = made; if (unavailable === null) { path = join(dir, `${name}.view.png`); @@ -230,16 +231,16 @@ if (command === "dev") { const stem = layoutFile(name, sheet.name, taken); path = join(dir, `${stem}.svg`); writeFileSync(path, sheet.svg); - const made = { + const made: Mutable = { name: sheet.name, svg: path, - png: null as string | null, + png: null, pngError: unavailable, pngFonts: pngFonts(sheet.fonts, sheet.svg), - pdf: null as string | null, - pdfError: null as string | null, + pdf: null, + pdfError: null, pdfFonts: pdfFonts(sheet.fonts), - pdfMissing: null as string | null, + pdfMissing: null, }; if (unavailable === null) { path = join(dir, `${stem}.png`); @@ -286,41 +287,31 @@ if (command === "dev") { } catch (error) { failed = outputError(`Could not write ${path}`, error); } - // A picture this run did not write is not left behind from an earlier run, where it would - // pass for the drawing as it is now. Only in the default folder, which is this command's: a - // file in a folder the user named may be theirs. - for (const [kind, written] of Object.entries({ - svg: outputs.svg, - png: outputs.png, - "view.svg": outputs.view?.svg ?? null, - "view.png": outputs.view?.png ?? null, - pdf: outputs.pdf, - })) { - if (written !== null || values.out !== undefined) continue; - const old = join(dir, `${name}.${kind}`); - try { - rmSync(old, { force: true }); - } catch (error) { - if (outcome.ok) failed ??= outputError(`Could not remove the old ${old}`, error); - } - } - // The same for the picture of a layout the drawing no longer has. - if (values.out === undefined && existsSync(dir)) { - const kept = new Set(layouts.flatMap((made) => [made.svg, made.png, made.pdf])); - for (const entry of readdirSync(dir)) { - const old = join(dir, entry); - if ( - !entry.startsWith(`${name}.layout-`) || - !/\.(svg|png|pdf)$/.test(entry) || - kept.has(old) - ) { - continue; - } + // Only the default folder belongs to the command. A file in --out may be the user's. + if (values.out === undefined) { + const removeOld = (old: string): void => { try { rmSync(old, { force: true }); } catch (error) { if (outcome.ok) failed ??= outputError(`Could not remove the old ${old}`, error); } + }; + for (const [kind, written] of Object.entries({ + svg: outputs.svg, + png: outputs.png, + "view.svg": outputs.view?.svg ?? null, + "view.png": outputs.view?.png ?? null, + pdf: outputs.pdf, + })) { + if (written === null) removeOld(join(dir, `${name}.${kind}`)); + } + if (existsSync(dir)) { + const kept = new Set(layouts.flatMap((made) => [made.svg, made.png, made.pdf])); + for (const entry of readdirSync(dir)) { + if (!entry.startsWith(`${name}.layout-`) || !/\.(svg|png|pdf)$/.test(entry)) continue; + const old = join(dir, entry); + if (!kept.has(old)) removeOld(old); + } } } const state = toState(outcome, randomUUID().slice(0, 8), 1, file, outcome.ok ? 1 : null, outputs); diff --git a/cli/test/render.test.ts b/cli/test/render.test.ts index 377e4ec..cd2ccbe 100644 --- a/cli/test/render.test.ts +++ b/cli/test/render.test.ts @@ -17,6 +17,7 @@ import { join } from "node:path"; 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 { faces } from "../src/fonts.ts"; import type { BuildState } from "../src/state.ts"; @@ -141,13 +142,10 @@ export default createDrawing().line([0, 0], [1, 1], { lineweight: weight as 0.5 test("a build that fails leaves no picture from an earlier run in the default folder", () => { const dir = realpathSync(tempDir()); const plan = join(dir, "plan.ts"); - writeFileSync( - plan, - `export default { format: 0, units: "ft", dxf: "R2018", layers: [{ name: "0", color: 7 }], - entities: [{ kind: "line", layer: "0", from: [0, 0], to: [1, 0] }] };\n`, - ); - const { outputs } = render(plan).state; - assert.deepEqual([existsSync(outputs.svg!), existsSync(outputs.png!)], [true, true]); + const out = join(dir, "out"); + mkdirSync(out); + const stale = ["plan.svg", "plan.png"].map((name) => join(out, name)); + for (const path of stale) writeFileSync(path, "stale"); // In a folder the user named, a picture this run did not write may be theirs, and stays. const theirs = join(dir, "kept"); mkdirSync(theirs); @@ -165,7 +163,10 @@ test("a build that fails leaves no picture from an earlier run in the default fo pdf: null, pdfError: null, }); - assert.deepEqual([existsSync(outputs.svg!), existsSync(outputs.png!)], [false, false]); + assert.deepEqual( + stale.map((path) => existsSync(path)), + [false, false], + ); }); test("the state says which blocks a drawing has and where each is inserted", () => { @@ -660,17 +661,6 @@ async function withDev( } } -/** A folder under examples/out, removed after `use`. A project in it links tsdraft itself. */ -async function inScratch(use: (dir: string) => Promise): Promise { - mkdirSync(join(root, "examples/out"), { recursive: true }); - const dir = mkdtempSync(join(root, "examples/out/test-")); - try { - await use(dir); - } finally { - rmSync(dir, { recursive: true, force: true }); - } -} - test("dev answers /state.json?after= with the first build newer than n", () => inScratch(async (dir) => { const file = join(dir, "lot.ts"); @@ -1477,11 +1467,6 @@ test("render --view draws one rectangle of model space or of a layout, and nothi assert.deepEqual([png.readUInt32BE(16), png.readUInt32BE(20)], [700, 100]); assert.ok(!existsSync(join(out, "crowded.svg")) && !existsSync(join(out, "crowded.png"))); - // A rectangle that starts with a negative number, given as the next argument. - const negative = render(crowded, "--out", out, "--view", "-1,-1,18.5,7", "--width", "700"); - assert.equal(negative.status, 0); - assert.deepEqual(negative.state.outputs.view?.box, { min: [-1, -1], max: [18.5, 7] }); - // A corner of the sheet that misses its viewport: the tag is drawn, and no view. const sheet = render(crowded, "--out", out, "--layout", "S-1", "--view=10,7.5,11,8.5"); assert.equal(sheet.status, 0); @@ -1513,25 +1498,27 @@ test("render --view draws one rectangle of model space or of a layout, and nothi } }); -test("in the default folder a view replaces the whole pictures, and they replace it", () => { - mkdirSync(join(root, "examples/out"), { recursive: true }); - const scratch = mkdtempSync(join(root, "examples/out/test-")); - const file = join(scratch, "crowded.ts"); - writeFileSync(file, readFileSync(join(root, "test/fixtures/crowded.ts"))); - const names = ["crowded.svg", "crowded.png", "crowded.layout-S-1.svg", "crowded.layout-S-1.png"]; - const views = ["crowded.view.svg", "crowded.view.png"]; - const there = (list: readonly string[]) => list.map((n) => existsSync(join(scratch, "out", n))); - try { +test("in the default folder a view replaces the whole pictures, and they replace it", () => + inScratch((scratch) => { + const file = join(scratch, "crowded.ts"); + writeFileSync(file, readFileSync(join(root, "test/fixtures/crowded.ts"))); + const names = [ + "crowded.svg", + "crowded.png", + "crowded.layout-S-1.svg", + "crowded.layout-S-1.png", + ]; + const views = ["crowded.view.svg", "crowded.view.png"]; + const there = (list: readonly string[]) => list.map((n) => existsSync(join(scratch, "out", n))); assert.equal(render(file).status, 0); assert.deepEqual([...there(names), ...there(views)], [true, true, true, true, false, false]); - assert.equal(render(file, "--view", "0,0,5,5").status, 0); + const view = render(file, "--view", "-1,-1,5,5"); + assert.equal(view.status, 0); + assert.deepEqual(view.state.outputs.view?.box, { min: [-1, -1], max: [5, 5] }); assert.deepEqual([...there(names), ...there(views)], [false, false, false, false, true, true]); assert.equal(render(file).status, 0); assert.deepEqual([...there(names), ...there(views)], [true, true, true, true, false, false]); - } finally { - rmSync(scratch, { recursive: true, force: true }); - } -}); + })); const prlimit = spawnSync("prlimit", ["--version"]).status === 0; diff --git a/cli/test/scratch.ts b/cli/test/scratch.ts new file mode 100644 index 0000000..a522743 --- /dev/null +++ b/cli/test/scratch.ts @@ -0,0 +1,14 @@ +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; + +/** A temporary project inside the package so its imports resolve to this copy of tsdraft. */ +export async function inScratch(use: (dir: string) => void | Promise): Promise { + const out = join(import.meta.dirname, "../examples/out"); + mkdirSync(out, { recursive: true }); + const dir = mkdtempSync(join(out, "test-")); + try { + await use(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} diff --git a/cli/test/warm.test.ts b/cli/test/warm.test.ts index a9ddc5a..5600751 100644 --- a/cli/test/warm.test.ts +++ b/cli/test/warm.test.ts @@ -6,7 +6,6 @@ import { spawn, spawnSync } from "node:child_process"; import { cpSync, mkdirSync, - mkdtempSync, readFileSync, renameSync, rmSync, @@ -16,6 +15,7 @@ import { import { join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { test } from "node:test"; +import { inScratch } from "./scratch.ts"; import { Builder, type Outcome } from "../src/build.ts"; import { librarySteps } from "../src/warmup.ts"; @@ -73,16 +73,6 @@ const answer = ({ ms: _ms, timings: _timings, modules: _modules, files, ...rest files: [...files].sort(), }); -async function inScratch(use: (dir: string) => Promise): Promise { - mkdirSync(join(root, "examples/out"), { recursive: true }); - const dir = mkdtempSync(join(root, "examples/out/test-")); - try { - await use(dir); - } finally { - rmSync(dir, { recursive: true, force: true }); - } -} - const LOT = 'import { createDrawing } from "tsdraft";\nconst d = createDrawing({ units: "ft" });\n' + 'd.layer("A", { color: 1 }, () => d.line([0, 0], [1, 1]));\nexport default d.build();\n'; diff --git a/src/images.ts b/src/images.ts index a0d7358..e83893e 100644 --- a/src/images.ts +++ b/src/images.ts @@ -7,7 +7,7 @@ import { keyHandle } from "./handles.ts"; import { layerKey } from "./layers.ts"; import { imagePixelsProblem } from "./rules.ts"; import { sha256Text } from "./sha256.ts"; -import { filled, KEYED } from "./shape.ts"; +import { drawableClip, filled, isFinitePoint, KEYED } from "./shape.ts"; /** * A key of a `Map` for a string of any length, which no other string has: the string itself, or @@ -17,22 +17,6 @@ export function exactKey(text: string): string { return text.length <= KEYED ? `=${text}` : `#${sha256Text(text)}`; } -/** A plain array of `count` finite numbers or more, read without running a getter. */ -function finiteNumbers(value: unknown, count: number): boolean { - if ( - !Array.isArray(value) || - value.length !== count || - Reflect.ownKeys(value).length !== count + 1 - ) - return false; - for (let i = 0; i < count; i++) { - const item = Object.getOwnPropertyDescriptor(value, i); - if (!item || !("value" in item) || typeof item.value !== "number") return false; - if (!Number.isFinite(item.value)) return false; - } - return true; -} - /** * Whether an image's fields can be drawn: a path, its pixels, a point and finite sizes not 0, and * a clip of two points or more, each a point, plain arrays all. The plots and the extents leave @@ -44,21 +28,10 @@ export function imageDrawable(image: Image, checked?: WeakMap): >; const size = (n: unknown) => typeof n === "number" && Number.isFinite(n) && n !== 0; if (typeof path !== "string" || imagePixelsProblem(pixels) !== undefined) return false; - if (!finiteNumbers(at, 2) || !size(width) || !size(height)) return false; + if (!isFinitePoint(at) || !size(width) || !size(height)) return false; if (rotation !== undefined && !(typeof rotation === "number" && Number.isFinite(rotation))) return false; - if (clip === undefined) return true; - if (!Array.isArray(clip) || clip.length < 2) return false; - // A list many images share is read once a call that keeps what it found in `checked`. - const known = checked?.get(clip); - if (known !== undefined) return known; - let sound = Reflect.ownKeys(clip).length === clip.length + 1; - for (let i = 0; sound && i < clip.length; i++) { - const item = Object.getOwnPropertyDescriptor(clip, i); - sound = item !== undefined && "value" in item && finiteNumbers(item.value, 2); - } - checked?.set(clip, sound); - return sound; + return drawableClip(clip, checked); } /** The vectors of one pixel of an image: along its bottom edge, and up its side. */ @@ -269,7 +242,6 @@ export function imageDefinitions(images: Iterable): ImageDefinition[] { // The next number to try after each name taken, so that many files of one name are named in // time in proportion to their count. const next = new Map(); - const found: ImageDefinition[] = []; for (const image of images) { const path = imagePathKey(image.path); const key = exactKey(path); @@ -287,16 +259,14 @@ export function imageDefinitions(images: Iterable): ImageDefinition[] { next.set(baseKey, n + 1); } taken.add(exactKey(layerKey(name))); - const definition: ImageDefinition = { + byPath.set(key, { name, path: image.path, pixels: [image.pixels[0], image.pixels[1]], handle: imageDefinitionHandle(image.path), - }; - byPath.set(key, definition); - found.push(definition); + }); } - return found; + return [...byPath.values()]; } /** diff --git a/src/inspect.ts b/src/inspect.ts index 980484c..42f2e4f 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -337,6 +337,23 @@ export function inspectWithin( ): void => { const { id, layer } = entities[index]!; const place = (p: Point): Point => (matrix ? mapPoint(matrix, p) : p); + const keepText = (value: string, corners: readonly Point[], anchor?: () => Point): void => { + const placed = matrix ? corners.map(place) : corners; + const inner = innerBox(placed); + if (!inner) return; + texts.push({ + entity: index, + attribute, + id, + layer, + value, + at: anchor ? anchor() : placed[0]!, + corners: placed, + inner: inner.corners, + height: inner.height, + box: boxOf(placed), + }); + }; if (drawn.kind === "leader") { // Each line of a leader's note is a text where its picture puts it. const tables = tablesOf(from); @@ -376,21 +393,7 @@ export function inspectWithin( for (const text of pictureTexts(dimensionPicture(drawn, style, font), font)) { for (const line of measured(text, layoutDimensionText(text)).lines) { if (line.value.trim() === "") continue; - const placed = matrix ? line.corners.map(place) : line.corners; - const inner = innerBox(placed); - if (!inner) continue; - texts.push({ - entity: index, - attribute, - id, - layer, - value: line.value, - at: placed[0]!, - corners: placed, - inner: inner.corners, - height: inner.height, - box: boxOf(placed), - }); + keepText(line.value, line.corners); } } return; @@ -411,42 +414,14 @@ export function inspectWithin( expanded.add(layout); if (repeated && !walk(layout.lines.length)) return; for (const line of measured(paragraph, layout).lines) { - const placed = matrix ? line.corners.map(place) : line.corners; - const inner = innerBox(placed); - if (!inner) continue; - texts.push({ - entity: index, - attribute, - id, - layer, - value: line.value, - at: placed[0]!, - corners: placed, - inner: inner.corners, - height: inner.height, - box: boxOf(placed), - }); + keepText(line.value, line.corners); } return; } if (drawn.kind === "text") { const style = styleOf(drawn, from); const { corners } = measure(inStyle(drawn, style)); - const placed = matrix ? corners.map(place) : corners; - const inner = innerBox(placed); - if (!inner) return; - texts.push({ - entity: index, - attribute, - id, - layer, - value: drawn.value, - at: place(drawn.at), - corners: placed, - inner: inner.corners, - height: inner.height, - box: boxOf(placed), - }); + keepText(drawn.value, corners, () => place(drawn.at)); } else if (drawn.kind === "polyline") { if (matrix && !spend(Math.floor(drawn.points.length / 8))) return; const long = !matrix && drawn.points.length >= LONG; diff --git a/src/rules.ts b/src/rules.ts index 55c6c98..d529479 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -816,13 +816,6 @@ export type ZeroSuppressionOf = string extends Z ? Z : typeof ZERO_SUPPRESSION; -/** Resolves to `U` when it is a dimension style's `units`, and to the error message otherwise. */ -export type DimensionUnitsOf = string extends U - ? U - : U extends (typeof DIMENSION_UNITS)[number] - ? U - : typeof DIMENSION_UNITS_MESSAGE; - /** Resolves to `Z` when it is a `feetInchZeros`, and to the error message otherwise. */ export type FeetInchZerosOf = string extends Z ? Z diff --git a/src/shape.ts b/src/shape.ts index 50e4894..b3c6310 100644 --- a/src/shape.ts +++ b/src/shape.ts @@ -39,6 +39,7 @@ import type { LinetypeText, Paragraph, PatternLine, + Point, PointEntity, Polyline, Text, @@ -140,6 +141,36 @@ export function arrayProblem(value: unknown, at: string): string | undefined { return Array.isArray(value) && value instanceof Array ? undefined : `${at} must be an array`; } +/** A pair of finite coordinates with no extra keys or indexed getters. */ +export function isFinitePoint(value: unknown): value is Point { + if (!Array.isArray(value) || value.length !== 2 || Reflect.ownKeys(value).length !== 3) + return false; + for (let i = 0; i < 2; i++) { + const item = Object.getOwnPropertyDescriptor(value, i); + if (!item || !("value" in item) || !Number.isFinite(item.value)) return false; + } + return true; +} + +/** + * Whether an image's or an underlay's clip can be drawn: absent, or a plain array of two points or + * more. Many entities may share one list, so a call that passes `checked` reads each list once and + * keeps the answer, `false` included. + */ +export function drawableClip(clip: unknown, checked?: WeakMap): boolean { + if (clip === undefined) return true; + if (!Array.isArray(clip) || clip.length < 2) return false; + const known = checked?.get(clip); + if (known !== undefined) return known; + let sound = Reflect.ownKeys(clip).length === clip.length + 1; + for (let i = 0; sound && i < clip.length; i++) { + const item = Object.getOwnPropertyDescriptor(clip, i); + sound = item !== undefined && "value" in item && isFinitePoint(item.value); + } + checked?.set(clip, sound); + return sound; +} + /** * The longest string V8 hashes by its characters. It hashes a longer one by its length alone, so * a `Map` keyed by many long strings of one length compares each it looks up with all the others. diff --git a/src/underlays.ts b/src/underlays.ts index 7d33be0..a7e2d13 100644 --- a/src/underlays.ts +++ b/src/underlays.ts @@ -6,23 +6,7 @@ import { written } from "./format.ts"; import { keyHandle } from "./handles.ts"; import { exactKey } from "./images.ts"; import { layerKey } from "./layers.ts"; -import { filled } from "./shape.ts"; - -/** A plain array of `count` finite numbers, read without running a getter. */ -function finiteNumbers(value: unknown, count: number): boolean { - if ( - !Array.isArray(value) || - value.length !== count || - Reflect.ownKeys(value).length !== count + 1 - ) - return false; - for (let i = 0; i < count; i++) { - const item = Object.getOwnPropertyDescriptor(value, i); - if (!item || !("value" in item) || typeof item.value !== "number") return false; - if (!Number.isFinite(item.value)) return false; - } - return true; -} +import { drawableClip, filled, isFinitePoint } from "./shape.ts"; /** * Whether an underlay's fields can be drawn: a path and a page, a page size of two numbers above @@ -34,24 +18,14 @@ export function underlayDrawable(underlay: Underlay, checked?: WeakMap >; if (typeof path !== "string" || (page !== undefined && typeof page !== "string")) return false; - if (!finiteNumbers(pageSize, 2) || !finiteNumbers(at, 2)) return false; - const [w, h] = pageSize as [number, number]; + if (!isFinitePoint(pageSize) || !isFinitePoint(at)) return false; + const [w, h] = pageSize; if (!(w > 0 && h > 0)) return false; if (scale !== undefined && !(typeof scale === "number" && Number.isFinite(scale) && scale !== 0)) return false; if (rotation !== undefined && !(typeof rotation === "number" && Number.isFinite(rotation))) return false; - if (clip === undefined) return true; - if (!Array.isArray(clip) || clip.length < 2) return false; - const known = checked?.get(clip); - if (known !== undefined) return known; - let sound = Reflect.ownKeys(clip).length === clip.length + 1; - for (let i = 0; sound && i < clip.length; i++) { - const item = Object.getOwnPropertyDescriptor(clip, i); - sound = item !== undefined && "value" in item && finiteNumbers(item.value, 2); - } - checked?.set(clip, sound); - return sound; + return drawableClip(clip, checked); } /** The page's name an underlay shows: its number from 1, `"1"` when it gives none. */ @@ -74,7 +48,7 @@ export function underlayVectors(underlay: Underlay): [u: Point, v: Point] { } /** The lower-left corner as written, and the vectors of one inch of the page. */ -function placed(underlay: Underlay): { at: Point; u: Point; v: Point } { +export function underlayPlacement(underlay: Underlay): { at: Point; u: Point; v: Point } { const [u, v] = underlayVectors(underlay); return { at: [written(underlay.at[0]), written(underlay.at[1])], u, v }; } @@ -93,7 +67,7 @@ export function fromPage(at: Point, u: Point, v: Point, [x, y]: Point): Point { /** The corners of an underlay's page in the drawing, from its lower-left round counterclockwise. */ export function underlayCorners(underlay: Underlay): [Point, Point, Point, Point] { - const { at, u, v } = placed(underlay); + const { at, u, v } = underlayPlacement(underlay); const [w, h] = underlay.pageSize; return [at, fromPage(at, u, v, [w, 0]), fromPage(at, u, v, [w, h]), fromPage(at, u, v, [0, h])]; } @@ -105,7 +79,7 @@ export function underlayCorners(underlay: Underlay): [Point, Point, Point, Point */ export function underlayClip(underlay: Underlay): Point[] { if (underlay.clip === undefined) return []; - const { at, u, v } = placed(underlay); + const { at, u, v } = underlayPlacement(underlay); const points = underlay.clip.map(([x, y]) => toPage(at, u, v, [written(x), written(y)])); if (points.length !== 2) return points; const [[x0, y0], [x1, y1]] = points as [Point, Point]; @@ -122,7 +96,7 @@ export function underlayClip(underlay: Underlay): Point[] { */ export function underlayFrame(underlay: Underlay): Point[] { if (underlay.clip === undefined) return underlayCorners(underlay); - const { at, u, v } = placed(underlay); + const { at, u, v } = underlayPlacement(underlay); const clip = underlayClip(underlay); const back = (p: Point) => fromPage(at, u, v, p); if (clip.length === 2) { @@ -233,7 +207,6 @@ export function underlayFrameValue(frame: Drawing["underlayFrame"]): 0 | 1 | 2 { export function underlayDefinitions(underlays: Iterable): UnderlayDefinition[] { const byKey = new Map(); const taken = new Set(); - const found: UnderlayDefinition[] = []; // The next number to try after each name taken, so many files of one name are named in time. const next = new Map(); for (const underlay of underlays) { @@ -254,16 +227,14 @@ export function underlayDefinitions(underlays: Iterable): UnderlayDefi next.set(baseKey, n + 1); } taken.add(exactKey(layerKey(name))); - const definition: UnderlayDefinition = { + byKey.set(key, { name, path: underlay.path, page, handle: underlayDefinitionHandle(underlay.path, page), - }; - byKey.set(key, definition); - found.push(definition); + }); } - return found; + return [...byKey.values()]; } /** @@ -318,17 +289,11 @@ export function underlayLook(underlay: Underlay): { monochrome: boolean; } { const { fade, contrast } = underlay as { fade?: unknown; contrast?: unknown }; + const within = (n: unknown, least: number, most: number): n is number => + Number.isInteger(n) && (n as number) >= least && (n as number) <= most; return { - fade: - Number.isInteger(fade) && (fade as number) >= 0 && (fade as number) <= UNDERLAY_FADE_MOST - ? (fade as number) - : 0, - contrast: - Number.isInteger(contrast) && - (contrast as number) >= UNDERLAY_CONTRAST_LEAST && - (contrast as number) <= 100 - ? (contrast as number) - : 100, + fade: within(fade, 0, UNDERLAY_FADE_MOST) ? fade : 0, + contrast: within(contrast, UNDERLAY_CONTRAST_LEAST, 100) ? contrast : 100, monochrome: underlay.monochrome === true, }; } @@ -365,8 +330,3 @@ export function missingReach(underlay: Underlay): number { ); return (longest + 1) * MISSING_HEIGHT * Math.abs(written(underlay.scale ?? 1)); } - -/** Where `placed` puts the page, for the plot: its corner as written and its vectors. */ -export function underlayPlacement(underlay: Underlay): { at: Point; u: Point; v: Point } { - return placed(underlay); -} diff --git a/test/bounded.test.ts b/test/bounded.test.ts index 9f3775a..eecb623 100644 --- a/test/bounded.test.ts +++ b/test/bounded.test.ts @@ -1,7 +1,6 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { test } from "node:test"; -import { Script } from "node:vm"; import sheet, { standard } from "../examples/site-plan.ts"; import { createDrawing, @@ -29,7 +28,7 @@ import { Strings } from "../src/shape.ts"; import { svgToPDF } from "../src/pdf.ts"; import { svgWithin } from "../src/svg.ts"; import { toDXFR2018 } from "../src/dxf-r2018.ts"; -import { timeLimit } from "./time-limit.ts"; +import { within } from "./time-limit.ts"; /** The command's own font, given to the PDF as the file of every TrueType font, to embed. */ const shipped = new Uint8Array( @@ -37,12 +36,6 @@ const shipped = new Uint8Array( ); const embedded = { Arial: shipped, Calibri: shipped, "Times New Roman": shipped }; -const running = new Script("running()"); -/** What `fn` gives, stopped after `ms`, so a run that never ends fails. */ -const within = (ms: number, fn: () => T): T => { - Object.assign(globalThis, { running: fn }); - return running.runInThisContext({ timeout: timeLimit(ms) }) as T; -}; /** What `fn` gives or throws, stopped after `ms`. */ const settled = (ms: number, fn: () => unknown): unknown => within(ms, () => { diff --git a/test/curves.test.ts b/test/curves.test.ts index f19a782..f4e6db2 100644 --- a/test/curves.test.ts +++ b/test/curves.test.ts @@ -15,22 +15,7 @@ import { clamped, ellipsePoint, splinePoint } from "../src/curves.ts"; import { extents } from "../src/extents.ts"; import { readProblems } from "./read-agreement.ts"; -/** The groups of the `n`th record of `type` in a DXF, as `code=value`. */ -function record(dxf: string, type: string, n = 0): string[] { - const lines = dxf.split("\r\n"); - let at = -1; - for (let k = 0; k <= n; k++) { - at = lines.findIndex((line, i) => i > at && line === type && lines[i - 1]!.trim() === "0"); - } - const out: string[] = []; - for (let i = at + 1; i + 1 < lines.length && lines[i]!.trim() !== "0"; i += 2) - out.push(`${lines[i]!.trim()}=${lines[i + 1]}`); - return out; -} - -/** The groups of a record from its subclass on, without its handle and owner. */ -const own = (groups: readonly string[], subclass: string) => - groups.slice(groups.indexOf(`100=${subclass}`) + 1); +import { recordFields } from "./dxf-groups.ts"; const drawing = (entities: Entity[]): Drawing => ({ ...createDrawing().build(), entities }); @@ -97,22 +82,22 @@ test("toDXF writes an ellipse and a spline as the leading CAD app saves them", ( }, ]), ); - assert.deepEqual(own(record(dxf, "ELLIPSE"), "AcDbEllipse"), [ + assert.deepEqual(recordFields(dxf, "ELLIPSE", "AcDbEllipse"), [ ...["10=1", "20=2", "30=0", "11=3", "21=0", "31=0", "210=0", "220=0", "230=1", "40=0.5"], ...["41=0", "42=6.28318530717959"], ]); - assert.deepEqual(own(record(dxf, "ELLIPSE", 1), "AcDbEllipse").slice(-2), [ + assert.deepEqual(recordFields(dxf, "ELLIPSE", "AcDbEllipse", 1).slice(-2), [ "41=5.23598775598299", "42=7.33038285837618", ]); - assert.deepEqual(own(record(dxf, "SPLINE"), "AcDbSpline"), [ + assert.deepEqual(recordFields(dxf, "SPLINE", "AcDbSpline"), [ ...["210=0", "220=0", "230=1", "70=12", "71=2", "72=6", "73=3", "74=0"], ...["42=0.000000001", "43=0.0000000001"], ...["40=0", "40=0", "40=0", "40=1", "40=1", "40=1"], ...["10=0", "20=0", "30=0", "41=1", "10=0", "20=1", "30=0", "41=0.5"], ...["10=1", "20=1", "30=0", "41=1"], ]); - const periodic = own(record(dxf, "SPLINE", 1), "AcDbSpline"); + const periodic = recordFields(dxf, "SPLINE", "AcDbSpline", 1); assert.deepEqual(periodic.slice(3, 8), ["70=11", "71=3", "72=11", "73=7", "74=0"]); assert.deepEqual( periodic.filter((g) => g.startsWith("40=")).map((g) => Number(g.slice(3))), @@ -121,7 +106,7 @@ test("toDXF writes an ellipse and a spline as the leading CAD app saves them", ( const points = periodic.filter((g) => /^[12]0=/.test(g)); assert.deepEqual(points.slice(0, 2), points.slice(-2)); // Through two points: a line, its four control points a third of the way apart. - const two = own(record(dxf, "SPLINE", 2), "AcDbSpline"); + const two = recordFields(dxf, "SPLINE", "AcDbSpline", 2); assert.deepEqual(two.slice(3, 15), [ ...["70=1080", "71=3", "72=8", "73=4", "74=2"], ...["42=0.000000001", "43=0.0000000001", "44=0.0000000001"], @@ -141,7 +126,7 @@ test("toDXF writes an ellipse and a spline as the leading CAD app saves them", ( ], ); // Closed: its first fit point again at the end, and one tangent at both ends. - const ring = own(record(dxf, "SPLINE", 3), "AcDbSpline"); + const ring = recordFields(dxf, "SPLINE", "AcDbSpline", 3); assert.deepEqual(ring.slice(3, 8), ["70=1067", "71=3", "72=10", "73=6", "74=4"]); const tangent = (codes: readonly number[]) => codes.map((code) => ring.find((g) => g.startsWith(`${code}=`))!.split("=")[1]); diff --git a/test/dxf-groups.ts b/test/dxf-groups.ts new file mode 100644 index 0000000..c3c0585 --- /dev/null +++ b/test/dxf-groups.ts @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; + +/** Parses DXF text into [code, value] pairs. */ +export function pairs(dxf: string): [number, string][] { + const lines = dxf.split("\r\n"); + assert.equal(lines.pop(), "", "DXF ends with CRLF"); + assert.equal(lines.length % 2, 0, "DXF has whole group-code pairs"); + const out: [number, string][] = []; + for (let i = 0; i < lines.length; i += 2) out.push([Number(lines[i]), lines[i + 1] ?? ""]); + return out; +} + +/** The records of a DXF: each from one group 0 to the next. */ +export function records(dxf: string): [number, string][][] { + const out: [number, string][][] = []; + for (const pair of pairs(dxf)) { + if (pair[0] === 0) out.push([]); + out.at(-1)?.push(pair); + } + return out; +} + +/** The groups following the subclass marker in the nth record of this type. */ +export function recordFields(dxf: string, type: string, subclass: string, n = 0): string[] { + const groups = records(dxf).filter((record) => record[0]?.[1] === type)[n]; + assert.ok(groups, `Missing ${type} record ${n}`); + const marker = groups.findIndex(([code, value]) => code === 100 && value === subclass); + assert.notEqual(marker, -1, `Missing ${subclass} in ${type}`); + return groups.slice(marker + 1).map(([code, value]) => `${code}=${value}`); +} diff --git a/test/export.test.ts b/test/export.test.ts index cf688a1..6d5f88d 100644 --- a/test/export.test.ts +++ b/test/export.test.ts @@ -11,15 +11,7 @@ import { type Drawing, } from "../src/index.ts"; -/** Parses DXF text into [code, value] pairs. */ -function pairs(dxf: string): [number, string][] { - const lines = dxf.split("\r\n"); - assert.equal(lines.pop(), "", "DXF ends with CRLF"); - assert.equal(lines.length % 2, 0, "DXF has whole group-code pairs"); - const out: [number, string][] = []; - for (let i = 0; i < lines.length; i += 2) out.push([Number(lines[i]), lines[i + 1] ?? ""]); - return out; -} +import { pairs } from "./dxf-groups.ts"; function sample() { const b = createDrawing({ units: "ft", dxf: "R12" }); @@ -58,7 +50,9 @@ test("SVG flips Y, escapes text and colors by layer", () => { test("empty drawing still exports", () => { const d = createDrawing().build(); - assert.deepEqual(pairs(toDXF(d)).at(-1), [0, "EOF"]); + const groups = pairs(toDXF(d)); + assert.deepEqual(groups.at(-1), [0, "EOF"]); + assert.ok(groups.some(([code, value]) => code === 1 && value === "AC1032")); assert.match(toSVG(d), /^ { assert.deepEqual(p.at(-1), [0, "EOF"]); assert.equal(after("$ACADVER"), "AC1032"); + const xedit = p.findIndex(([code, name]) => code === 9 && name === "$XEDIT"); + assert.deepEqual(p[xedit + 1], [290, "0"]); assert.equal(after("$INSUNITS"), "2", "feet"); assert.equal(after("$MEASUREMENT"), "0", "imperial"); const sections = p.flatMap(([c, v], i) => (c === 0 && v === "SECTION" ? [p[i + 1]?.[1]] : [])); @@ -115,7 +111,6 @@ test("R2018 DXF records metric units and keeps UTF-8 text", () => { assert.match(dxf, /\$INSUNITS\r\n70\r\n4\r\n/); assert.match(dxf, /\$MEASUREMENT\r\n70\r\n1\r\n/); assert.match(dxf, /\r\nØ 25 – café\r\n/); - assert.deepEqual(pairs(toDXF(createDrawing().build(), { version: "R2018" })).at(-1), [0, "EOF"]); }); test("toDXF rejects unknown versions", () => { @@ -123,13 +118,6 @@ test("toDXF rejects unknown versions", () => { assert.throws(() => toDXF(sample(), { version: "R14" }), /Unsupported DXF version/); }); -test("text is escaped for each DXF version", () => { - const b = createDrawing({ dxf: "R12" }).text([0, 0], "Ø 25 – café x^2"); - // R12 predates Unicode DXF. The leading CAD app discards a drawing with a bare caret in either version. - assert.match(toDXF(b.build()), /\r\n\\U\+00D8 25 \\U\+2013 caf\\U\+00E9 x\^ 2\r\n/); - assert.match(toDXF(b.build(), { version: "R2018" }), /\r\nØ 25 – café x\^ 2\r\n/); -}); - test("toDXF writes the version the drawing was created for, R2018 unless it names R12", () => { const d = createDrawing({ dxf: "R12" }).build(); assert.match(toDXF(d), /AC1009/); @@ -138,12 +126,18 @@ test("toDXF writes the version the drawing was created for, R2018 unless it name }); test("an R2018 drawing has $XEDIT 0, and an R12 drawing does not state it", () => { - const dxf = (version: "R12" | "R2018"): string => - toDXF(createDrawing({ units: "ft", dxf: version }).build()); + const dxf = (version: "R12" | "R2018"): string => toDXF(createDrawing({ dxf: version }).build()); assert.match(dxf("R2018"), /\r\n9\r\n\$XEDIT\r\n290\r\n0\r\n/); assert.doesNotMatch(dxf("R12"), /XEDIT/); }); +test("text is escaped for each DXF version", () => { + const b = createDrawing({ dxf: "R12" }).text([0, 0], "Ø 25 – café x^2"); + // R12 predates Unicode DXF. The leading CAD app discards a drawing with a bare caret in either version. + assert.match(toDXF(b.build()), /\r\n\\U\+00D8 25 \\U\+2013 caf\\U\+00E9 x\^ 2\r\n/); + assert.match(toDXF(b.build(), { version: "R2018" }), /\r\nØ 25 – café x\^ 2\r\n/); +}); + test("text that looks like a DXF escape is written so the leading CAD app keeps it", () => { /** The value the leading CAD app is given for a text, which is group 1 of the TEXT record. */ const value = (text: string, version: "R12" | "R2018") => { diff --git a/test/layouts.test.ts b/test/layouts.test.ts index 14ad911..c6d7cc8 100644 --- a/test/layouts.test.ts +++ b/test/layouts.test.ts @@ -19,6 +19,7 @@ import { } from "../src/index.ts"; import { layoutNameKey } from "../src/layers.ts"; import { findLayout } from "../src/layouts.ts"; +import { pairs, records } from "./dxf-groups.ts"; /** A plan in feet with one sheet: a border and a note on the paper, and a view at 1" = 10'. */ function sheet(): Drawing { @@ -37,23 +38,6 @@ function sheet(): Drawing { return d.build(); } -function pairs(dxf: string): [number, string][] { - const lines = dxf.split("\r\n"); - const out: [number, string][] = []; - for (let i = 0; i + 1 < lines.length; i += 2) out.push([Number(lines[i]), lines[i + 1]!]); - return out; -} - -/** The records of a DXF: each from one group 0 to the next. */ -function records(dxf: string): [number, string][][] { - const out: [number, string][][] = []; - for (const pair of pairs(dxf)) { - if (pair[0] === 0) out.push([]); - out.at(-1)?.push(pair); - } - return out; -} - test("layout() puts what is drawn inside it on a sheet, and the drawing round-trips as JSON", () => { const drawing = sheet(); assert.equal(drawing.entities.length, 1); diff --git a/test/paragraphs.test.ts b/test/paragraphs.test.ts index c1ffb17..5c8a55c 100644 --- a/test/paragraphs.test.ts +++ b/test/paragraphs.test.ts @@ -1,7 +1,6 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { test } from "node:test"; -import { Script } from "node:vm"; import { bold, createDrawing, @@ -35,14 +34,7 @@ import { } from "../src/index.ts"; import { paragraphMeasurer } from "../src/paragraphs.ts"; import { readProblems } from "./read-agreement.ts"; -import { timeLimit } from "./time-limit.ts"; - -const running = new Script("running()"); -/** What `fn` gives, stopped after `ms`, so a run that never ends fails. */ -const within = (ms: number, fn: () => T): T => { - Object.assign(globalThis, { running: fn }); - return running.runInThisContext({ timeout: timeLimit(ms) }) as T; -}; +import { within } from "./time-limit.ts"; /** What a value draws, a piece at a time: characters, `[top, divider, bottom]` and `|` for a break. */ const drawn = (value: string) => diff --git a/test/points.test.ts b/test/points.test.ts index 626a30a..ffaf612 100644 --- a/test/points.test.ts +++ b/test/points.test.ts @@ -13,17 +13,7 @@ import { import { extents } from "../src/extents.ts"; import { readProblems } from "./read-agreement.ts"; -/** The groups of the `n`th record of `type` in a DXF from its subclass on, as `code=value`. */ -function point(dxf: string, n = 0): string[] { - const lines = dxf.split("\r\n"); - let at = -1; - for (let k = 0; k <= n; k++) - at = lines.findIndex((line, i) => i > at && line === "POINT" && lines[i - 1]!.trim() === "0"); - const out: string[] = []; - for (let i = at + 1; i + 1 < lines.length && lines[i]!.trim() !== "0"; i += 2) - out.push(`${lines[i]!.trim()}=${lines[i + 1]}`); - return out.slice(out.indexOf("100=AcDbPoint") + 1); -} +import { recordFields } from "./dxf-groups.ts"; const header = (dxf: string, name: string): string | undefined => { const lines = dxf.split("\r\n"); @@ -52,9 +42,9 @@ test("toDXF writes a point and the point style as the leading CAD app saves them d.point([1, 2]); d.point([3, 4], { rotation: 30 }); const dxf = toDXF(d.build()); - assert.deepEqual(point(dxf), ["10=1", "20=2", "30=0"]); + assert.deepEqual(recordFields(dxf, "POINT", "AcDbPoint"), ["10=1", "20=2", "30=0"]); // The file holds the angle the figure turns clockwise by. - assert.deepEqual(point(dxf, 1), ["10=3", "20=4", "30=0", "50=330"]); + assert.deepEqual(recordFields(dxf, "POINT", "AcDbPoint", 1), ["10=3", "20=4", "30=0", "50=330"]); assert.equal(header(dxf, "$PDMODE"), "35"); assert.equal(header(dxf, "$PDSIZE"), "-10"); assert.equal(header(toDXF(createDrawing().build()), "$PDMODE"), undefined); diff --git a/test/read-fuzz.test.ts b/test/read-fuzz.test.ts index aa4c467..b32f37e 100644 --- a/test/read-fuzz.test.ts +++ b/test/read-fuzz.test.ts @@ -1,9 +1,8 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { Script } from "node:vm"; import { READ_LIMITS, readDXFWithin } from "../src/read/dxf.ts"; import { fuzz, seedFiles } from "./read-fuzz.ts"; -import { timeLimit } from "./time-limit.ts"; +import { within } from "./time-limit.ts"; test("readDXF gives a sound read or a ReadError for each bent file, within its time", async () => { const files = seedFiles(); @@ -16,8 +15,6 @@ test("readDXF gives a sound read or a ReadError for each bent file, within its t } }); -const running = new Script("running()"); - test("readDXF stays linear in names longer than a DXF holds", async () => { // Many names of one length past 16,383 characters, which V8 hashes by their length alone. const long = (i: number): string => "N".repeat(17_000) + String(i).padStart(5, "0"); @@ -31,12 +28,7 @@ test("readDXF stays linear in names longer than a DXF holds", async () => { lines.push(" 0", "SEQEND"); lines.push(" 0", "ENDSEC", " 0", "EOF", ""); const bytes = new TextEncoder().encode(lines.join("\n")); - Object.assign(globalThis, { - running: () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS), - }); - const read = await (running.runInThisContext({ timeout: timeLimit(5_000) }) as ReturnType< - typeof readDXFWithin - >); + const read = await within(5_000, () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS)); assert.deepEqual(JSON.parse(JSON.stringify(read.unread.malformed)), { "LINE on a layer longer than 2049 characters": 1500, "ATTRIB with a tag longer than 2049 characters": 1000, @@ -64,12 +56,7 @@ test("readDXF stays linear in long values where a dictionary holds a handle", as } lines.push(" 0", "ENDSEC", " 0", "EOF", ""); const bytes = new TextEncoder().encode(lines.join("\n")); - Object.assign(globalThis, { - running: () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS), - }); - const read = await (running.runInThisContext({ timeout: timeLimit(4_000) }) as ReturnType< - typeof readDXFWithin - >); + const read = await within(4_000, () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS)); assert.equal(read.model.entities!.length, 2000); assert.deepEqual(read.fields, []); }); @@ -89,11 +76,6 @@ test("readDXF reads a header's value once, however many entities follow", async for (let i = 0; i < 50_000; i++) lines.push(" 0", "LINE", " 8", "0", " 10", "0", " 20", "0"); lines.push(" 0", "ENDSEC", " 0", "EOF", ""); const bytes = new TextEncoder().encode(lines.join("\n")); - Object.assign(globalThis, { - running: () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS), - }); - const read = await (running.runInThisContext({ timeout: timeLimit(2_000) }) as ReturnType< - typeof readDXFWithin - >); + const read = await within(2_000, () => readDXFWithin(bytes, { geometry: true }, READ_LIMITS)); assert.equal(read.model.entities!.length, 50_000); }); diff --git a/test/shape-sweep.ts b/test/shape-sweep.ts index e99c59b..f918140 100644 --- a/test/shape-sweep.ts +++ b/test/shape-sweep.ts @@ -783,12 +783,16 @@ export const r12: Drawing = { export type Path = readonly (string | number)[]; -/** Every path to a value in `value`, at every depth. */ -function paths(value: unknown, at: Path = []): Path[] { - if (typeof value !== "object" || value === null) return []; +/** + * Visit each field once. structuredClone preserves shared objects, so changing a field + * through any path to its parent produces the same mutated drawing. + */ +function paths(value: unknown, at: Path = [], seen = new WeakSet()): Path[] { + if (typeof value !== "object" || value === null || seen.has(value)) return []; + seen.add(value); return Object.keys(value).flatMap((key) => { const step = [...at, Array.isArray(value) ? Number(key) : key]; - return [step, ...paths((value as Record)[key], step)]; + return [step, ...paths((value as Record)[key], step, seen)]; }); } @@ -965,8 +969,10 @@ export function sweep(file: string): void { for (const { drawing, path, value, count } of cases()) { if (count % SHARES !== share - 1) continue; const found = failure(replaced(drawing, path, value)); - const shown = inspect(value, { depth: 0, breakLength: Infinity }); - if (found) failures.push(`${drawing.dxf} ${path.join(".")} = ${shown}: ${found}`); + if (found) { + const shown = inspect(value, { depth: 0, breakLength: Infinity }); + failures.push(`${drawing.dxf} ${path.join(".")} = ${shown}: ${found}`); + } } assert.deepEqual(failures, []); }); diff --git a/test/standard-lint.test.ts b/test/standard-lint.test.ts index 0397266..1644e96 100644 --- a/test/standard-lint.test.ts +++ b/test/standard-lint.test.ts @@ -1,6 +1,5 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { Script } from "node:vm"; import sheet, { sitePlan, standard } from "../examples/site-plan.ts"; import { BUILT_IN_STANDARD, @@ -20,7 +19,7 @@ import { type Text, } from "../src/index.ts"; import { lintStandard } from "../src/standard/lint.ts"; -import { timeLimit } from "./time-limit.ts"; +import { within } from "./time-limit.ts"; const layout = sheet.layouts![0]!; const titleBlock = layout.entities[0] as Insert; @@ -34,13 +33,8 @@ const withSheet = (change: Partial): Drawing => ({ }); const only = (found: readonly Diagnostic[], rule: string) => found.filter((d) => d.rule === rule); -const linting = new Script("linting()"); -const checking = new Script("checking()"); -/** The rules `lint` reports with `options`, stopped after `ms`, so a run that never ends fails. */ -const within = (ms: number, drawing: unknown, options: LintOptions = { standard }): string[] => { - Object.assign(globalThis, { linting: () => rules(drawing as Drawing, options) }); - return linting.runInThisContext({ timeout: timeLimit(ms) }) as string[]; -}; +const rulesWithin = (ms: number, drawing: unknown, options: LintOptions = { standard }): string[] => + within(ms, () => rules(drawing as Drawing, options)); test("the example sheet breaks no rule of its standard at either scale, nor from JSON", () => { for (const scale of ["1in-10ft", "1in-20ft"] as const) { @@ -357,7 +351,7 @@ test("a title block is the standard's when its block, text styles and linetypes ...sheet, blocks: sheet.blocks!.map((b) => (b.name === "TITLE BLOCK" ? { ...b, ...change } : b)), }; - assert.ok(within(1000, changed).includes("title-block-differs-from-standard")); + assert.ok(rulesWithin(1000, changed).includes("title-block-differs-from-standard")); } }); @@ -519,7 +513,7 @@ test("the walk of an insert enters what can draw a text, and pays for each item ...withSheet({ entities: [...layout.entities, lines.top, twice] }), blocks: lines.blocks, }; - assert.deepEqual(within(3000, sheetTree), ["height-off-role"]); + assert.deepEqual(rulesWithin(3000, sheetTree), ["height-off-role"]); // No layout, whose viewports have the other rules walk the inserts of model space. const long = "A".repeat(10_000); const text = (value: string): Entity => ({ @@ -532,7 +526,7 @@ test("the walk of an insert enters what can draw a text, and pays for each item style: "NOTE", }); for (const { blocks, top } of [tree(text(long)), tree(text("A"), long, `L-${long}`)]) { - const found = within(3000, { ...sheet, entities: [top], blocks, layouts: [] }); + const found = rulesWithin(3000, { ...sheet, entities: [top], blocks, layouts: [] }); assert.equal(found.at(-1), "standard-check-capped"); } }); @@ -550,10 +544,12 @@ test("lint stops at the first empty slot of a list, as the other rules do", () = withSheet({ entities: slots() }), withSheet({ viewports: slots() }), ]) { - assert.ok(within(1000, drawing).length > 0); + assert.ok(rulesWithin(1000, drawing).length > 0); } const data = JSON.parse(JSON.stringify(standard)) as Standard; - assert.deepEqual(within(1000, sheet, { standard: { ...data, chain: slots() } }), ["standard"]); + assert.deepEqual(rulesWithin(1000, sheet, { standard: { ...data, chain: slots() } }), [ + "standard", + ]); }); /** Numbers from 0 up to 1, the same from one seed on every run. */ @@ -757,12 +753,10 @@ test("the checks of a standard stay bounded on any data, and never throw", () => const discipline = pick([undefined, undefined, "C", long, 5]); const out: Diagnostic[] = []; - Object.assign(globalThis, { - checking: () => - lintStandard(checked as unknown as Drawing, given, discipline, undefined, out, 20_000), - }); try { - checking.runInThisContext({ timeout: timeLimit(1000) }); + within(1000, () => + lintStandard(checked as unknown as Drawing, given, discipline, undefined, out, 20_000), + ); } catch (thrown) { assert.fail(`case ${n}: ${String((thrown as Error)?.message ?? thrown)}`); } diff --git a/test/tables.test.ts b/test/tables.test.ts index 1d0d07a..95064f8 100644 --- a/test/tables.test.ts +++ b/test/tables.test.ts @@ -2,7 +2,6 @@ // smallest drawing that shows it. import assert from "node:assert/strict"; import { test } from "node:test"; -import { Script } from "node:vm"; import { createDrawing, inspectText, @@ -16,14 +15,8 @@ import { referencedByKey } from "../src/blocks.ts"; import { extents } from "../src/extents.ts"; import { TABLE_COLOR } from "../src/rules.ts"; import { tableCost, tableRepeats } from "../src/tables.ts"; -import { timeLimit } from "./time-limit.ts"; +import { within } from "./time-limit.ts"; -const running = new Script("running()"); -/** What `fn` gives, stopped after `ms`, so a run that never ends fails. */ -const within = (ms: number, fn: () => T): T => { - Object.assign(globalThis, { running: fn }); - return running.runInThisContext({ timeout: timeLimit(ms) }) as T; -}; const boxOf = (d: Drawing, xrefs?: Parameters[1]) => extents( d.entities, diff --git a/test/time-limit.ts b/test/time-limit.ts index 276f742..42b32e0 100644 --- a/test/time-limit.ts +++ b/test/time-limit.ts @@ -1,3 +1,5 @@ +import { Script } from "node:vm"; + /** * A vm time limit of `ms`, times `TSDRAFT_TIME_LIMIT_SCALE` where a slow machine sets it. CI and * the Release workflow run on hosted runners, which run every test file at once on a few cores, @@ -8,3 +10,11 @@ export function timeLimit(ms: number): number { const scale = Number(process.env.TSDRAFT_TIME_LIMIT_SCALE ?? 1); return Number.isFinite(scale) && scale >= 1 ? ms * scale : ms; } + +const running = new Script("running()"); + +/** Run a callback with the test's scaled VM timeout. */ +export function within(ms: number, fn: () => T): T { + Object.assign(globalThis, { running: fn }); + return running.runInThisContext({ timeout: timeLimit(ms) }) as T; +} From 8b16d83a87d3b8c9fb6ef200cb4221d9a45df00a Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Sun, 22 Nov 2026 02:37:04 -0500 Subject: [PATCH 35/35] Speed up drawing previews, exports and DXF reads Rendering the site-plan example with a warm compiler cache took 297 ms, down from 361 ms on the benchmark machine. The `render` command loads the PDF plotter only when it plots. DXF, DWG and SVG export spend less time rounding coordinates, and the DXF reader decodes header bytes faster. Run `pnpm bench:io` from the library source checkout to measure the permit set. Co-authored-by: Claude Opus 5.5 --- cli/scripts/bench.ts | 1 + cli/src/cli.ts | 8 ++++++-- package.json | 1 + scripts/bench-io.ts | 23 +++++++++++++++++++++++ src/format.ts | 8 ++++++++ src/read/groups.ts | 2 +- test/format.test.ts | 21 +++++++++++++++++++++ 7 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 scripts/bench-io.ts diff --git a/cli/scripts/bench.ts b/cli/scripts/bench.ts index 6bd5cc2..76eb1eb 100644 --- a/cli/scripts/bench.ts +++ b/cli/scripts/bench.ts @@ -44,6 +44,7 @@ export default d.build(); // It is copied with its helpers, importing the library by name as the other two do. const sheet = `${dir}/site-plan.ts`; mkdirSync(`${dir}/lib`, { recursive: true }); +copyFileSync(`${root}../examples/vicinity-map.png`, `${dir}/vicinity-map.png`); for (const file of ["site-plan.ts", "lib/drafting.ts"]) { const source = readFileSync(`${root}../examples/${file}`, "utf8"); writeFileSync(`${dir}/${file}`, source.replace(/"(\.\.\/)+src\/index\.ts"/, '"tsdraft"')); diff --git a/cli/src/cli.ts b/cli/src/cli.ts index 2aa7fef..ba8073c 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -7,7 +7,6 @@ import { basename, extname, join, resolve } from "node:path"; import { parseArgs } from "node:util"; import { Builder, projectRoot, round, toState } from "./build.ts"; import { faces, pdfFonts, pngFonts } from "./fonts.ts"; -import { plot } from "./pdf.ts"; import { pngUnavailable, RendererCrashed, startRenderer, toPNG } from "./png.ts"; import type { BuildError, BuildState, LayoutOutput, ViewOutput } from "./state.ts"; @@ -144,7 +143,11 @@ if (command === "dev") { drawNoPlot: values["draw-no-plot"] === true, view: view && { box: view, ...(values.layout === undefined ? {} : { layout: values.layout }) }, }); - // The renderer's process starts while the drawing is built. + // The plotter loads only for --pdf, and before anything is built or written, as a static + // import would: a plotter that fails to load stops the command first. + const pdf = values.pdf ? await import("./pdf.ts") : undefined; + // The renderer's process starts while the drawing is built. Its modules load before the + // build starts, so their load time never counts against the drawing's --timeout. startRenderer(); let pngMs: number | undefined; const building = builder.build(file, projectRoot(file)); @@ -252,6 +255,7 @@ if (command === "dev") { } // Each sheet, then the set: a page for each sheet, in the order of the layouts. if (values.pdf && sheets.length > 0) { + const { plot } = pdf!; const omitted = outcome.drawing?.omitted?.length ?? 0; if (omitted > 0) { outputs.pdfError = diff --git a/package.json b/package.json index f2f3ca9..3cf1d2f 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "example": "node examples/site-plan.ts && node examples/outdoor-kitchen.ts && node examples/plan-set/set.ts", "readme:drawing": "node scripts/readme-drawing.ts", "bench": "pnpm build:lib && node cli/scripts/bench.ts", + "bench:io": "node scripts/bench-io.ts", "standard:files": "node scripts/standard-files.ts", "verify": "pnpm fmt:check && pnpm lint && pnpm check && pnpm test && pnpm test:package" }, diff --git a/scripts/bench-io.ts b/scripts/bench-io.ts new file mode 100644 index 0000000..88e20db --- /dev/null +++ b/scripts/bench-io.ts @@ -0,0 +1,23 @@ +// Warm library calls on the permit set. Run with pnpm bench:io. +import drawing, { xrefs } from "../examples/plan-set/set.ts"; +import { readDXF, toDXF, toSVG } from "../src/index.ts"; + +async function measure(name: string, run: () => unknown): Promise { + await run(); + const times: number[] = []; + for (let i = 0; i < 5; i++) { + const start = performance.now(); + await run(); + times.push(performance.now() - start); + } + times.sort((a, b) => a - b); + console.log(`${name}: ${times[2]!.toFixed(1)} ms (median of 5)`); +} + +const dxf = toDXF(drawing); +await measure("Write DXF", () => toDXF(drawing)); +await measure("Read DXF with geometry", () => readDXF(dxf, { geometry: true })); +await measure("Draw model space and all sheets as SVG", () => { + toSVG(drawing, { xrefs }); + for (const sheet of drawing.layouts ?? []) toSVG(drawing, { xrefs, layout: sheet.name }); +}); diff --git a/src/format.ts b/src/format.ts index 840e49a..385261c 100644 --- a/src/format.ts +++ b/src/format.ts @@ -1,11 +1,19 @@ /** The number of decimals the writers keep. */ const DECIMALS = 6; +const SCALE = 10 ** DECIMALS; /** * A number as the writers print it: rounded to 6 decimals. Two values that are * equal here are the same number in the file, whatever they were in the drawing. */ export function written(value: number): number { + if (typeof value === "number" && Math.abs(value) < 2 ** 52 / SCALE) { + const scaled = value * SCALE; + const nearest = Math.round(scaled); + // Every half-integer in this range is representable. Multiplication can land on a + // half from either side, but cannot cross one, so leave those ties to toFixed. + if (Math.abs(scaled - nearest) !== 0.5) return nearest === 0 ? 0 : nearest / SCALE; + } const rounded = Number(value.toFixed(DECIMALS)); return Object.is(rounded, -0) ? 0 : rounded; } diff --git a/src/read/groups.ts b/src/read/groups.ts index 6c81db4..f4f6da6 100644 --- a/src/read/groups.ts +++ b/src/read/groups.ts @@ -216,7 +216,7 @@ export class GroupReader { function latin1(bytes: Uint8Array): string { let text = ""; for (let i = 0; i < bytes.length; i += 8192) { - text += String.fromCharCode(...bytes.subarray(i, i + 8192)); + text += Reflect.apply(String.fromCharCode, undefined, bytes.subarray(i, i + 8192)); } return text; } diff --git a/test/format.test.ts b/test/format.test.ts index 64c894f..5a2efd0 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { callerInStack, parseStack } from "../src/callsite.ts"; +import { written } from "../src/format.ts"; import { createDrawing, DASHED, @@ -14,6 +15,26 @@ import { type Drawing, } from "../src/index.ts"; +test("coordinates round to six decimal places on both sides of a half-millionth", () => { + // 1.2345678 is rounded by arithmetic, not as a tie. 6846209353.3203125 and 22673844301.198742 + // are past 2 ** 52 / 1e6, where scaling stops being exact, and must not take the fast path. + for (const value of [ + 0, + 0.0000005, + 0.0000025, + 1 / 128, + 1.2345678, + 4_000_000_000.0000005, + 6846209353.3203125, + 22673844301.198742, + 1e20, + ]) { + for (const signed of [value, -value]) { + assert.equal(written(signed), Number(signed.toFixed(6)) || 0); + } + } +}); + function sample(): Drawing { const d = createDrawing({ units: "ft", linetypeScale: 2 }); d.layer("A-WALL", { color: 1, linetype: DASHED, lineweight: 0.5, locked: true }, () => {