inkless 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/bin/inkless.js +10 -0
  4. package/console-dist/assets/BlueprintTool-CLWuM21a.js +4226 -0
  5. package/console-dist/assets/index-CIqLZU6s.js +33 -0
  6. package/console-dist/assets/index-Dv7Gg9qm.css +1 -0
  7. package/console-dist/favicon.svg +11 -0
  8. package/console-dist/index.html +18 -0
  9. package/native/linux/rfcomm.py +84 -0
  10. package/native/macos/build/InklessBluetooth.app/Contents/Info.plist +26 -0
  11. package/native/macos/build/InklessBluetooth.app/Contents/MacOS/InklessBluetooth +0 -0
  12. package/native/macos/build/InklessBluetooth.app/Contents/_CodeSignature/CodeResources +115 -0
  13. package/package.json +60 -4
  14. package/skills/inkless/SKILL.md +213 -0
  15. package/src/core/bits.js +143 -0
  16. package/src/core/blueprint/demos.js +119 -0
  17. package/src/core/blueprint/geometry.js +232 -0
  18. package/src/core/blueprint/index.js +100 -0
  19. package/src/core/blueprint/layout.js +210 -0
  20. package/src/core/blueprint/mesh.js +101 -0
  21. package/src/core/blueprint/methods.js +95 -0
  22. package/src/core/blueprint/remesh.js +250 -0
  23. package/src/core/blueprint/slice.js +134 -0
  24. package/src/core/blueprint/unfold.js +185 -0
  25. package/src/core/design/codes.js +39 -0
  26. package/src/core/design/filters.js +109 -0
  27. package/src/core/design/render.js +317 -0
  28. package/src/core/design/schema.js +132 -0
  29. package/src/core/formats/fit.js +46 -0
  30. package/src/core/formats/index.js +210 -0
  31. package/src/core/formats/library.js +341 -0
  32. package/src/core/formats/share.js +65 -0
  33. package/src/core/index.js +15 -0
  34. package/src/core/printers/hp6.js +160 -0
  35. package/src/core/printers/index.js +14 -0
  36. package/src/core/printers/pm290.js +115 -0
  37. package/src/core/session.js +56 -0
  38. package/src/node/artwork.js +33 -0
  39. package/src/node/cli.js +430 -0
  40. package/src/node/console/actions.js +30 -0
  41. package/src/node/console/client.js +68 -0
  42. package/src/node/console/paths.js +8 -0
  43. package/src/node/console/server.js +286 -0
  44. package/src/node/design.js +99 -0
  45. package/src/node/formats.js +39 -0
  46. package/src/node/frames.js +93 -0
  47. package/src/node/index.js +6 -0
  48. package/src/node/kit.js +12 -0
  49. package/src/node/skill.js +44 -0
  50. package/src/node/transports/index.js +21 -0
  51. package/src/node/transports/linux.js +52 -0
  52. package/src/node/transports/macos.js +81 -0
@@ -0,0 +1,134 @@
1
+ // @ts-check
2
+ // Mesh -> flat pieces. A plane cuts every shell, the cuts are joined into
3
+ // regions, and each region becomes a piece. Where two pieces cross they get
4
+ // interlocking slots, like an egg crate.
5
+ import { chain, inside, outline, regions, simplify, spans } from "./geometry.js";
6
+
7
+ /** @typedef {import("./index.js").Part} Part @typedef {import("./index.js").Frame} Frame @typedef {import("./geometry.js").Ring} Ring @typedef {import("./geometry.js").Point} Point */
8
+ /** @typedef {ReturnType<typeof import("./mesh.js").shells>} Shells */
9
+
10
+ const CLEARANCE_MM = 0.2; // slot width = pen line + this
11
+ const OPEN_MM = 1; // slots run this far past the edge so they open cleanly
12
+
13
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
14
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
15
+ const clean = (/** @type {Ring[]} */ rings) => rings.map((r) => simplify(r)).filter((r) => r.length >= 3);
16
+
17
+ /** The plane `axis = offset` (u, v as in Part), or the vertical half plane at `deg` around Z (u: out from the axis). */
18
+ export const axisFrame = (/** @type {"x" | "y" | "z"} */ axis, offset) => /** @type {Frame} */ ({
19
+ x: { origin: [offset, 0, 0], u: [0, 1, 0], v: [0, 0, 1] },
20
+ y: { origin: [0, offset, 0], u: [1, 0, 0], v: [0, 0, 1] },
21
+ z: { origin: [0, 0, offset], u: [1, 0, 0], v: [0, 1, 0] },
22
+ }[axis]);
23
+ export const finFrame = (deg) => {
24
+ const a = (deg * Math.PI) / 180;
25
+ return /** @type {Frame} */ ({ origin: [0, 0, 0], u: [Math.cos(a), Math.sin(a), 0], v: [0, 0, 1] });
26
+ };
27
+
28
+ /** Segments where the frame's plane cuts a triangle soup, in plane coordinates. @param {Float32Array} p @param {Frame} f */
29
+ function cut(p, f) {
30
+ const n = cross(f.u, f.v), d0 = dot(f.origin, n), out = [];
31
+ const at = (i, j, k) => {
32
+ const q = [p[i] + (p[j] - p[i]) * k - f.origin[0], p[i + 1] + (p[j + 1] - p[i + 1]) * k - f.origin[1], p[i + 2] + (p[j + 2] - p[i + 2]) * k - f.origin[2]];
33
+ return [dot(q, f.u), dot(q, f.v)];
34
+ };
35
+ for (let t = 0; t < p.length; t += 9) {
36
+ const d = [0, 3, 6].map((o) => p[t + o] * n[0] + p[t + o + 1] * n[1] + p[t + o + 2] * n[2] - d0), pts = [];
37
+ for (let e = 0; e < 3; e++) {
38
+ const e1 = (e + 1) % 3;
39
+ // A vertex on the plane counts as above it, so every crossing is found once.
40
+ if ((d[e] >= 0) === (d[e1] >= 0)) continue;
41
+ pts.push(at(t + e * 3, t + e1 * 3, d[e] / (d[e] - d[e1])));
42
+ }
43
+ if (pts.length === 2) out.push(pts);
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /** Does the plane pass through the shell's box? */
49
+ function touches(shell, f) {
50
+ const n = cross(f.u, f.v), d0 = dot(f.origin, n);
51
+ let lo = Infinity, hi = -Infinity;
52
+ for (let c = 0; c < 8; c++) {
53
+ const d = dot([0, 1, 2].map((a) => ((c >> a) & 1 ? shell.max[a] : shell.min[a])), n) - d0;
54
+ lo = Math.min(lo, d); hi = Math.max(hi, d);
55
+ }
56
+ return lo <= 0 && hi >= 0;
57
+ }
58
+
59
+ /**
60
+ * The regions where a plane cuts the model, each `[outer, ...holes]`.
61
+ * @param {Shells} shells @param {Frame} frame @param {number} minWidth
62
+ * @param {number} [fromU] keep only the side where u >= fromU (fins)
63
+ */
64
+ export function section(shells, frame, minWidth, fromU) {
65
+ const solid = shells.filter((s) => touches(s, frame)).map((s) => clean(chain(cut(s.positions, frame)))).filter((rings) => rings.length);
66
+ const half = fromU === undefined || !solid.length ? [] : [[[[fromU, -1e4], [1e4, -1e4], [1e4, 1e4], [fromU, 1e4]]]];
67
+ const shapes = [...solid, ...half];
68
+ const rings = shapes.length > 1 ? clean(outline(shapes, (pt) => (!half.length || pt[0] >= fromU) && solid.some((r) => inside(r, pt)))) : shapes.flat();
69
+ return regions(rings, minWidth);
70
+ }
71
+
72
+ /** `count` values spread evenly across [lo, hi], none on the ends. */
73
+ export const planes = (lo, hi, count) => Array.from({ length: count }, (_, i) => lo + ((i + 1) * (hi - lo)) / (count + 1));
74
+
75
+ /**
76
+ * Pieces for a list of planes, numbered in order.
77
+ * @param {Shells} shells @param {Frame[]} frames @param {string} letter @param {(i: number) => string} label
78
+ * @param {number} minWidth @param {number} [fromU]
79
+ * @returns {Part[]}
80
+ */
81
+ export function family(shells, frames, letter, label, minWidth, fromU) {
82
+ const parts = frames.flatMap((frame, i) => section(shells, frame, minWidth, fromU).map((polygons, k, all) => ({
83
+ name: all.length > 1 ? `${label(i)}, piece ${k + 1}` : label(i),
84
+ polygons,
85
+ slots: [],
86
+ frame,
87
+ })));
88
+ return parts.map((part, i) => ({ id: `${letter}${i + 1}`, ...part }));
89
+ }
90
+
91
+ /** Where the line `from + t * dir` (dir of length 1) runs inside the region, as [t0, t1] stretches. */
92
+ function along(polygons, from, dir) {
93
+ const local = polygons.map((ring) => ring.map(([x, y]) => {
94
+ const dx = x - from[0], dy = y - from[1];
95
+ return [dx * dir[0] + dy * dir[1], dy * dir[0] - dx * dir[1]];
96
+ }));
97
+ return spans(local, 1, 0);
98
+ }
99
+
100
+ /**
101
+ * Interlocking slots where pieces `a` and `b` cross. They meet along a line;
102
+ * `a` is slotted from the end where t grows, `b` from the other end, each to
103
+ * the middle of the shared stretch, so `b` slides onto `a` along the line.
104
+ * The line is given in each piece's coordinates: a point at t = 0 and a unit
105
+ * direction. Returns how many joints were cut.
106
+ * @param {Part} a @param {Point} aFrom @param {Point} aDir @param {Part} b @param {Point} bFrom @param {Point} bDir @param {number} penMm
107
+ */
108
+ export function interlock(a, aFrom, aDir, b, bFrom, bDir, penMm) {
109
+ const sa = along(a.polygons, aFrom, aDir), sb = along(b.polygons, bFrom, bDir), w = penMm + CLEARANCE_MM;
110
+ const at = (from, dir, t) => [from[0] + dir[0] * t, from[1] + dir[1] * t];
111
+ let joints = 0;
112
+ for (const [a0, a1] of sa) for (const [b0, b1] of sb) {
113
+ const lo = Math.max(a0, b0), hi = Math.min(a1, b1);
114
+ if (hi - lo < 2 * penMm) continue;
115
+ const mid = (lo + hi) / 2;
116
+ a.slots.push({ from: at(aFrom, aDir, a1), to: at(aFrom, aDir, mid), w });
117
+ b.slots.push({ from: at(bFrom, bDir, b0), to: at(bFrom, bDir, mid), w });
118
+ joints++;
119
+ }
120
+ return joints;
121
+ }
122
+
123
+ /** The piece with its slots cut out. @param {Part} part */
124
+ export function cutSlots(part) {
125
+ if (!part.slots.length) return part.polygons;
126
+ const rects = part.slots.map(({ from, to, w }) => {
127
+ const len = Math.hypot(to[0] - from[0], to[1] - from[1]), d = [(to[0] - from[0]) / len, (to[1] - from[1]) / len];
128
+ const s = [from[0] - d[0] * OPEN_MM, from[1] - d[1] * OPEN_MM], n = [-d[1] * w / 2, d[0] * w / 2];
129
+ return [[[s[0] - n[0], s[1] - n[1]], [to[0] - n[0], to[1] - n[1]], [to[0] + n[0], to[1] + n[1]], [s[0] + n[0], s[1] + n[1]]]];
130
+ });
131
+ const rings = clean(outline([part.polygons, ...rects], (pt) => inside(part.polygons, pt) && !rects.some((r) => inside(r, pt))));
132
+ // A slot can nip off a sliver at a narrow tip; keep the piece itself.
133
+ return regions(rings, 0)[0] ?? part.polygons;
134
+ }
@@ -0,0 +1,185 @@
1
+ // @ts-check
2
+ // Unfold: papercraft nets. The model is rebuilt as one simple closed surface
3
+ // (remesh.js), then its faces are unfolded flat a face at a time, each net
4
+ // growing across its longest edges while it stays free of overlaps and fits
5
+ // on one label. Every edge cut open gets a number on both sides: the pen
6
+ // welds edges with the same number together.
7
+ import { chain, regions } from "./geometry.js";
8
+ import { labelArea } from "./layout.js";
9
+ import { list } from "./methods.js";
10
+ import { remesh, simplify } from "./remesh.js";
11
+
12
+ /** @typedef {import("./methods.js").Input} Input @typedef {import("./methods.js").MethodResult} MethodResult @typedef {import("./geometry.js").Point} Point */
13
+
14
+ const GRID_CELLS = 48; // samples along the largest side before simplifying
15
+ const ROLL_NET_MM = 100; // nets on the roll stay this short
16
+ const FACE_SHARE = 0.12, AUTO_MIN = 60, AUTO_MAX = 300; // automatic face count: each face about this share of a label
17
+ const ANGLES = Array.from({ length: 36 }, (_, i) => (i * Math.PI) / 36);
18
+ const FLAT = Math.cos((2 * Math.PI) / 180); // folds flatter than 2 degrees are not drawn
19
+
20
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
21
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
22
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
23
+ const len = (a) => Math.hypot(...a);
24
+
25
+ /** Do two flat triangles overlap by more than a hair? Separating axes. @param {Point[]} a @param {Point[]} b */
26
+ function overlaps(a, b) {
27
+ for (const tri of [a, b]) for (let i = 0; i < 3; i++) {
28
+ const p = tri[i], q = tri[(i + 1) % 3], nx = q[1] - p[1], ny = p[0] - q[0], l = Math.hypot(nx, ny);
29
+ const proj = (t) => t.map(([x, y]) => (x * nx + y * ny) / l);
30
+ const pa = proj(a), pb = proj(b);
31
+ if (Math.max(...pa) <= Math.min(...pb) + 1e-3 || Math.max(...pb) <= Math.min(...pa) + 1e-3) return false;
32
+ }
33
+ return true;
34
+ }
35
+
36
+ /** Enough faces that a few fit on one label, so big models get more, smaller faces. @param {import("./remesh.js").Indexed} mesh */
37
+ function autoFaces({ verts, faces }, labelMm2) {
38
+ const total = faces.reduce((sum, [a, b, c]) => sum + len(cross(sub(verts[b], verts[a]), sub(verts[c], verts[a]))) / 2, 0);
39
+ return Math.min(AUTO_MAX, Math.max(AUTO_MIN, Math.round(total / (labelMm2 * FACE_SHARE))));
40
+ }
41
+
42
+ /** @param {Input} input @returns {MethodResult} */
43
+ export function unfold({ solids, s }) {
44
+ const [areaW, areaH0] = labelArea(s.label), areaH = s.label === "roll" ? ROLL_NET_MM : areaH0;
45
+ const surface = remesh(solids, GRID_CELLS);
46
+ const { verts, faces } = simplify(surface, s.faces || autoFaces(surface, areaW * areaH));
47
+ const F = faces.length, normal = faces.map((f) => cross(sub(verts[f[1]], verts[f[0]]), sub(verts[f[2]], verts[f[0]])));
48
+ const edgeKey = (a, b) => (a < b ? `${a},${b}` : `${b},${a}`);
49
+ /** @type {Map<string, { f: number, e: number }[]>} the faces on each edge; edge e of face f runs from f[e] to f[e + 1] */
50
+ const sides = new Map();
51
+ faces.forEach((f, fi) => f.forEach((v, e) => {
52
+ const key = edgeKey(v, f[(e + 1) % 3]);
53
+ sides.set(key, [...(sides.get(key) ?? []), { f: fi, e }]);
54
+ }));
55
+ const edgeLength = (f, e) => len(sub(verts[faces[f][(e + 1) % 3]], verts[faces[f][e]]));
56
+
57
+ // Grow nets. flat[f] is face f laid flat, its corners in the face's own order.
58
+ const net = new Int32Array(F).fill(-1), flat = /** @type {Point[][]} */ ([]), joined = new Set();
59
+ const nets = /** @type {number[][]} */ ([]);
60
+ const order = [...faces.keys()].sort((a, b) => len(normal[b]) - len(normal[a]));
61
+ for (const seed of order) {
62
+ if (net[seed] >= 0) continue;
63
+ const id = nets.length, members = [seed];
64
+ nets.push(members);
65
+ net[seed] = id;
66
+ const [a, b, c] = faces[seed].map((v) => verts[v]), ab = sub(b, a), l = len(ab), x = dot(sub(c, a), ab) / l;
67
+ flat[seed] = [[0, 0], [l, 0], [x, len(sub(sub(c, a), ab.map((v) => (v * x) / l)))]];
68
+ // Extents of the net turned to each angle, to know whether it still fits a label.
69
+ const extents = ANGLES.map(() => [Infinity, -Infinity, Infinity, -Infinity]);
70
+ const grow = (ext, pts) => ANGLES.map((t, i) => {
71
+ const e = [...ext[i]], cos = Math.cos(t), sin = Math.sin(t);
72
+ for (const [px, py] of pts) {
73
+ const u = px * cos - py * sin, w = px * sin + py * cos;
74
+ e[0] = Math.min(e[0], u); e[1] = Math.max(e[1], u); e[2] = Math.min(e[2], w); e[3] = Math.max(e[3], w);
75
+ }
76
+ return e;
77
+ });
78
+ let ext = grow(extents, flat[seed]);
79
+ const fits = (e) => e.some(([u0, u1, w0, w1]) => u1 - u0 <= areaW && w1 - w0 <= areaH);
80
+ const open = [0, 1, 2].map((e) => ({ f: seed, e }));
81
+ while (open.length) {
82
+ // Fold across the longest edge first, so the edges left to weld are short.
83
+ open.sort((p, q) => edgeLength(p.f, p.e) - edgeLength(q.f, q.e));
84
+ const { f, e } = /** @type {{ f: number, e: number }} */ (open.pop());
85
+ const across = sides.get(edgeKey(faces[f][e], faces[f][(e + 1) % 3]));
86
+ if (across.length !== 2) continue;
87
+ const { f: g, e: ge } = across[0].f === f ? across[1] : across[0];
88
+ if (net[g] >= 0) continue;
89
+ // Turn g about the shared edge into the plane of the net, on the far side from f.
90
+ const pa = flat[f][e], pb = flat[f][(e + 1) % 3], A = verts[faces[f][e]], B = verts[faces[f][(e + 1) % 3]];
91
+ const third = (ge + 2) % 3, R = verts[faces[g][third]], AB = sub(B, A), l2 = dot(AB, AB);
92
+ const t = dot(sub(R, A), AB) / l2, h = len(sub(sub(R, A), AB.map((v) => v * t)));
93
+ const d = [pb[0] - pa[0], pb[1] - pa[1]], dl = Math.hypot(d[0], d[1]);
94
+ const pr = [pa[0] + d[0] * t + (d[1] / dl) * h, pa[1] + d[1] * t - (d[0] / dl) * h];
95
+ const tri = [];
96
+ tri[ge] = pb; tri[(ge + 1) % 3] = pa; tri[third] = pr;
97
+ const next = grow(ext, [pr]);
98
+ if (!fits(next) || members.some((m) => overlaps(flat[m], tri))) continue;
99
+ flat[g] = tri;
100
+ net[g] = id;
101
+ members.push(g);
102
+ joined.add(edgeKey(faces[f][e], faces[f][(e + 1) % 3]));
103
+ ext = next;
104
+ open.push({ f: g, e: (ge + 1) % 3 }, { f: g, e: third });
105
+ }
106
+ // Turn the net to the angle where its box is smallest and still fits.
107
+ const best = ANGLES.map((angle, i) => ({ angle, e: ext[i] }))
108
+ .sort((p, q) => Number(fits([q.e])) - Number(fits([p.e])) || (p.e[1] - p.e[0]) * (p.e[3] - p.e[2]) - (q.e[1] - q.e[0]) * (q.e[3] - q.e[2]))[0];
109
+ const cos = Math.cos(best.angle), sin = Math.sin(best.angle);
110
+ for (const m of members) flat[m] = flat[m].map(([px, py]) => [px * cos - py * sin, px * sin + py * cos]);
111
+ }
112
+
113
+ // Cut edges: pair the sides of every edge not folded inside a net.
114
+ const cuts = /** @type {{ key: string, a: { f: number, e: number }, b: { f: number, e: number } }[]} */ ([]);
115
+ for (const [key, list2] of sides) if (!joined.has(key)) for (let i = 0; i + 1 < list2.length; i += 2) cuts.push({ key, a: list2[i], b: list2[i + 1] });
116
+
117
+ // Build order: start with the biggest net, then always the net sharing most edges with those placed.
118
+ const placed = [], left = new Set(nets.keys());
119
+ while (left.size) {
120
+ const shared = (n) => cuts.filter((c) => (net[c.a.f] === n && placed.includes(net[c.b.f])) || (net[c.b.f] === n && placed.includes(net[c.a.f]))).length;
121
+ const pick = [...left].sort((p, q) => shared(q) - shared(p) || nets[q].length - nets[p].length)[0];
122
+ placed.push(pick);
123
+ left.delete(pick);
124
+ }
125
+ const rank = new Int32Array(nets.length);
126
+ placed.forEach((n, i) => { rank[n] = i; });
127
+ // Number the edges in build order, so the numbers count up as the model closes.
128
+ const late = (c) => Math.max(rank[net[c.a.f]], rank[net[c.b.f]]);
129
+ cuts.sort((p, q) => late(p) - late(q) || Math.min(rank[net[p.a.f]], rank[net[p.b.f]]) - Math.min(rank[net[q.a.f]], rank[net[q.b.f]]));
130
+ const numberOf = new Map();
131
+ cuts.forEach((c, i) => { numberOf.set(`${c.a.f}:${c.a.e}`, i + 1); numberOf.set(`${c.b.f}:${c.b.e}`, i + 1); });
132
+
133
+ const pieces = placed.map((n, i) => {
134
+ const members = nets[n], id = `N${i + 1}`, folds = [], valleys = [], notes = [], boundary = [];
135
+ for (const f of members) for (let e = 0; e < 3; e++) {
136
+ const p = flat[f][e], q = flat[f][(e + 1) % 3], key = edgeKey(faces[f][e], faces[f][(e + 1) % 3]);
137
+ if (joined.has(key)) {
138
+ // Each fold once: from the face that has it running forwards in the lower face number.
139
+ const other = sides.get(key).find((side) => side.f !== f);
140
+ if (!other || other.f < f) continue;
141
+ const nf = normal[f], ng = normal[other.f];
142
+ if (dot(nf, ng) >= FLAT * len(nf) * len(ng)) continue;
143
+ folds.push([p, q]);
144
+ valleys.push(dot(sub(verts[faces[other.f][(other.e + 2) % 3]], verts[faces[f][e]]), nf) > 0);
145
+ continue;
146
+ }
147
+ boundary.push([p, q]);
148
+ const number = numberOf.get(`${f}:${e}`);
149
+ if (!number) continue;
150
+ // The number sits just inside the face, off the middle of its edge.
151
+ const r = flat[f][(e + 2) % 3], dx = q[0] - p[0], dy = q[1] - p[1], dl = Math.hypot(dx, dy);
152
+ const reach = Math.abs((r[0] - p[0]) * dy - (r[1] - p[1]) * dx) / dl, step = Math.min(1.8, reach * 0.3);
153
+ notes.push({ text: String(number), at: [(p[0] + q[0]) / 2 - (dy / dl) * step, (p[1] + q[1]) / 2 + (dx / dl) * step] });
154
+ }
155
+ const surface = Float32Array.from(members.flatMap((f) => faces[f].flatMap((v) => verts[v])));
156
+ const part = {
157
+ id, name: `net ${i + 1}`, polygons: regions(chain(boundary), 0).flat(), slots: [],
158
+ surface, faces: members.map((f) => flat[f]), folds, valleys, notes,
159
+ };
160
+ return { part, hint: `${members.length} face${members.length > 1 ? "s" : ""}`, cross: false };
161
+ });
162
+
163
+ // Steps: fold each net, weld its own edges, then join it to the nets before it.
164
+ const steps = [{ text: "Fold along the thin lines with the traced side out: solid lines make a ridge, dashed lines a valley.", parts: [] }];
165
+ /** Edge numbers as words, runs shortened: "1 to 4 and 7". */
166
+ const numbers = (cs) => {
167
+ const runs = [];
168
+ for (const n of cs.map((c) => cuts.indexOf(c) + 1).sort((x, y) => x - y)) {
169
+ const last = runs[runs.length - 1];
170
+ if (last && n === last[1] + 1) last[1] = n; else runs.push([n, n]);
171
+ }
172
+ return list(runs.map(([x, y]) => (x === y ? String(x) : `${x} ${y > x + 1 ? "to" : "and"} ${y}`)));
173
+ };
174
+ placed.forEach((n, i) => {
175
+ const id = `N${i + 1}`, own = cuts.filter((c) => net[c.a.f] === n && net[c.b.f] === n);
176
+ const toEarlier = cuts.filter((c) => late(c) === i && !own.includes(c));
177
+ const earlier = [...new Set(toEarlier.map((c) => (rank[net[c.a.f]] === i ? net[c.b.f] : net[c.a.f])))].map((m) => `N${rank[m] + 1}`);
178
+ const parts = [id, ...earlier], plural = (cs) => (cs.length > 1 ? "edges" : "edge");
179
+ const close = own.length ? `close ${id} with ${plural(own)} ${numbers(own)}` : "";
180
+ if (i === 0) steps.push({ text: own.length ? `Fold ${id} and weld ${plural(own)} ${numbers(own)} to the same numbers on it.` : `Fold ${id}.`, parts });
181
+ else if (!toEarlier.length) steps.push({ text: `${id} is a separate part: fold it${close ? `, ${close},` : ""} and set it where the 3D view shows.`, parts });
182
+ else steps.push({ text: `Join ${id} to ${list(earlier)}: weld ${plural(toEarlier)} ${numbers(toEarlier)} to the same numbers${close ? `, then ${close}` : ""}.`, parts });
183
+ });
184
+ return { pieces, steps };
185
+ }
@@ -0,0 +1,39 @@
1
+ // @ts-check
2
+ // QR codes and Code 128 barcodes as module grids. OWNER: design builder.
3
+ import qrcode from "qrcode-generator";
4
+
5
+ /** @returns {boolean[][]} rows of dark modules, quiet zone NOT included */
6
+ export function qrModules(value) {
7
+ const qr = qrcode(0, "M");
8
+ qr.addData(value);
9
+ qr.make();
10
+ const n = qr.getModuleCount();
11
+ return Array.from({ length: n }, (_, r) => Array.from({ length: n }, (_, c) => qr.isDark(r, c)));
12
+ }
13
+
14
+ // Code 128 element widths (bar, space, bar, ...) for values 0..105, then the stop pattern.
15
+ const PATTERNS = (
16
+ "212222 222122 222221 121223 121322 131222 122213 122312 132212 221213 221312 231212 112232 122132 122231 113222 " +
17
+ "123122 123221 223211 221132 221231 213212 223112 312131 311222 321122 321221 312212 322112 322211 212123 212321 " +
18
+ "232121 111323 131123 131321 112313 132113 132311 211313 231113 231311 112133 112331 132131 113123 113321 133121 " +
19
+ "313121 211331 231131 213113 213311 213131 311123 311321 331121 312113 312311 332111 314111 221411 431111 111224 " +
20
+ "111422 121124 121421 141122 141221 112214 112412 122114 122411 142112 142211 241211 221114 413111 241112 134111 " +
21
+ "111242 121142 121241 114212 124112 124211 411212 421112 421211 212141 214121 412121 111143 111341 131141 114113 " +
22
+ "114311 411113 411311 113141 114131 311141 411131 211412 211214 211232 2331112"
23
+ ).split(" ").map((p) => [...p].map(Number));
24
+ const START_B = 104;
25
+ const STOP = 106;
26
+
27
+ /** @returns {number[]} bar widths in modules, starting with a bar (dark) */
28
+ export function code128Bars(value) {
29
+ const codes = [START_B];
30
+ let sum = START_B;
31
+ for (const ch of value) {
32
+ const v = ch.codePointAt(0) - 32;
33
+ if (v < 0 || v > 94) throw new Error(`barcode: "${ch}" is not printable ASCII`);
34
+ codes.push(v);
35
+ sum += v * (codes.length - 1);
36
+ }
37
+ codes.push(sum % 103, STOP);
38
+ return codes.flatMap((c) => PATTERNS[c]);
39
+ }
@@ -0,0 +1,109 @@
1
+ // @ts-check
2
+ // Grayscale image -> 1-bit according to an ImageFilter. OWNER: design builder.
3
+ import { adjustGray, dither } from "../bits.js";
4
+
5
+ /** Grow 1-bits so a one-dot line becomes `thickness` dots wide (square, separable). */
6
+ function thicken(bits, width, height, thickness) {
7
+ if (thickness <= 1) return bits;
8
+ const before = Math.floor((thickness - 1) / 2);
9
+ const after = thickness - 1 - before;
10
+ const pass = (src, horizontal) => {
11
+ const out = new Uint8Array(src.length);
12
+ for (let y = 0; y < height; y++) {
13
+ for (let x = 0; x < width; x++) {
14
+ if (!src[y * width + x]) continue;
15
+ for (let d = -before; d <= after; d++) {
16
+ const xx = horizontal ? x + d : x;
17
+ const yy = horizontal ? y : y + d;
18
+ if (xx >= 0 && xx < width && yy >= 0 && yy < height) out[yy * width + xx] = 1;
19
+ }
20
+ }
21
+ }
22
+ return out;
23
+ };
24
+ return pass(pass(bits, true), false);
25
+ }
26
+
27
+ /** Sobel gradient magnitude divided by 4, so a full black/white step reads 255. */
28
+ function sobel(gray, width, height) {
29
+ const at = (x, y) => gray[Math.min(height - 1, Math.max(0, y)) * width + Math.min(width - 1, Math.max(0, x))];
30
+ const out = new Float32Array(width * height);
31
+ for (let y = 0; y < height; y++) {
32
+ for (let x = 0; x < width; x++) {
33
+ const gx = at(x + 1, y - 1) + 2 * at(x + 1, y) + at(x + 1, y + 1) - at(x - 1, y - 1) - 2 * at(x - 1, y) - at(x - 1, y + 1);
34
+ const gy = at(x - 1, y + 1) + 2 * at(x, y + 1) + at(x + 1, y + 1) - at(x - 1, y - 1) - 2 * at(x, y - 1) - at(x + 1, y - 1);
35
+ out[y * width + x] = Math.hypot(gx, gy) / 4;
36
+ }
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /** Black dots that touch white: the boundary of every filled shape, one dot wide. */
42
+ function boundary(mask, width, height) {
43
+ const out = new Uint8Array(mask.length);
44
+ for (let y = 0; y < height; y++) {
45
+ for (let x = 0; x < width; x++) {
46
+ const i = y * width + x;
47
+ if (!mask[i]) continue;
48
+ if ((x > 0 && !mask[i - 1]) || (x < width - 1 && !mask[i + 1]) || (y > 0 && !mask[i - width]) || (y < height - 1 && !mask[i + width])) out[i] = 1;
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /** Round dots on a square grid; each dot's area follows how dark its cell is. */
55
+ function halftone(gray, width, height, cell) {
56
+ const bits = new Uint8Array(width * height);
57
+ const cols = Math.ceil(width / cell);
58
+ const rows = Math.ceil(height / cell);
59
+ for (let cy = 0; cy < rows; cy++) {
60
+ for (let cx = 0; cx < cols; cx++) {
61
+ const x0 = Math.floor(cx * cell);
62
+ const y0 = Math.floor(cy * cell);
63
+ const x1 = Math.min(width, Math.max(x0 + 1, Math.floor((cx + 1) * cell)));
64
+ const y1 = Math.min(height, Math.max(y0 + 1, Math.floor((cy + 1) * cell)));
65
+ let sum = 0;
66
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) sum += gray[y * width + x];
67
+ const darkness = 1 - sum / ((x1 - x0) * (y1 - y0) * 255);
68
+ // Area matches darkness up to touching dots, then the dot grows to cover the corners.
69
+ const radius = darkness <= Math.PI / 4
70
+ ? cell * Math.sqrt(darkness / Math.PI)
71
+ : cell * (0.5 + (darkness - Math.PI / 4) / (1 - Math.PI / 4) * (Math.SQRT1_2 - 0.5));
72
+ if (radius <= 0.3) continue;
73
+ const mx = (cx + 0.5) * cell;
74
+ const my = (cy + 0.5) * cell;
75
+ for (let y = y0; y < y1; y++) {
76
+ for (let x = x0; x < x1; x++) if (Math.hypot(x + 0.5 - mx, y + 0.5 - my) <= radius) bits[y * width + x] = 1;
77
+ }
78
+ }
79
+ }
80
+ return bits;
81
+ }
82
+
83
+ /**
84
+ * @param {Float32Array} gray 0..255, row-major
85
+ * @param {number} width
86
+ * @param {number} height
87
+ * @param {import("./schema.js").ImageFilter} filter
88
+ * @returns {Uint8Array} bits, 1 = black
89
+ */
90
+ export function applyFilter(gray, width, height, filter) {
91
+ const { mode, style = "floyd", level = 128, lineMm = 0.25, cellMm = 1 } = filter;
92
+ const adjusted = adjustGray(gray, filter);
93
+ const lineDots = Math.max(1, Math.round(lineMm * 8));
94
+ switch (mode) {
95
+ case "dither": return dither(adjusted, width, height, style, level);
96
+ case "threshold": return dither(adjusted, width, height, "threshold", level);
97
+ case "edges": {
98
+ const magnitude = sobel(adjusted, width, height);
99
+ const edge = Uint8Array.from(magnitude, (m) => (m > level / 4 ? 1 : 0));
100
+ return thicken(edge, width, height, lineDots - 1);
101
+ }
102
+ case "outline":
103
+ return thicken(boundary(dither(adjusted, width, height, "threshold", level), width, height), width, height, lineDots);
104
+ case "halftone": return halftone(adjusted, width, height, Math.max(2, cellMm * 8));
105
+ default: throw new Error(`unknown filter mode ${mode}; use ${FILTER_MODES.join(", ")}`);
106
+ }
107
+ }
108
+
109
+ export const FILTER_MODES = ["dither", "threshold", "edges", "outline", "halftone"];