azulejeria 2.5.1 → 2.7.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.
- package/README.md +211 -23
- package/package.json +7 -4
- package/src/azulejeria.css +43 -0
- package/src/azulejeria.js +103 -16
- package/src/draw.js +448 -0
- package/src/loom.js +175 -0
- package/src/shadow.js +83 -0
- package/test/draw.mjs +53 -0
- package/test/loom.mjs +52 -0
package/src/draw.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
// draw: a tile painted by hand, one eighth of it.
|
|
2
|
+
//
|
|
3
|
+
// Every design the engine paints is symmetric across the diagonal of its
|
|
4
|
+
// square, and the repeats do the rest. So a hand only has to draw half
|
|
5
|
+
// of the square, the triangle under the diagonal from the main corner
|
|
6
|
+
// (0, 0) to the far corner (1, 1): an eighth of a quartered tile. This
|
|
7
|
+
// module turns that drawing into a motif. Each stroke is painted once on
|
|
8
|
+
// its own side of the diagonal, clipped there, and again reflected onto
|
|
9
|
+
// the other side with the same drift, so a petal drawn across the
|
|
10
|
+
// diagonal comes out whole and symmetric.
|
|
11
|
+
//
|
|
12
|
+
// A drawing is a list of strokes `{ k, c, w, pts }`: the kind (`line`,
|
|
13
|
+
// `shape` or `dot`), the colour (0 the wash, 1 to 3 an accent, 4 the
|
|
14
|
+
// ink), the weight (1 to 8) and the points in design coordinates. It is
|
|
15
|
+
// carried in a wall's state as a short string (`encodeDrawing`), two
|
|
16
|
+
// bytes a point, so it fits in a query string or a stored value.
|
|
17
|
+
//
|
|
18
|
+
// import { drawnMotif, DRAW_PAINTERS, mountPad } from 'azulejeria/draw';
|
|
19
|
+
// const wall = createWall(canvas, { motifs: { drawn: drawnMotif() },
|
|
20
|
+
// painters: { ...PAINTERS, ...DRAW_PAINTERS }, ... });
|
|
21
|
+
// mountPad(wall);
|
|
22
|
+
|
|
23
|
+
import { mulberry32, wash, ink, makeDesign, paintDesign, hexA } from './azulejeria.js';
|
|
24
|
+
|
|
25
|
+
export const KINDS = ['line', 'shape', 'dot'];
|
|
26
|
+
export const MAX_POINTS = 96; // a stroke is simplified until it has no more than this
|
|
27
|
+
|
|
28
|
+
// ----------------------------------------------------------- encoding ---
|
|
29
|
+
// A version byte, then per stroke a header byte (kind in bits 0-1,
|
|
30
|
+
// colour in 2-4, weight less one in 5-7), a point count and the points,
|
|
31
|
+
// x then y, each a byte over the unit square. Base64url.
|
|
32
|
+
const byte = v => Math.max(0, Math.min(255, Math.round(v * 255)));
|
|
33
|
+
|
|
34
|
+
export function encodeDrawing(strokes) {
|
|
35
|
+
const bytes = [1];
|
|
36
|
+
for (const s of strokes || []) {
|
|
37
|
+
const k = KINDS.indexOf(s.k);
|
|
38
|
+
const pts = (s.pts || []).slice(0, 255);
|
|
39
|
+
if (k < 0 || !pts.length) continue;
|
|
40
|
+
const c = Math.max(0, Math.min(4, s.c | 0)), w = Math.max(1, Math.min(8, s.w | 0));
|
|
41
|
+
bytes.push(k | (c << 2) | ((w - 1) << 5), pts.length);
|
|
42
|
+
for (const [x, y] of pts) bytes.push(byte(x), byte(y));
|
|
43
|
+
}
|
|
44
|
+
if (bytes.length === 1) return '';
|
|
45
|
+
let bin = '';
|
|
46
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
47
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// anything it cannot read it drops: a drawing from a bad link is empty
|
|
51
|
+
export function decodeDrawing(str) {
|
|
52
|
+
if (!str || typeof str !== 'string') return [];
|
|
53
|
+
let bin;
|
|
54
|
+
try { bin = atob(str.replace(/-/g, '+').replace(/_/g, '/')); } catch (e) { return []; }
|
|
55
|
+
if (bin.charCodeAt(0) !== 1) return [];
|
|
56
|
+
const out = [];
|
|
57
|
+
let i = 1;
|
|
58
|
+
while (i + 2 <= bin.length) {
|
|
59
|
+
const h = bin.charCodeAt(i++), n = bin.charCodeAt(i++);
|
|
60
|
+
if (!n || i + 2 * n > bin.length) break;
|
|
61
|
+
const pts = [];
|
|
62
|
+
for (let j = 0; j < n; j++) pts.push([bin.charCodeAt(i++) / 255, bin.charCodeAt(i++) / 255]);
|
|
63
|
+
const k = KINDS[h & 3], c = (h >> 2) & 7;
|
|
64
|
+
if (k && c <= 4) out.push({ k, c, w: (h >> 5) + 1, pts });
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ------------------------------------------------------------ strokes ---
|
|
70
|
+
// Ramer-Douglas-Peucker: drop the points a line through their
|
|
71
|
+
// neighbours would pass within `eps` of
|
|
72
|
+
export function simplify(pts, eps) {
|
|
73
|
+
if (pts.length < 3) return pts.slice();
|
|
74
|
+
const keep = new Uint8Array(pts.length);
|
|
75
|
+
keep[0] = keep[pts.length - 1] = 1;
|
|
76
|
+
const stack = [[0, pts.length - 1]];
|
|
77
|
+
while (stack.length) {
|
|
78
|
+
const [a, b] = stack.pop();
|
|
79
|
+
const [ax, ay] = pts[a], [bx, by] = pts[b];
|
|
80
|
+
const dx = bx - ax, dy = by - ay, dl = Math.hypot(dx, dy);
|
|
81
|
+
let far = -1, fd = eps;
|
|
82
|
+
for (let i = a + 1; i < b; i++) {
|
|
83
|
+
const [px, py] = pts[i];
|
|
84
|
+
const d = dl ? Math.abs(dy * (px - ax) - dx * (py - ay)) / dl : Math.hypot(px - ax, py - ay);
|
|
85
|
+
if (d > fd) { fd = d; far = i; }
|
|
86
|
+
}
|
|
87
|
+
if (far > 0) { keep[far] = 1; stack.push([a, far], [far, b]); }
|
|
88
|
+
}
|
|
89
|
+
return pts.filter((_, i) => keep[i]);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Chaikin's corners, cut twice: a hand's polyline as a curve
|
|
93
|
+
export function smooth(pts, closed, times) {
|
|
94
|
+
let p = pts;
|
|
95
|
+
for (let t = 0; t < (times === undefined ? 2 : times); t++) {
|
|
96
|
+
if (p.length < 3) return p;
|
|
97
|
+
const q = closed ? [] : [p[0]];
|
|
98
|
+
const n = closed ? p.length : p.length - 1;
|
|
99
|
+
for (let i = 0; i < n; i++) {
|
|
100
|
+
const a = p[i], b = p[(i + 1) % p.length];
|
|
101
|
+
q.push([a[0] * 0.75 + b[0] * 0.25, a[1] * 0.75 + b[1] * 0.25], [a[0] * 0.25 + b[0] * 0.75, a[1] * 0.25 + b[1] * 0.75]);
|
|
102
|
+
}
|
|
103
|
+
if (!closed) q.push(p[p.length - 1]);
|
|
104
|
+
p = q;
|
|
105
|
+
}
|
|
106
|
+
return p;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const swap = pts => pts.map(([x, y]) => [y, x]);
|
|
110
|
+
|
|
111
|
+
// A stroke as it is kept: inside the square, on the drawn side of the
|
|
112
|
+
// diagonal (a stroke drawn mostly on the other side is reflected over),
|
|
113
|
+
// and simplified to no more than MAX_POINTS.
|
|
114
|
+
export function settle(stroke) {
|
|
115
|
+
let pts = stroke.pts.map(([x, y]) => [Math.max(0, Math.min(1, x)), Math.max(0, Math.min(1, y))]);
|
|
116
|
+
if (!pts.length) return null;
|
|
117
|
+
const lean = pts.reduce((s, [x, y]) => s + (y - x), 0);
|
|
118
|
+
if (lean > 0) pts = swap(pts);
|
|
119
|
+
if (stroke.k === 'dot') pts = [pts[0]];
|
|
120
|
+
else {
|
|
121
|
+
let eps = 0.004;
|
|
122
|
+
pts = simplify(pts, eps);
|
|
123
|
+
while (pts.length > MAX_POINTS) pts = simplify(pts, eps *= 1.5);
|
|
124
|
+
if (stroke.k === 'shape' && pts.length < 3) return null;
|
|
125
|
+
if (stroke.k === 'line' && pts.length < 2) return null;
|
|
126
|
+
}
|
|
127
|
+
return { k: stroke.k, c: stroke.c | 0, w: stroke.w | 0 || 1, pts };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// a band either side of a polyline, as a closed outline
|
|
131
|
+
function ribbon(pts, h) {
|
|
132
|
+
const L = [], R = [];
|
|
133
|
+
for (let i = 0; i < pts.length; i++) {
|
|
134
|
+
const a = pts[Math.max(0, i - 1)], c = pts[Math.min(pts.length - 1, i + 1)];
|
|
135
|
+
const dx = c[0] - a[0], dy = c[1] - a[1], d = Math.hypot(dx, dy) || 1;
|
|
136
|
+
const nx = -dy / d * h, ny = dx / d * h;
|
|
137
|
+
L.push([pts[i][0] + nx, pts[i][1] + ny]);
|
|
138
|
+
R.push([pts[i][0] - nx, pts[i][1] - ny]);
|
|
139
|
+
}
|
|
140
|
+
return L.concat(R.reverse());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// The brush's drift along a whole stroke: two slow sines across its
|
|
144
|
+
// length, pushed along the normal. The engine's `polyPts` drifts each
|
|
145
|
+
// side of a polygon, which suits a shape with a few long sides; a
|
|
146
|
+
// hand's stroke is hundreds of short ones and wants one drift from end
|
|
147
|
+
// to end. A closed stroke takes whole numbers of waves so it closes.
|
|
148
|
+
// Four numbers from the rng, whatever the stroke.
|
|
149
|
+
function drift(pts, closed, amp, rng) {
|
|
150
|
+
const p1 = rng() * 6.283, p2 = rng() * 6.283, a = rng(), b = rng();
|
|
151
|
+
const n = pts.length;
|
|
152
|
+
if (n < 2 || !amp) return pts;
|
|
153
|
+
const len = [0];
|
|
154
|
+
for (let i = 1; i < n; i++) len.push(len[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
|
|
155
|
+
const total = (len[n - 1] + (closed ? Math.hypot(pts[0][0] - pts[n - 1][0], pts[0][1] - pts[n - 1][1]) : 0)) || 1;
|
|
156
|
+
// so many waves to a tile's side, not to a stroke: a short stroke gets part of one
|
|
157
|
+
const k = Math.max(0.3, Math.min(2.5, total / 0.8));
|
|
158
|
+
const f1 = closed ? Math.max(1, Math.round((2 + a) * k)) : (1.5 + a * 2) * k;
|
|
159
|
+
const f2 = closed ? Math.max(2, Math.round((5 + b * 3) * k)) : (4 + b * 4) * k;
|
|
160
|
+
return pts.map((p, i) => {
|
|
161
|
+
const q = pts[closed ? (i - 1 + n) % n : Math.max(0, i - 1)], r = pts[closed ? (i + 1) % n : Math.min(n - 1, i + 1)];
|
|
162
|
+
const dx = r[0] - q[0], dy = r[1] - q[1], d = Math.hypot(dx, dy) || 1, t = len[i] / total * 6.283;
|
|
163
|
+
const w = (Math.sin(t * f1 + p1) * 0.65 + Math.sin(t * f2 + p2) * 0.35) * amp;
|
|
164
|
+
return [p[0] - dy / d * w, p[1] + dx / d * w];
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// two layers the size of the tile, for the halves of a glazed stroke
|
|
169
|
+
let LAYERS = null;
|
|
170
|
+
function layers(g) {
|
|
171
|
+
const w = g.canvas.width, h = g.canvas.height;
|
|
172
|
+
if (!LAYERS) LAYERS = [0, 1].map(() => { const c = document.createElement('canvas'); return c.getContext('2d'); });
|
|
173
|
+
for (const l of LAYERS) {
|
|
174
|
+
if (l.canvas.width !== w || l.canvas.height !== h) { l.canvas.width = w; l.canvas.height = h; }
|
|
175
|
+
else { l.setTransform(1, 0, 0, 1, 0, 0); l.clearRect(0, 0, w, h); }
|
|
176
|
+
l.setTransform(g.getTransform());
|
|
177
|
+
l.lineCap = 'round'; l.lineJoin = 'round';
|
|
178
|
+
}
|
|
179
|
+
return LAYERS;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ----------------------------------------------------------- painters ---
|
|
183
|
+
// `stroke` paints one stroke of a drawing and its reflection. The drift
|
|
184
|
+
// is laid once and the brush's random numbers are dealt the same to
|
|
185
|
+
// both halves, so the two meet on the diagonal without a seam in the
|
|
186
|
+
// line. Glaze is translucent, so its halves are painted on a layer
|
|
187
|
+
// each, clipped exactly at the diagonal, and added together: where the
|
|
188
|
+
// two soft edges share a pixel their cover sums to one, and no hairline
|
|
189
|
+
// shows. A material's `shape`, `line` and `dot` are used when it has
|
|
190
|
+
// them, so a drawing comes out in clay or cement as readily as in
|
|
191
|
+
// glaze; those are opaque and paint straight on, the drawn half a hair
|
|
192
|
+
// past the diagonal. A coloured line is a ribbon, which is a shape.
|
|
193
|
+
export const DRAW_PAINTERS = {
|
|
194
|
+
stroke(el, b) {
|
|
195
|
+
const { g, pal } = b;
|
|
196
|
+
const m = b.material || {};
|
|
197
|
+
const seed = Math.floor(b.rng() * 2147483647);
|
|
198
|
+
const col = el.c === 4 ? pal.ink
|
|
199
|
+
: el.c === 0 || !pal.accents.length ? pal.wash
|
|
200
|
+
: pal.accents[(el.c - 1) % pal.accents.length];
|
|
201
|
+
const t = g.getTransform ? g.getTransform() : { a: 100, b: 0 };
|
|
202
|
+
const eps = 0.8 / (Math.hypot(t.a, t.b) || 100);
|
|
203
|
+
const width = b.lw * el.w;
|
|
204
|
+
const r0 = mulberry32(seed);
|
|
205
|
+
|
|
206
|
+
let path = null;
|
|
207
|
+
const fill = el.k === 'shape' || (el.k === 'line' && el.c !== 4);
|
|
208
|
+
if (el.k === 'shape' && el.pts.length >= 3) path = drift(smooth(el.pts, true, 3), true, b.amp, r0);
|
|
209
|
+
else if (el.k === 'line' && el.pts.length >= 2) {
|
|
210
|
+
const line = drift(smooth(el.pts, false, 3), false, b.amp, r0);
|
|
211
|
+
path = el.c === 4 ? line : ribbon(line, width * 0.9);
|
|
212
|
+
} else if (el.k !== 'dot') return;
|
|
213
|
+
const own = m.shape || m.line || m.dot; // the material paints, straight onto the tile
|
|
214
|
+
const L = own ? null : layers(g);
|
|
215
|
+
|
|
216
|
+
const rng0 = b.rng, col0 = b.col, g0 = g;
|
|
217
|
+
for (const half of [0, 1]) {
|
|
218
|
+
const rr = mulberry32(seed + 1);
|
|
219
|
+
const g = L ? L[half] : g0, e = L ? 0 : eps;
|
|
220
|
+
g.save();
|
|
221
|
+
g.beginPath();
|
|
222
|
+
if (half) { g.moveTo(-1, -1); g.lineTo(2, 2); g.lineTo(-1, 2); }
|
|
223
|
+
else { g.moveTo(-1, -1); g.lineTo(-1, -1 + e); g.lineTo(2, 2 + e); g.lineTo(2, -1); }
|
|
224
|
+
g.closePath();
|
|
225
|
+
g.clip();
|
|
226
|
+
b.rng = rr; b.col = col;
|
|
227
|
+
if (el.k === 'dot') {
|
|
228
|
+
for (const [x0, y0] of el.pts) {
|
|
229
|
+
const [x, y] = half ? [y0, x0] : [x0, y0], r = width * 0.8;
|
|
230
|
+
if (m.dot) m.dot(g, x, y, r, col, 0.88, b);
|
|
231
|
+
else { g.beginPath(); g.arc(x, y, r, 0, 6.283); g.fillStyle = col; g.globalAlpha = 0.88; g.fill(); g.globalAlpha = 1; }
|
|
232
|
+
}
|
|
233
|
+
} else {
|
|
234
|
+
const P = half ? swap(path) : path;
|
|
235
|
+
if (fill) {
|
|
236
|
+
if (m.shape) m.shape(g, P, col, b);
|
|
237
|
+
else { wash(g, P, col, rr); ink(g, P, b.lw, pal, rr, true); }
|
|
238
|
+
} else if (m.line) m.line(g, P, width, false, b);
|
|
239
|
+
else ink(g, P, width, pal, rr, false);
|
|
240
|
+
}
|
|
241
|
+
g.restore();
|
|
242
|
+
}
|
|
243
|
+
b.rng = rng0; b.col = col0;
|
|
244
|
+
if (L) {
|
|
245
|
+
L[0].setTransform(1, 0, 0, 1, 0, 0);
|
|
246
|
+
L[0].globalCompositeOperation = 'lighter';
|
|
247
|
+
L[0].drawImage(L[1].canvas, 0, 0);
|
|
248
|
+
L[0].globalCompositeOperation = 'source-over';
|
|
249
|
+
g0.save(); g0.setTransform(1, 0, 0, 1, 0, 0); g0.drawImage(L[0].canvas, 0, 0); g0.restore();
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
// ------------------------------------------------------------- motif ---
|
|
255
|
+
// The motif that paints the drawing in `state[key]` ('d' by default),
|
|
256
|
+
// with the engine's band across the far corner when bands are on.
|
|
257
|
+
export function drawnMotif(key) {
|
|
258
|
+
key = key || 'd';
|
|
259
|
+
return ({ state, bands }) => {
|
|
260
|
+
const els = decodeDrawing(state && state[key]).map(s => ({ t: 'stroke', ...s }));
|
|
261
|
+
if (bands) els.push({ t: 'band', kind: 'circle', w: 0.045, role: 'wash' });
|
|
262
|
+
return els;
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// --------------------------------------------------------------- pad ---
|
|
267
|
+
// mountPad(wall, opts) wires a drawing pad to a wall whose motif is
|
|
268
|
+
// `drawnMotif`. The page provides, inside `#pad`: a canvas `#padCanvas`;
|
|
269
|
+
// buttons `.tool[data-tool]` (line, shape, dot); an empty `#swatches`
|
|
270
|
+
// the palette's colours are put in; a range `#weight`; buttons `#undo`
|
|
271
|
+
// and `#clear`; and `#padHead` with `#padToggle` to fold it. Anything
|
|
272
|
+
// missing is skipped. The pad shows the square of the design in the
|
|
273
|
+
// wall's own palette, brush and material, with the reflected half
|
|
274
|
+
// dimmed; you draw in the bright half. Every stroke is written to
|
|
275
|
+
// `wall.state[key]` and the wall repaints, while you draw as well as
|
|
276
|
+
// after. `opts.onEdit(d)` hears each change (to put it in the address,
|
|
277
|
+
// say). Cmd or Ctrl Z undoes. Returns `{ render, undo, clear }`.
|
|
278
|
+
export function mountPad(wall, opts) {
|
|
279
|
+
opts = opts || {};
|
|
280
|
+
const doc = opts.document || document;
|
|
281
|
+
const $ = id => doc.getElementById(id);
|
|
282
|
+
const key = opts.key || 'd';
|
|
283
|
+
const canvas = $(opts.canvasId || 'padCanvas');
|
|
284
|
+
const { state } = wall;
|
|
285
|
+
const pen = { tool: 'shape', c: 0, w: 3 };
|
|
286
|
+
const history = [];
|
|
287
|
+
let strokes = decodeDrawing(state[key]), seen = state[key], live = null, liveTimer = 0, queued = false, palSeen = null;
|
|
288
|
+
const M = 10; // the margin round the square, css pixels
|
|
289
|
+
|
|
290
|
+
function write(list) {
|
|
291
|
+
state[key] = encodeDrawing(list);
|
|
292
|
+
seen = state[key];
|
|
293
|
+
wall.preset = '';
|
|
294
|
+
wall.rebuild(true);
|
|
295
|
+
if (opts.onEdit) opts.onEdit(state[key]);
|
|
296
|
+
}
|
|
297
|
+
function commit(next) {
|
|
298
|
+
history.push(strokes);
|
|
299
|
+
if (history.length > 200) history.shift();
|
|
300
|
+
strokes = next;
|
|
301
|
+
write(strokes);
|
|
302
|
+
schedule();
|
|
303
|
+
}
|
|
304
|
+
function undo() { if (history.length) { strokes = history.pop(); write(strokes); schedule(); } }
|
|
305
|
+
function clear() { if (strokes.length) commit([]); }
|
|
306
|
+
|
|
307
|
+
function swatches(pal) {
|
|
308
|
+
const box = $('swatches');
|
|
309
|
+
if (!box) return;
|
|
310
|
+
const cols = [pal.wash, ...pal.accents.slice(0, 3), pal.ink];
|
|
311
|
+
const ids = [0, ...pal.accents.slice(0, 3).map((_, i) => i + 1), 4];
|
|
312
|
+
if (!ids.includes(pen.c)) pen.c = 0;
|
|
313
|
+
box.innerHTML = '';
|
|
314
|
+
ids.forEach((c, i) => {
|
|
315
|
+
const s = doc.createElement('button');
|
|
316
|
+
s.className = 'sw' + (c === pen.c ? ' on' : '');
|
|
317
|
+
s.style.background = cols[i];
|
|
318
|
+
s.title = c === 0 ? 'wash' : c === 4 ? 'ink' : 'accent ' + c;
|
|
319
|
+
s.addEventListener('click', () => { pen.c = c; box.querySelectorAll('.sw').forEach(x => x.classList.toggle('on', x === s)); });
|
|
320
|
+
box.appendChild(s);
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function render() {
|
|
325
|
+
queued = false;
|
|
326
|
+
if (!canvas) return;
|
|
327
|
+
if (state[key] !== seen) { strokes = decodeDrawing(state[key]); seen = state[key]; history.length = 0; }
|
|
328
|
+
const pal = wall.palettes[state.pal];
|
|
329
|
+
if (pal !== palSeen) { palSeen = pal; swatches(pal); }
|
|
330
|
+
const W = canvas.clientWidth || 200, DPR = Math.min(window.devicePixelRatio || 1, 2);
|
|
331
|
+
if (canvas.width !== Math.round(W * DPR)) { canvas.width = canvas.height = Math.round(W * DPR); }
|
|
332
|
+
const g = canvas.getContext('2d');
|
|
333
|
+
const S = W - 2 * M;
|
|
334
|
+
g.setTransform(DPR, 0, 0, DPR, 0, 0);
|
|
335
|
+
g.fillStyle = pal.grout; g.fillRect(0, 0, W, W);
|
|
336
|
+
g.translate(M, M);
|
|
337
|
+
g.fillStyle = pal.glaze; g.fillRect(0, 0, S, S);
|
|
338
|
+
const m = wall.material || {};
|
|
339
|
+
if (m.surface) m.surface(g, S, pal, mulberry32(state.seed));
|
|
340
|
+
g.lineCap = 'round'; g.lineJoin = 'round';
|
|
341
|
+
g.save(); g.scale(S, S);
|
|
342
|
+
const list = live ? strokes.concat([settle(live) || []]).filter(s => s.pts) : strokes;
|
|
343
|
+
const view = { ...state, [key]: encodeDrawing(list) };
|
|
344
|
+
const design = makeDesign(state.seed, state.density, state.bands, 1, wall.motifs[state.motif], view);
|
|
345
|
+
paintDesign(g, design, pal, state.hand, 0.012 * state.brush, state.seed * 31 + 17, wall.painters, wall.material, state.brush);
|
|
346
|
+
// the reflected half, dimmed, and the diagonal
|
|
347
|
+
g.beginPath(); g.moveTo(0, 0); g.lineTo(1, 1); g.lineTo(0, 1); g.closePath();
|
|
348
|
+
g.fillStyle = hexA(pal.grout, 0.55); g.fill();
|
|
349
|
+
g.restore();
|
|
350
|
+
g.setLineDash([3, 4]); g.strokeStyle = hexA(pal.ink, 0.45); g.lineWidth = 1;
|
|
351
|
+
g.beginPath(); g.moveTo(0, 0); g.lineTo(S, S); g.stroke(); g.setLineDash([]);
|
|
352
|
+
// the main corner, where four tiles (or the four quarters) meet
|
|
353
|
+
g.beginPath(); g.arc(0, 0, 4, 0, 6.283); g.fillStyle = hexA(pal.ink, 0.7); g.fill();
|
|
354
|
+
// the stroke under the pen, as drawn
|
|
355
|
+
if (live && live.pts.length > 1) {
|
|
356
|
+
g.beginPath();
|
|
357
|
+
live.pts.forEach(([x, y], i) => (i ? g.lineTo(x * S, y * S) : g.moveTo(x * S, y * S)));
|
|
358
|
+
if (live.k === 'shape') g.closePath();
|
|
359
|
+
g.strokeStyle = hexA(pal.ink, 0.6); g.lineWidth = 1.2; g.stroke();
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function schedule() { if (!queued) { queued = true; requestAnimationFrame(render); } }
|
|
363
|
+
|
|
364
|
+
// the wall tells the pad when the palette, brush, preset or seed changes
|
|
365
|
+
const rebuild = wall.rebuild;
|
|
366
|
+
wall.rebuild = t => { rebuild(t); schedule(); };
|
|
367
|
+
const changed = wall.onChange;
|
|
368
|
+
wall.onChange = k => { if (changed) changed(k); schedule(); };
|
|
369
|
+
|
|
370
|
+
if (canvas) {
|
|
371
|
+
const at = e => {
|
|
372
|
+
const r = canvas.getBoundingClientRect(), S = r.width - 2 * M;
|
|
373
|
+
return [(e.clientX - r.left - M) / S, (e.clientY - r.top - M) / S];
|
|
374
|
+
};
|
|
375
|
+
canvas.addEventListener('pointerdown', e => {
|
|
376
|
+
e.preventDefault();
|
|
377
|
+
canvas.setPointerCapture(e.pointerId);
|
|
378
|
+
const p = at(e);
|
|
379
|
+
if (pen.tool === 'dot') {
|
|
380
|
+
const s = settle({ k: 'dot', c: pen.c, w: pen.w, pts: [p] });
|
|
381
|
+
if (s) commit(strokes.concat([s]));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
live = { k: pen.tool, c: pen.c, w: pen.w, pts: [p] };
|
|
385
|
+
schedule();
|
|
386
|
+
});
|
|
387
|
+
canvas.addEventListener('pointermove', e => {
|
|
388
|
+
if (!live) return;
|
|
389
|
+
const p = at(e), q = live.pts[live.pts.length - 1];
|
|
390
|
+
if (Math.hypot(p[0] - q[0], p[1] - q[1]) < 0.004) return;
|
|
391
|
+
live.pts.push(p);
|
|
392
|
+
schedule();
|
|
393
|
+
// the wall follows the pen, a few times a second
|
|
394
|
+
if (!liveTimer) liveTimer = setTimeout(() => {
|
|
395
|
+
liveTimer = 0;
|
|
396
|
+
if (!live) return;
|
|
397
|
+
const s = settle(live);
|
|
398
|
+
state[key] = encodeDrawing(s ? strokes.concat([s]) : strokes);
|
|
399
|
+
seen = state[key];
|
|
400
|
+
wall.rebuild(true);
|
|
401
|
+
}, 70);
|
|
402
|
+
});
|
|
403
|
+
const end = () => {
|
|
404
|
+
if (!live) return;
|
|
405
|
+
const s = settle(live);
|
|
406
|
+
live = null;
|
|
407
|
+
clearTimeout(liveTimer); liveTimer = 0;
|
|
408
|
+
if (s) commit(strokes.concat([s]));
|
|
409
|
+
else { write(strokes); schedule(); }
|
|
410
|
+
};
|
|
411
|
+
canvas.addEventListener('pointerup', end);
|
|
412
|
+
canvas.addEventListener('pointercancel', end);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
doc.querySelectorAll('.tool[data-tool]').forEach(btn => {
|
|
416
|
+
btn.classList.toggle('on', btn.dataset.tool === pen.tool);
|
|
417
|
+
btn.addEventListener('click', () => {
|
|
418
|
+
pen.tool = btn.dataset.tool;
|
|
419
|
+
doc.querySelectorAll('.tool[data-tool]').forEach(x => x.classList.toggle('on', x === btn));
|
|
420
|
+
});
|
|
421
|
+
});
|
|
422
|
+
const weight = $('weight');
|
|
423
|
+
if (weight) {
|
|
424
|
+
weight.value = pen.w;
|
|
425
|
+
const val = $('weightVal');
|
|
426
|
+
if (val) val.textContent = pen.w;
|
|
427
|
+
weight.addEventListener('input', () => { pen.w = parseInt(weight.value, 10) || 1; if (val) val.textContent = pen.w; });
|
|
428
|
+
}
|
|
429
|
+
const on = (id, fn) => { const el = $(id); if (el) el.addEventListener('click', fn); };
|
|
430
|
+
on('undo', undo);
|
|
431
|
+
on('clear', clear);
|
|
432
|
+
doc.addEventListener('keydown', e => {
|
|
433
|
+
if ((e.metaKey || e.ctrlKey) && !e.shiftKey && e.key.toLowerCase() === 'z' && !/^(INPUT|SELECT|TEXTAREA)$/.test(e.target.tagName)) {
|
|
434
|
+
e.preventDefault(); undo();
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
const box = $('pad');
|
|
438
|
+
on('padHead', () => {
|
|
439
|
+
if (!box) return;
|
|
440
|
+
box.classList.toggle('closed');
|
|
441
|
+
const t = $('padToggle');
|
|
442
|
+
if (t) t.textContent = box.classList.contains('closed') ? '+' : '−';
|
|
443
|
+
schedule();
|
|
444
|
+
});
|
|
445
|
+
window.addEventListener('resize', schedule);
|
|
446
|
+
schedule();
|
|
447
|
+
return { render: schedule, undo, clear };
|
|
448
|
+
}
|
package/src/loom.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// loom: cloth by rule.
|
|
2
|
+
//
|
|
3
|
+
// A weaving draft is a small program. The threading says which shaft
|
|
4
|
+
// each warp end is drawn through, the tie-up says which shafts each
|
|
5
|
+
// treadle lifts, and the treadling says which treadle is pressed for
|
|
6
|
+
// each pick of the weft. Where an end's shaft is lifted the warp lies
|
|
7
|
+
// over the weft; everywhere else the weft lies over the warp. That is
|
|
8
|
+
// the whole of the structure, and `lifted` is the whole of the rule.
|
|
9
|
+
//
|
|
10
|
+
// The colour is a second program laid over the first. A sett is a
|
|
11
|
+
// string of colours and thread counts, "K4 R24 K24 Y4", and the cloth
|
|
12
|
+
// shows a thread's colour wherever that thread is on top.
|
|
13
|
+
//
|
|
14
|
+
// Nothing above the last section needs a document, so the rule can be
|
|
15
|
+
// tested without a browser.
|
|
16
|
+
|
|
17
|
+
const mod = (n, m) => ((n % m) + m) % m;
|
|
18
|
+
|
|
19
|
+
// ------------------------------------------------------------- drafts ---
|
|
20
|
+
// threading: a shaft for each end, repeating. tieup: for each treadle,
|
|
21
|
+
// the shafts it lifts. treadling: a treadle for each pick, repeating.
|
|
22
|
+
const TWILL_TIE = [[0, 1], [1, 2], [2, 3], [3, 0]];
|
|
23
|
+
export const DRAFTS = {
|
|
24
|
+
// over one, under one
|
|
25
|
+
plain: { threading: [0, 1], tieup: [[0], [1]], treadling: [0, 1] },
|
|
26
|
+
// 2/2 twill: over two, under two, stepping one along each pick. The cloth of tartan
|
|
27
|
+
twill: { threading: [0, 1, 2, 3], tieup: TWILL_TIE, treadling: [0, 1, 2, 3] },
|
|
28
|
+
// 3/1 twill: the warp shows on the face. Denim
|
|
29
|
+
drill: { threading: [0, 1, 2, 3], tieup: [[0, 1, 2], [1, 2, 3], [2, 3, 0], [3, 0, 1]], treadling: [0, 1, 2, 3] },
|
|
30
|
+
// the twill turned back on itself every eight ends, with a break at the turn
|
|
31
|
+
herringbone: { threading: [0, 1, 2, 3, 0, 1, 2, 3, 1, 0, 3, 2, 1, 0, 3, 2], tieup: TWILL_TIE, treadling: [0, 1, 2, 3] },
|
|
32
|
+
// the twill turned back in the weft as well: diamonds
|
|
33
|
+
diamond: { threading: [0, 1, 2, 3, 0, 1, 2, 3, 2, 1, 0, 3, 2, 1], tieup: TWILL_TIE, treadling: [0, 1, 2, 3, 0, 1, 2, 3, 2, 1, 0, 3, 2, 1] },
|
|
34
|
+
// plain weave with every thread doubled
|
|
35
|
+
basket: { threading: [0, 0, 1, 1], tieup: [[0], [1]], treadling: [0, 0, 1, 1] },
|
|
36
|
+
};
|
|
37
|
+
export const DRAFT_NAMES = Object.keys(DRAFTS);
|
|
38
|
+
|
|
39
|
+
// is warp end i over the weft at pick j?
|
|
40
|
+
export function lifted(draft, i, j) {
|
|
41
|
+
const shaft = draft.threading[mod(i, draft.threading.length)];
|
|
42
|
+
return draft.tieup[draft.treadling[mod(j, draft.treadling.length)]].includes(shaft);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// the drawdown of one repeat: w ends by h picks, 1 where the warp is up
|
|
46
|
+
export function drawdown(draft) {
|
|
47
|
+
const w = draft.threading.length, h = draft.treadling.length, m = new Uint8Array(w * h);
|
|
48
|
+
for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) m[j * w + i] = lifted(draft, i, j) ? 1 : 0;
|
|
49
|
+
return { w, h, m };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// --------------------------------------------------------------- setts ---
|
|
53
|
+
// A sett is written as the weavers write it: a colour code and a
|
|
54
|
+
// count, over and over. "K4 R24 K24 Y4" is four black, twenty-four
|
|
55
|
+
// red, twenty-four black, four yellow. A colour is one or two letters
|
|
56
|
+
// (K black, R red, G green, B blue, Y yellow, W white, N grey, P
|
|
57
|
+
// purple, O orange, T brown, A azure, with L or D in front for light
|
|
58
|
+
// and dark) or a hex colour, #c8102e. A slash may sit between the
|
|
59
|
+
// colour and the count, as it does at the pivots of a registered
|
|
60
|
+
// threadcount ("B/24 K4 ... B/4"), and is ignored: a sett is taken to
|
|
61
|
+
// turn back at both ends, the first and last stripes being the pivots
|
|
62
|
+
// and counted once, unless it is written with "..." in it, which
|
|
63
|
+
// says it simply repeats.
|
|
64
|
+
export function parseSett(text) {
|
|
65
|
+
const t = String(text || '');
|
|
66
|
+
const stripes = [];
|
|
67
|
+
const re = /(#[0-9a-fA-F]{6}|[A-Za-z]{1,2})\s*\/?\s*(\d{1,3})/g;
|
|
68
|
+
let m;
|
|
69
|
+
while ((m = re.exec(t)) && stripes.length < 64) {
|
|
70
|
+
const n = Math.min(400, parseInt(m[2], 10));
|
|
71
|
+
if (n > 0) stripes.push({ code: m[1][0] === '#' ? m[1].toLowerCase() : m[1].toUpperCase(), n });
|
|
72
|
+
}
|
|
73
|
+
return { stripes, mirror: !t.includes('...') };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// one repeat of the sett, a colour code for each thread
|
|
77
|
+
export function threadsOf(sett) {
|
|
78
|
+
const s = sett.stripes;
|
|
79
|
+
if (!s.length) return ['N'];
|
|
80
|
+
const order = sett.mirror && s.length > 2 ? s.concat(s.slice(1, -1).reverse()) : s;
|
|
81
|
+
const out = [];
|
|
82
|
+
for (const { code, n } of order) for (let k = 0; k < n; k++) out.push(code);
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// the sett written back out, as the register would have it
|
|
87
|
+
export function writeSett(sett) {
|
|
88
|
+
const s = sett.stripes;
|
|
89
|
+
if (!sett.mirror) return s.map(x => x.code + x.n).join(' ') + ' ...';
|
|
90
|
+
return s.map((x, i) => x.code + (i === 0 || i === s.length - 1 ? '/' : '') + x.n).join(' ');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// --------------------------------------------------------------- dyes ---
|
|
94
|
+
// The same sett in three dye lots. Modern is the aniline dye of the
|
|
95
|
+
// mills, ancient the paler shades the vegetable dyes are supposed to
|
|
96
|
+
// have given, weathered what a plaid looks like after a century in a
|
|
97
|
+
// peat bog.
|
|
98
|
+
export const DYES = {
|
|
99
|
+
modern: { K: '#101010', R: '#c80000', G: '#006818', B: '#2c2c80', Y: '#e8c000', W: '#e0e0e0', N: '#808080', P: '#780078', O: '#d87c00', T: '#604000', A: '#5c8cd0', M: '#901c38', C: '#b01030' },
|
|
100
|
+
ancient: { K: '#2a2a2a', R: '#d4542c', G: '#4f8a4a', B: '#5a86b8', Y: '#e6cc5c', W: '#f0ebdd', N: '#9a9a94', P: '#9a5a9a', O: '#e89a3c', T: '#8a6a3a', A: '#8cb4dc', M: '#b0506a', C: '#c8485a' },
|
|
101
|
+
weathered: { K: '#4c4a48', R: '#a2553f', G: '#6f7046', B: '#5a6c80', Y: '#c2a85e', W: '#d9d0bd', N: '#8f8a80', P: '#7d6478', O: '#b9814a', T: '#75603f', A: '#8a9cab', M: '#8f5a5c', C: '#9c5450' },
|
|
102
|
+
};
|
|
103
|
+
const rgbOf = hex => { const n = parseInt(hex.slice(1), 16); return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; };
|
|
104
|
+
// a code as [r, g, b] in a dye lot: a letter, a letter with L or D
|
|
105
|
+
// before it, or a hex colour as it stands
|
|
106
|
+
export function dyeOf(code, dye) {
|
|
107
|
+
const lot = typeof dye === 'string' ? DYES[dye] || DYES.modern : dye;
|
|
108
|
+
if (code[0] === '#') return rgbOf(code);
|
|
109
|
+
if (lot[code]) return rgbOf(lot[code]);
|
|
110
|
+
if (code.length === 2 && (code[0] === 'L' || code[0] === 'D') && lot[code[1]]) {
|
|
111
|
+
const c = rgbOf(lot[code[1]]), to = code[0] === 'L' ? 255 : 0, t = code[0] === 'L' ? 0.4 : 0.35;
|
|
112
|
+
return c.map(v => Math.round(v + (to - v) * t));
|
|
113
|
+
}
|
|
114
|
+
return rgbOf(lot.N);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// -------------------------------------------------------------- cloth ---
|
|
118
|
+
// Fills `data` (RGBA, w by h, one pixel a crossing) with the cloth from
|
|
119
|
+
// end i0 and pick j0: at each crossing the colour of whichever thread
|
|
120
|
+
// is on top. `warp` and `weft` are one repeat of colours, [r, g, b]
|
|
121
|
+
// each. The thread underneath shows a little at the edges of the one
|
|
122
|
+
// above, so `under` (0 to 1) lets that much of it through.
|
|
123
|
+
export function weavePixels(data, w, h, i0, j0, warp, weft, draft, under) {
|
|
124
|
+
const dd = drawdown(draft), u = under || 0, nw = warp.length, nf = weft.length;
|
|
125
|
+
for (let y = 0; y < h; y++) {
|
|
126
|
+
const j = j0 + y, f = weft[mod(j, nf)], row = mod(j, dd.h) * dd.w;
|
|
127
|
+
for (let x = 0; x < w; x++) {
|
|
128
|
+
const i = i0 + x, p = warp[mod(i, nw)], up = dd.m[row + mod(i, dd.w)];
|
|
129
|
+
const a = up ? p : f, b = up ? f : p, o = (y * w + x) * 4;
|
|
130
|
+
data[o] = a[0] + (b[0] - a[0]) * u; data[o + 1] = a[1] + (b[1] - a[1]) * u; data[o + 2] = a[2] + (b[2] - a[2]) * u; data[o + 3] = 255;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return data;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The same as a canvas, one pixel a crossing, to be drawn scaled up
|
|
137
|
+
// with smoothing off. Pass `into` to reuse a canvas.
|
|
138
|
+
export function clothCanvas(w, h, i0, j0, warp, weft, draft, under, into) {
|
|
139
|
+
const c = into || document.createElement('canvas');
|
|
140
|
+
if (c.width !== w || c.height !== h) { c.width = w; c.height = h; }
|
|
141
|
+
const g = c.getContext('2d'), img = g.createImageData(w, h);
|
|
142
|
+
weavePixels(img.data, w, h, i0, j0, warp, weft, draft, under);
|
|
143
|
+
g.putImageData(img, 0, 0);
|
|
144
|
+
return c;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// The threads themselves: one repeat of the draft with each crossing
|
|
148
|
+
// `t` pixels square, in black and white over nothing, to be laid over
|
|
149
|
+
// the colour. The thread on top is round (dark at its edges, light
|
|
150
|
+
// down its middle) and goes under where the other system comes up.
|
|
151
|
+
const tiles = new Map();
|
|
152
|
+
export function threadTile(draft, t) {
|
|
153
|
+
const key = JSON.stringify(draft) + '|' + t;
|
|
154
|
+
let c = tiles.get(key);
|
|
155
|
+
if (c) return c;
|
|
156
|
+
if (tiles.size > 24) tiles.clear();
|
|
157
|
+
const dd = drawdown(draft);
|
|
158
|
+
c = document.createElement('canvas'); c.width = dd.w * t; c.height = dd.h * t;
|
|
159
|
+
const g = c.getContext('2d');
|
|
160
|
+
const up = (i, j) => dd.m[mod(j, dd.h) * dd.w + mod(i, dd.w)];
|
|
161
|
+
for (let j = 0; j < dd.h; j++) for (let i = 0; i < dd.w; i++) {
|
|
162
|
+
const x = i * t, y = j * t, warp = up(i, j);
|
|
163
|
+
const gr = warp ? g.createLinearGradient(x, 0, x + t, 0) : g.createLinearGradient(0, y, 0, y + t);
|
|
164
|
+
gr.addColorStop(0, 'rgba(0,0,0,0.34)'); gr.addColorStop(0.22, 'rgba(0,0,0,0.04)');
|
|
165
|
+
gr.addColorStop(0.45, 'rgba(255,255,255,0.16)'); gr.addColorStop(0.78, 'rgba(0,0,0,0.05)'); gr.addColorStop(1, 'rgba(0,0,0,0.38)');
|
|
166
|
+
g.fillStyle = gr; g.fillRect(x, y, t, t);
|
|
167
|
+
// where it dives under its neighbour along its own length
|
|
168
|
+
const e = Math.max(1, t * 0.16);
|
|
169
|
+
g.fillStyle = 'rgba(0,0,0,0.26)';
|
|
170
|
+
if (warp) { if (!up(i, j - 1)) g.fillRect(x, y, t, e); if (!up(i, j + 1)) g.fillRect(x, y + t - e, t, e); }
|
|
171
|
+
else { if (up(i - 1, j)) g.fillRect(x, y, e, t); if (up(i + 1, j)) g.fillRect(x + t - e, y, e, t); }
|
|
172
|
+
}
|
|
173
|
+
tiles.set(key, c);
|
|
174
|
+
return c;
|
|
175
|
+
}
|