Shipping zero-backend browser CAD and puzzle studios exposes two deceptively hard engineering problems the moment real users export printable files or ask why a logical solver made a deduction:
-
Client-Side PDF Generation Breaks on Bilingual Titles & 1:1 Physical Scale: Relying on
window.print()hangs headless Chromium / AI browser agents on modal OS dialogs, drops background cell shading unless users toggle hidden print settings, and lets printer "Fit to Printable Area" silently shrink1:1woodworking templates to94%. Moving to a pure client-side%PDF-1.4byte serializer fixes exact72 pt/ingeometry—right up until someone enters a bilingual or CJK header like数织复测 Portrait 20. Standard Type1/Helveticastrips non-ASCII bytes; unembedded CID fonts render blank boxes inside minimal LinuxPoppler(pdftoppm) containers lackingfonts-noto-cjk; and bundling a14 MBCJK.ttfwrecks Core Web Vitals. -
Black-Box Backtracking Fails Mid-Game Logic Players & Photo Grid Generators: Restarting a Nonogram solver from an empty board ignores marks a player has already placed halfway through a
20x20grid, and returning a raw backtracked matrix when single-line overlap stalls offers zero human-verifiable explanation. Meanwhile, naive image thresholding routinely exports broken multi-solution2x2switching components or unanchored fretwork islands that fall straight through a scroll-saw table.
Here is how we solved both problems in zero-dependency TypeScript / ES Modules, with full reference implementations published under MIT in kaiyilu/grid-and-fretwork-math.
Part 1: Zero-Font-Payload Bilingual Vector PDFs (4x Scanlines + 3 Tr /ToUnicode)
When generating printable puzzle booklets (Printable Nonogram Puzzles) or calibrated 1:1 multi-sheet woodworking templates (Scroll Saw Pattern Generator), every PDF must satisfy three simultaneous invariants with 0 kB of embedded font files:
-
Deterministic
72 pt/inGeometry:US Letter(612 x 792 pt) andISO A4(595.28 x 841.89 pt) coordinates computed directly in user space without browser print-margin scaling. -
100% Font-Independent Visual Rendering: CJK, accented Latin, and symbols must render crisply even in stripped-down Linux
pdftoppm/Ghostscriptcontainers with zero system CJK fonts installed. -
100% Verbatim Text Extraction: Running
pdftotextorPyMuPDF(page.get_text()) must extract exact Unicode strings ("数织复测 Portrait 20") rather than outlined paths alone.
Layer A: 4x Offscreen Canvas Supersampling & 2D Scanline Coalescing
For pure ASCII text (row/column numeric clues, page badges), standard PDF Type1 /Helvetica and /Courier-Bold (0.6 * fontSize exact advance width) emit ultra-compact (text) Tj operators. Whenever a string contains non-ASCII Unicode (/[^\x20-\x7E]/), we rasterize that single text line onto an offscreen HTML5 <canvas> at 4x supersampling (1 px = 0.25 pt) using the host OS CJK font stack.
Emitting one PDF rectangle per dark pixel would bloat content streams. Instead, mergeBinaryInkScanlines performs a two-pass horizontal + vertical run-length coalescing pass:
-
Horizontal Pass: Along each scanline
py, merge contiguous ink pixels (R < 172) into half-open spans[x0, x1). -
Vertical Pass: Maintain an
activeRunsmap keyed by"x0,x1". Whenever rowpyproduces the exact same[x0, x1)span as an active run ending atpy, extendyEnd = py + 1in place instead of starting a new rectangle.
export function mergeBinaryInkScanlines(inkMask, width, height, scale = 4) {
let rawInkPixelCount = 0;
let horizontalRunCount = 0;
const activeRuns = new Map();
const finishedRuns = [];
for (let py = 0; py < height; py++) {
const rowOff = py * width;
const rowRuns = [];
let x = 0;
while (x < width) {
if (inkMask[rowOff + x]) {
const start = x;
x++;
while (x < width && inkMask[rowOff + x]) x++;
rawInkPixelCount += x - start;
rowRuns.push({ x0: start, x1: x });
} else {
x++;
}
}
horizontalRunCount += rowRuns.length;
const nextActive = new Map();
for (const run of rowRuns) {
const key = `${run.x0},${run.x1}`;
const prev = activeRuns.get(key);
if (prev && prev.yEnd === py) {
prev.yEnd = py + 1;
nextActive.set(key, prev);
activeRuns.delete(key);
} else {
nextActive.set(key, { x0: run.x0, x1: run.x1, yStart: py, yEnd: py + 1 });
}
}
for (const leftover of activeRuns.values()) finishedRuns.push(leftover);
activeRuns.clear();
for (const [k, v] of nextActive.entries()) activeRuns.set(k, v);
}
for (const leftover of activeRuns.values()) finishedRuns.push(leftover);
finishedRuns.sort((a, b) => a.yStart - b.yStart || a.x0 - b.x0);
const fmt = (n) => Number(n.toFixed(4)).toString();
const rects = finishedRuns.map((r) => ({
x: Number((r.x0 / scale).toFixed(4)),
yTop: Number((r.yStart / scale).toFixed(4)),
yPdf: Number(((height - r.yEnd) / scale).toFixed(4)),
w: Number(((r.x1 - r.x0) / scale).toFixed(4)),
h: Number(((r.yEnd - r.yStart) / scale).toFixed(4)),
}));
return {
rawInkPixelCount,
horizontalRunCount,
mergedRectCount: rects.length,
pdfPathOps: rects.length
? `${rects.map((r) => `${fmt(r.x)} ${fmt(r.yPdf)} ${fmt(r.w)} ${fmt(r.h)} re`).join(" ")} f`
: "",
rects,
};
}
On CJK strokes with long horizontal and vertical stems (such as 十, 目, 口, or 数织), 2D scanline merging collapses 32+ supersampled pixels of a T-stroke into 2 vector re primitives (0 1 2 0.5 re 0.5 0 1 1 re f) resolved at 0.25 pt (1/288"), ending with a single non-zero fill (f).
Layer B: Invisible (3 Tr) Type0 /Identity-H Font + /ToUnicode CMap
Vector rectangles render everywhere, but on their own they are invisible to Ctrl+F, screen readers, and PyMuPDF. Right underneath the vector glyph path, we emit an invisible text operator using PDF Text Rendering Mode 3 (3 Tr = neither fill nor stroke):
q BT 3 Tr /F4 13.00 Tf 36.00 747.00 Td <0001000200030004> Tj ET Q
Font /F4 is a lightweight Type0 composite font with /Encoding /Identity-H, a minimal CIDFontType2 descendant dictionary (/DW 600, zero embedded FontFile2 bytes), and a /ToUnicode stream generated dynamically from the unique Unicode scalar values present in the document:
export function encodePdfToUnicodeCMap(codePoints) {
const rawValues =
typeof codePoints === "string"
? Array.from(codePoints, (ch) => ch.codePointAt(0) ?? 0x20)
: Array.from(codePoints ?? []);
const cidByCodePoint = new Map();
const entries = [];
for (const cp of rawValues) {
if (cidByCodePoint.has(cp)) continue;
const cid = entries.length + 1;
const cidHex = cid.toString(16).toUpperCase().padStart(4, "0");
let utf16BeHex;
if (cp <= 0xffff) {
utf16BeHex = cp.toString(16).toUpperCase().padStart(4, "0");
} else {
// UTF-16BE surrogate pair for astral code points (U+10000..U+10FFFF)
const offset = cp - 0x10000;
const hi = (0xd800 + (offset >> 10)).toString(16).toUpperCase().padStart(4, "0");
const lo = (0xdc00 + (offset & 0x3ff)).toString(16).toUpperCase().padStart(4, "0");
utf16BeHex = `${hi}${lo}`;
}
cidByCodePoint.set(cp, cid);
entries.push({ cid, cidHex, codePoint: cp, utf16BeHex });
}
const lines = [
"/CIDInit /ProcSet findresource begin",
"12 dict begin",
"begincmap",
"/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def",
"/CMapName /Adobe-Identity-UCS def",
"/CMapType 2 def",
"1 begincodespacerange",
"<0000> <FFFF>",
"endcodespacerange",
];
// Adobe CMap spec requires <= 100 mappings per beginbfchar block
for (let i = 0; i < entries.length; i += 100) {
const chunk = entries.slice(i, i + 100);
lines.push(`${chunk.length} beginbfchar`);
for (const item of chunk) {
lines.push(`<${item.cidHex}> <${item.utf16BeHex}>`);
}
lines.push("endbfchar");
}
lines.push("endcmap", "CMapName currentdict /CMap defineresource pop", "end", "end");
return { cmapStream: lines.join("\n"), entries, cidByCodePoint };
}
Two subtle PDF 1.4 compliance rules matter here:
-
Chunk
beginbfcharat<= 100entries: Strict Poppler and Acrobat parsers rejectbeginbfcharblocks larger than 100 lines. -
Encode supplementary planes (
> U+FFFF) as 8-hex UTF-16BE surrogate pairs: e.g.,🧩(U+1F9E9) encodes as<D83EDDE9>, not<01F9E9>.
Calibrated 1:1 Multi-Sheet Tiling (US Letter & ISO A4)
For physical woodworking plaques larger than a single sheet (for example, a 14" x 18" fretwork portrait), home laser and inkjet printers clip anything within ~0.4"–0.5" of the paper edge. computeTrueScalePrintTiles(widthInches, heightInches, paperFormat) partitions the 72 pt/in artwork into margin-safe 1:1 windows—7.5" x 9.6" (540 x 691.2 pt) on US Letter and 7.25" x 10.4" (184 x 264 mm / 522 x 748.8 pt) on ISO A4—so registration crop ticks align to the sub-millimeter when taped across R1C1..RmCn sheets.
Part 2: Mid-Game Nonogram Continuation & Cell-by-Cell Reductio ad Absurdum Proofs
In a 31-bit bitmask Nonogram engine (capped at 31 cells per integer word via 0x7fffffff because JavaScript 1 << 31 overflows signed Int32 to -2147483648), single-line dynamic programming intersects all valid placements of run clues R = [r_0, ..., r_{k-1}] in O(k * N^2) time:
forcedFilledMask = fullMask ^ unionOfValidEmptyMasks
forcedEmptyMask = fullMask ^ unionOfValidFillMasks
Seeding Mid-Game Partial Boards (partialGrid)
Interactive players using our Nonogram Solver rarely start from a blank grid—they paste clues and mark the 30–40 cells they have already deduced (1 = filled ■, -1 = crossed ×, 0 = unknown) to see the next logical step.
Seeding (rFill, rEmpty, cFill, cEmpty) bitmasks directly from partialGrid unlocks deductions that are mathematically invisible on a blank grid. For example, on a 5x5 permutation board where every row and column clue is [1], a blank board deduces 0 cells (unresolvedAfterLinePass === 25). Marking a single cell R1C1 = ■ (1) immediately forces 8 orthogonal crosses (R1C2..R1C5 = × and R2C1..R5C1 = ×) in two bitmask queue steps. Similarly, marking R1C2 = × (-1) on a 5x5 row with clue [3] orphans R1C1 (1 < 3), forcing R1C1 = × and R1C3..R1C5 = ■.
Generating Human-Verifiable Lookahead Contradiction Traces
What happens when a puzzle is 100% uniquely solvable (solutionCount === 1), yet every single row and column has zero single-line overlap?
Consider this compact 4x4 benchmark:
-
rowClues:[[2], [2], [2], [1]] -
colClues:[[1, 1], [2], [2], [1]]
On an empty 4x4 board, [2], [1, 1], and [1] each have multiple disjoint placements (unionFill === 0b1111 and unionEmpty === 0b1111), so pure 1D line propagation stalls immediately with all 16 cells unresolved.
Instead of silently running DFS backtracking and dumping the finished answer, proveNonogramLookaheadStep(rowClues, colClues, partialGrid) executes 1-ply trial lookahead (Reductio ad Absurdum) over unresolved cells, selecting the shortest contradiction chain and recording every forced cell along the way:
// Trial assumption on the stalled 4x4 benchmark: Assume R1C1 = × (-1)
const proof = proveNonogramLookaheadStep(
[[2], [2], [2], [1]],
[[1, 1], [2], [2], [1]]
);
Here is the exact trace emitted in proof.subSteps:
-
Trial Hypothesis:
Assume R1C1 = ×(assumedState = -1). -
Step 1 (
Column 1, clue[1, 1]): WithR1C1 = ×, only1placement remains across rows2..4-> forcesR2C1 = ■, R3C1 = ×, R4C1 = ■. -
Step 2 (
Row 2, clue[2]):R2C1 = ■at the left border forcesR2C2 = ■, R2C3 = ×, R2C4 = ×. -
Step 3 (
Row 4, clue[1]):R4C1 = ■satisfies the entire clue -> forcesR4C2 = ×, R4C3 = ×, R4C4 = ×. -
Step 4 (
Column 3, clue[2]): WithR2C3 = ×andR4C3 = ×,Column 3is split into isolated 1-cell pockets (R1C3andR3C3), yieldingvalidConfigurations === 0(Contradiction!).
Because R1C1 = × leads deterministically to validConfigurations === 0 in Column 3, R1C1 is proven to be ■ (+1)—and once R1C1 = ■ is committed, standard 1D line propagation cascades through all remaining 15 cells with zero further branching.
Part 3: Topology Guards Against Ambiguous Grids & Fretwork Dropouts
The same bitmask solver and 2D grid graph algorithms act as pre-export guards in creative generators:
-
Eliminating
2x2Switching Components in Photo Nonograms: Converting a portrait or icon into binary pixels (Clean Silhouette,Sharp Contours, orPortrait Ditherin our Photo-to-Nonogram Generator) frequently introduces2x2checkerboards[[1, 0], [0, 1]]whose row and column clues match[[0, 1], [1, 0]]. CappingsolveNonogramBitmaskatmaxSolutions = 2detectssolutionCount >= 2in under2 msso the generator can flip the highest-ambiguity switching pixel before allowing PDF or URL export. -
4-Connected BFS Dropout Guards for Wood Fretwork: In Scroll Saw Pattern Generator, thresholding a face or welded name plaque creates interior wood islands (eyes, or counters inside
O,A,B) surrounded by cut kerf. Because diagonal pixel touches(x, y) <-> (x+1, y+1)have zero physical wood width under a0.034"#3blade,detectFloatingIslandsruns strict 4-connected Von Neumann BFS from the outer frame, blocking unbridged downloads untilautoBridgeIslandsstamps shortest-Euclidean structural wood tabs across every floating component.
Try the Open-Source Spec & Interactive Tools
All functions covered above—deduceNonogramLine, solveNonogramBitmask, proveNonogramLookaheadStep, encodePdfToUnicodeCMap, mergeBinaryInkScanlines, computeTrueScalePrintTiles, detectFloatingIslands, and autoBridgeIslands—are available in a single zero-dependency ES module (Node.js 18+ & modern browsers):
-
GitHub Repository (
MIT): github.com/kaiyilu/grid-and-fretwork-math (node --testruns 11 unit test suites) - Interactive Browser Verifier: kaiyilu.github.io/grid-and-fretwork-math/
- Production Tools Running This Engine:
Top comments (0)