azulejeria 1.0.1 → 2.0.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 (3) hide show
  1. package/README.md +56 -6
  2. package/package.json +1 -1
  3. package/src/azulejeria.js +334 -198
package/README.md CHANGED
@@ -11,10 +11,16 @@ drifts. Washes are laid thin twice so the glaze pools. Each tile gets its
11
11
  own mottled glaze, a slight turn, a slight shift, and a few of them craze.
12
12
 
13
13
  This package is the engine. You bring the motifs, the palettes and the
14
- presets. Two walls built on it: [Azulejería](https://stepinto.dev/art/azulejeria.html)
15
- (Talavera rosettes and Mudéjar strapwork) and [Jerez](https://stepinto.dev/art/jerez.html)
16
- (vines, horses and sherry). The design is written up
17
- [here](https://stepinto.dev/posts/tiles-painted-by-rule/).
14
+ presets, and, if the tile is not glazed, a material. Three walls built on
15
+ it: [Azulejería](https://stepinto.dev/art/azulejeria.html) (Talavera
16
+ rosettes and Mudéjar strapwork), [Jerez](https://stepinto.dev/art/jerez.html)
17
+ (vines, horses and sherry) and [Hidráulico](https://stepinto.dev/art/hidraulico.html)
18
+ (pigmented cement, pressed rather than painted). Underneath the wall is a
19
+ viewer, a canvas you paint any world into, with the drag, the pinch, the
20
+ wheel and the page chrome; [Alicatado](https://stepinto.dev/art/alicatado.html)
21
+ (cut tile set in lime) is the viewer with its own paint. The design is
22
+ written up [here](https://stepinto.dev/posts/tiles-painted-by-rule/) and
23
+ [here](https://stepinto.dev/posts/cut-tile-and-poured-cement/).
18
24
 
19
25
  ```
20
26
  npm install azulejeria
@@ -74,7 +80,7 @@ tap. Drive it from your own controls through `wall.state` and
74
80
 
75
81
  ## The parts
76
82
 
77
- **`createWall(canvas, { palettes, motifs, painters, presets })`** returns
83
+ **`createWall(canvas, { palettes, motifs, painters, presets, material })`** returns
78
84
  the wall. `wall.state` holds `seed`, `repeat` (`module`, `rotate`,
79
85
  `single` or `checker`), `pal`, `motif`, `density` (1 to 5), `hand` (0 to
80
86
  1, how far the brush drifts), `brush` (line weight), `scale` (pixels per
@@ -84,8 +90,27 @@ for things the wall draws itself (pan, grout, age). `wall.applyPreset(name)`,
84
90
  `wall.newDesign()` and `wall.zoomAt(x, y, factor)` do what they say. Set
85
91
  `wall.onChange(kind)` to be told about them.
86
92
 
93
+ **A material** changes what the tile is made of without touching what is
94
+ drawn on it. It is an object of optional hooks, and without one the tile
95
+ is tin-glazed. `ampOf(hand)` turns the hand slider into a wobble
96
+ amplitude (glaze: `0.012 * hand`). `shape(g, pts, col, b)`,
97
+ `line(g, pts, lw, close, b)` and `dot(g, x, y, r, col, alpha, b)` replace
98
+ the brush's strokes, so a cement tile can fill flat and bleed at the edge
99
+ where glaze would wash and ink. `surface(g, S, pal, rng)` lays the ground
100
+ after the glaze colour is filled (the blooms of tint, or grain).
101
+ `plain(g, S, pal, rng, o)` paints the tile a checker alternates with.
102
+ `lay` is `{ shift, turn }`, how far a tile strays from its cell at hand
103
+ one (glaze: `0.014` of a tile and `0.016` radians). `gapOf(S, state)` is
104
+ the grout in pixels. `age(ctx, t)` is drawn over each tile in its own
105
+ frame when age is on, with `t` carrying `i`, `j`, the tile's `rng`, its
106
+ drawn size `s`, the cell size `S`, `pal`, `state` and the tile's world
107
+ centre `cx`, `cy`, so wear can follow the line people walk. `finish(ctx,
108
+ W, H, state, pal)` is drawn over the whole wall last. None of the hooks
109
+ read the design's rng, so a material never moves a design.
110
+
87
111
  **`mountPanel(wall, { fileName, defaultPreset })`** wires the standard
88
- panel, which is a handful of elements found by id: selects `repeat`,
112
+ panel for a wall. It is `mountChrome` (below) with the wall's controls,
113
+ which are a handful of elements found by id: selects `repeat`,
89
114
  `motif` and `palette`; ranges `density`, `hand`, `brush` and `zoom` with
90
115
  `densityVal`, `handVal`, `brushVal` and `zoomVal` spans beside them;
91
116
  checkboxes `bands`, `grout` and `age`; buttons `newDesign` and `save`;
@@ -97,6 +122,31 @@ reads the query string, so `?preset=talavera` or
97
122
  `?seed=4242&repeat=rotate&pal=talavera&motif=rosette&density=5&age=1` is a
98
123
  shareable wall. Copy the markup from either of the two pages above.
99
124
 
125
+ **`createViewer(canvas, { paint, scale, minZoom, maxZoom, margin })`**
126
+ is what a wall is built on, and what any other world can be. `paint(g,
127
+ state, w, h, dpr, ox, oy)` paints the world into `g`, `w` by `h` css
128
+ pixels at `dpr`, with the world's origin at `(ox, oy)`. The viewer fills
129
+ the window, pans on drag, zooms on pinch or wheel, and calls
130
+ `onDoubleTap()` on a double tap. With a `margin` it paints into a buffer
131
+ that much larger than the window and only blits while you drag, which is
132
+ what a slow paint wants. `viewer.state` has `scale`, `panX` and `panY`;
133
+ add your own fields to it. Call `viewer.repaint()` when the world
134
+ changes and `viewer.moved()` when only the pan did.
135
+
136
+ **`mountChrome(viewer, spec)`** wires the same chrome around any viewer:
137
+ the panel, the tabs, the preset cards, the title that fades, the save
138
+ button, the query string. The spec names the presets, `applyPreset(name)`,
139
+ `thumb(ctx, settings)` to paint a card, and the `controls`: a list of
140
+ `{ id, key, q, kind, fmt, valId, keep, change }`, where `kind` is
141
+ `select`, `range` or `check`, `key` is the field of `viewer.state` (the
142
+ id by default), `q` its name in the query string (the key by default),
143
+ `fmt` renders a range's value beside it, `keep` leaves the preset marked
144
+ when the query string sets it, and `change(value)` is what to do after.
145
+ Then `newId` and `onNew` for the button that starts over, `mood(state)`
146
+ for the line under it, `query(q)` for anything else in the query string,
147
+ `fileName` and `suffix(state)` for the saved png, and `ready()` once
148
+ everything is applied. Alicatado is the worked example.
149
+
100
150
  **`azulejeria.css`** styles that markup. Colour it with the custom
101
151
  properties at the top of the file: `--az-bg`, `--az-title`,
102
152
  `--az-whisper`, `--az-hint`, `--az-glow`, `--az-glow-far`, `--az-panel`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "azulejeria",
3
- "version": "1.0.1",
3
+ "version": "2.0.0",
4
4
  "description": "Tin-glazed tiles painted by rule. A seeded canvas engine for Spanish azulejo walls: a diagonal-symmetric design, brushwork that drifts, washes that pool, and four ways to repeat the tile.",
5
5
  "keywords": ["canvas", "generative", "tiles", "azulejo", "mudejar", "sevilla", "pattern", "procedural", "art", "wallpaper"],
6
6
  "license": "MIT",
package/src/azulejeria.js CHANGED
@@ -9,10 +9,17 @@
9
9
  // This module is the engine: the seeded random, the brushwork (every
10
10
  // line a polyline with a slow wobble along its normal, washes laid
11
11
  // thin twice so the glaze pools), the tile (mottled glaze, the design
12
- // laid once or four times), the wall (tiles repeated with a symmetry,
13
- // each turned and shifted a little, some crazed) and the standard
14
- // control panel. Motifs, palettes and presets belong to the page that
15
- // uses it. See README.md for the shape of each.
12
+ // laid once or four times), the viewer (a canvas you paint a world
13
+ // into, with drag, pinch, wheel and the double tap), the wall (a
14
+ // viewer painting tiles repeated with a symmetry, each turned and
15
+ // shifted a little, some crazed) and the standard chrome. Motifs,
16
+ // palettes and presets belong to the page that uses it. See README.md
17
+ // for the shape of each.
18
+ //
19
+ // A material, optionally, changes what the tile is made of without
20
+ // touching what is drawn on it: how the ground is laid, how a shape
21
+ // is filled, how far a piece strays from the drawing, what the grout
22
+ // is, and what age does. Without one the tile is tin-glazed.
16
23
 
17
24
  // ------------------------------------------------------------- random ---
18
25
  export function mulberry32(a) {
@@ -210,17 +217,28 @@ export const PAINTERS = {
210
217
  },
211
218
  };
212
219
 
213
- // paints one design into the unit square of g (already scaled)
214
- export function paintDesign(g, els, pal, hand, lw, jseed, painters) {
220
+ // paints one design into the unit square of g (already scaled). The
221
+ // material, if given, may supply `ampOf(hand)`, `shape(g, pts, col, b)`,
222
+ // `line(g, pts, lw, close, b)` and `dot(g, x, y, r, col, a, b)`.
223
+ export function paintDesign(g, els, pal, hand, lw, jseed, painters, material) {
215
224
  const rng = mulberry32(jseed);
216
- const amp = 0.012 * hand;
225
+ const m = material || {};
226
+ const amp = m.ampOf ? m.ampOf(hand) : 0.012 * hand;
217
227
  const Q = Math.PI / 2, D = Q / 2;
218
228
  const dc = Math.cos(D), ds = Math.sin(D); // the diagonal
219
- const shape = (pts, col) => { wash(g, pts, col, rng); ink(g, pts, lw, pal, rng, true); };
220
- const dot = (x, y, r, col, a) => {
221
- g.beginPath(); g.arc(x, y, r, 0, 6.283);
222
- g.fillStyle = col || pal.ink; g.globalAlpha = a || 0.85; g.fill(); g.globalAlpha = 1;
223
- };
229
+ const b = { g, pal, lw, amp, rng, Q, D, dc, ds, col: pal.wash };
230
+ const shape = m.shape
231
+ ? (pts, col) => m.shape(g, pts, col, b)
232
+ : (pts, col) => { wash(g, pts, col, rng); ink(g, pts, lw, pal, rng, true); };
233
+ const line = m.line
234
+ ? (pts, w, close) => m.line(g, pts, w, close, b)
235
+ : (pts, w, close) => ink(g, pts, w, pal, rng, close);
236
+ const dot = m.dot
237
+ ? (x, y, r, col, a) => m.dot(g, x, y, r, col, a, b)
238
+ : (x, y, r, col, a) => {
239
+ g.beginPath(); g.arc(x, y, r, 0, 6.283);
240
+ g.fillStyle = col || pal.ink; g.globalAlpha = a || 0.85; g.fill(); g.globalAlpha = 1;
241
+ };
224
242
  const petal = (cx, cy, ang, rIn, rOut, wd, col) => shape(petalPts(cx, cy, ang, rIn, rOut, wd, amp, rng), col);
225
243
  const kite = (cx, cy, ang, rIn, rOut, wd, col) => shape(kitePts(cx, cy, ang, rIn, rOut, wd, amp, rng), col);
226
244
  const lobes = (cx, cy, r, a0, a1, count) => {
@@ -232,7 +250,7 @@ export function paintDesign(g, els, pal, hand, lw, jseed, painters) {
232
250
  }
233
251
  };
234
252
  const altOf = el => pal.accents.length ? pal.accents[((el.ai || 0) + 1) % pal.accents.length] : pal.ink;
235
- const b = { g, pal, lw, amp, rng, Q, D, dc, ds, shape, dot, petal, kite, lobes, altOf, col: pal.wash };
253
+ Object.assign(b, { shape, line, dot, petal, kite, lobes, altOf });
236
254
  for (const el of els) {
237
255
  const painter = painters[el.t];
238
256
  if (!painter) continue;
@@ -252,23 +270,28 @@ export function makeTile(o, S, k, jseed) {
252
270
  const g = c.getContext('2d');
253
271
  g.scale(k, k);
254
272
  const rng = mulberry32(jseed);
255
- const pal = o.pal;
273
+ const pal = o.pal, m = o.material || {};
256
274
  g.fillStyle = pal.glaze;
257
275
  g.fillRect(0, 0, S, S);
258
- for (let i = 0; i < 3; i++) {
259
- const x = rng() * S, y = rng() * S, rr = S * (0.3 + rng() * 0.5);
260
- const gr = g.createRadialGradient(x, y, 0, x, y, rr);
261
- gr.addColorStop(0, hexA(pal.tint, 0.22));
262
- gr.addColorStop(1, hexA(pal.tint, 0));
263
- g.fillStyle = gr;
264
- g.fillRect(0, 0, S, S);
276
+ if (m.surface) m.surface(g, S, pal, rng);
277
+ else {
278
+ for (let i = 0; i < 3; i++) {
279
+ const x = rng() * S, y = rng() * S, rr = S * (0.3 + rng() * 0.5);
280
+ const gr = g.createRadialGradient(x, y, 0, x, y, rr);
281
+ gr.addColorStop(0, hexA(pal.tint, 0.22));
282
+ gr.addColorStop(1, hexA(pal.tint, 0));
283
+ g.fillStyle = gr;
284
+ g.fillRect(0, 0, S, S);
285
+ }
286
+ // glaze thickens at the edge
287
+ g.strokeStyle = hexA(pal.ink, 0.06);
288
+ g.lineWidth = S * 0.06;
289
+ g.strokeRect(0, 0, S, S);
265
290
  }
266
- // glaze thickens at the edge
267
- g.strokeStyle = hexA(pal.ink, 0.06);
268
- g.lineWidth = S * 0.06;
269
- g.strokeRect(0, 0, S, S);
270
291
  g.lineCap = 'round'; g.lineJoin = 'round';
271
- if (o.plain) {
292
+ if (o.plain && m.plain) {
293
+ m.plain(g, S, pal, mulberry32(jseed + 3), o);
294
+ } else if (o.plain) {
272
295
  g.save(); g.translate(S / 2, S / 2); g.scale(S, S);
273
296
  const r2 = mulberry32(jseed + 3);
274
297
  const amp = 0.012 * o.hand;
@@ -282,12 +305,12 @@ export function makeTile(o, S, k, jseed) {
282
305
  let v = 0;
283
306
  for (const [fx, fy] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) {
284
307
  g.save(); g.translate(S / 2, S / 2); g.scale(fx * S / 2, fy * S / 2);
285
- paintDesign(g, o.design, pal, o.hand, 0.024 * o.brush, jseed + 17 + v++, o.painters);
308
+ paintDesign(g, o.design, pal, o.hand, 0.024 * o.brush, jseed + 17 + v++, o.painters, o.material);
286
309
  g.restore();
287
310
  }
288
311
  } else {
289
312
  g.save(); g.translate(S, S); g.scale(-S, -S);
290
- paintDesign(g, o.design, pal, o.hand, 0.012 * o.brush, jseed + 17, o.painters);
313
+ paintDesign(g, o.design, pal, o.hand, 0.012 * o.brush, jseed + 17, o.painters, o.material);
291
314
  g.restore();
292
315
  }
293
316
  return c;
@@ -301,7 +324,7 @@ export function tileOpts(cfg, s) {
301
324
  const pal = cfg.palettes[s.pal];
302
325
  const quarter = s.repeat === 'single' || s.repeat === 'checker';
303
326
  const design = makeDesign(s.seed, s.density, s.bands, quarter ? 1.35 : 1, cfg.motifs[s.motif]);
304
- return { pal, design, quarter, hand: s.hand, brush: s.brush, painters: cfg.painters };
327
+ return { pal, design, quarter, hand: s.hand, brush: s.brush, painters: cfg.painters, material: cfg.material };
305
328
  }
306
329
 
307
330
  // a small wall of four tiles, for a preset card
@@ -321,24 +344,152 @@ export function paintThumb(cfg, p, g, T, k) {
321
344
  }
322
345
  }
323
346
 
347
+ // ------------------------------------------------------------- viewer ---
348
+ // createViewer(canvas, { paint, scale, minZoom, maxZoom, margin }) is
349
+ // a canvas you paint a world into. It fills the window, and handles
350
+ // drag, pinch, wheel and the double tap. `paint(g, state, w, h, dpr,
351
+ // ox, oy)` paints the world into g, w by h css pixels at dpr, with
352
+ // the world's origin at (ox, oy). With a `margin` the world is painted
353
+ // into a buffer that much larger than the window and only blitted
354
+ // while you drag, which is what a slow paint wants; without one it is
355
+ // painted straight to the canvas every time. `state` carries `scale`,
356
+ // `panX` and `panY`, plus whatever the page adds. Call `repaint()`
357
+ // when the world changes and `moved()` when only the pan did. Set
358
+ // `onChange(kind)` to hear 'zoom', `onInteract()` to hear the first
359
+ // touch, `onDoubleTap()` for the double tap and `onZoom()` for the end
360
+ // of a zoom.
361
+ export function createViewer(canvas, opts) {
362
+ opts = opts || {};
363
+ const ctx = canvas.getContext('2d');
364
+ const DPR = Math.min(window.devicePixelRatio || 1, 2);
365
+ const state = { scale: opts.scale || 120, panX: 0, panY: 0 };
366
+ const viewer = { canvas, ctx, state, W: 0, H: 0, DPR, paint: opts.paint,
367
+ minZoom: opts.minZoom || 40, maxZoom: opts.maxZoom || 260, margin: opts.margin || 0,
368
+ preset: '', onChange: null, onInteract: null, onDoubleTap: null, onZoom: null };
369
+ let dirty = true, needPaint = true, buf = null, bg = null, bufPan = null;
370
+
371
+ function render() {
372
+ const W = viewer.W, H = viewer.H, M = viewer.margin;
373
+ if (!M) { viewer.paint(ctx, state, W, H, DPR, W / 2 + state.panX, H / 2 + state.panY); return; }
374
+ if (needPaint || !bufPan) {
375
+ if (!buf) { buf = document.createElement('canvas'); bg = buf.getContext('2d'); }
376
+ buf.width = Math.ceil((W + 2 * M) * DPR); buf.height = Math.ceil((H + 2 * M) * DPR);
377
+ viewer.paint(bg, state, W + 2 * M, H + 2 * M, DPR, W / 2 + M + state.panX, H / 2 + M + state.panY);
378
+ bufPan = [state.panX, state.panY];
379
+ needPaint = false;
380
+ }
381
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
382
+ ctx.drawImage(buf, (state.panX - bufPan[0] - M) * DPR, (state.panY - bufPan[1] - M) * DPR);
383
+ }
384
+ function repaint() { needPaint = true; dirty = true; }
385
+ function moved() {
386
+ const M = viewer.margin;
387
+ if (M && bufPan && (Math.abs(state.panX - bufPan[0]) > M * 0.9 || Math.abs(state.panY - bufPan[1]) > M * 0.9)) needPaint = true;
388
+ dirty = true;
389
+ }
390
+ function frame() {
391
+ if (dirty) { dirty = false; render(); }
392
+ requestAnimationFrame(frame);
393
+ }
394
+ function resize() {
395
+ viewer.W = window.innerWidth; viewer.H = window.innerHeight;
396
+ canvas.width = Math.round(viewer.W * DPR); canvas.height = Math.round(viewer.H * DPR);
397
+ repaint();
398
+ }
399
+ window.addEventListener('resize', resize);
400
+
401
+ const changed = kind => { if (viewer.onChange) viewer.onChange(kind); };
402
+
403
+ function zoomAt(sx, sy, factor) {
404
+ const next = Math.max(viewer.minZoom, Math.min(viewer.maxZoom, state.scale * factor));
405
+ factor = next / state.scale;
406
+ // keep the world point under (sx, sy) fixed while the scale changes
407
+ state.panX = sx - viewer.W / 2 - (sx - viewer.W / 2 - state.panX) * factor;
408
+ state.panY = sy - viewer.H / 2 - (sy - viewer.H / 2 - state.panY) * factor;
409
+ state.scale = next;
410
+ repaint();
411
+ if (viewer.onZoom) viewer.onZoom();
412
+ changed('zoom');
413
+ }
414
+
415
+ // drag to pan, pinch or wheel to zoom, double-tap for whatever the page wants
416
+ const pointers = new Map();
417
+ let pinchDist = 0, pinchMid = null, lastTap = 0, lastTapX = 0, lastTapY = 0;
418
+
419
+ canvas.addEventListener('pointerdown', e => {
420
+ canvas.setPointerCapture(e.pointerId);
421
+ pointers.set(e.pointerId, [e.clientX, e.clientY]);
422
+ if (pointers.size === 1) {
423
+ const now = performance.now();
424
+ if (now - lastTap < 320 && Math.hypot(e.clientX - lastTapX, e.clientY - lastTapY) < 40) {
425
+ if (viewer.onDoubleTap) viewer.onDoubleTap();
426
+ lastTap = 0;
427
+ } else { lastTap = now; lastTapX = e.clientX; lastTapY = e.clientY; }
428
+ } else if (pointers.size === 2) {
429
+ const [a, b] = [...pointers.values()];
430
+ pinchDist = Math.hypot(a[0] - b[0], a[1] - b[1]);
431
+ pinchMid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
432
+ }
433
+ if (viewer.onInteract) viewer.onInteract();
434
+ });
435
+ canvas.addEventListener('pointermove', e => {
436
+ if (!pointers.has(e.pointerId)) return;
437
+ const prev = pointers.get(e.pointerId);
438
+ pointers.set(e.pointerId, [e.clientX, e.clientY]);
439
+ if (pointers.size === 1) {
440
+ state.panX += e.clientX - prev[0];
441
+ state.panY += e.clientY - prev[1];
442
+ moved();
443
+ } else if (pointers.size === 2) {
444
+ const [a, b] = [...pointers.values()];
445
+ const dist = Math.hypot(a[0] - b[0], a[1] - b[1]);
446
+ const mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
447
+ if (pinchMid) { state.panX += mid[0] - pinchMid[0]; state.panY += mid[1] - pinchMid[1]; }
448
+ if (pinchDist > 0) zoomAt(mid[0], mid[1], dist / pinchDist);
449
+ else moved();
450
+ pinchDist = dist; pinchMid = mid;
451
+ }
452
+ });
453
+ const endPointer = e => {
454
+ pointers.delete(e.pointerId);
455
+ if (pointers.size < 2) { pinchDist = 0; pinchMid = null; }
456
+ };
457
+ canvas.addEventListener('pointerup', endPointer);
458
+ canvas.addEventListener('pointercancel', endPointer);
459
+ canvas.addEventListener('wheel', e => {
460
+ e.preventDefault();
461
+ zoomAt(e.clientX, e.clientY, e.deltaY < 0 ? 1.08 : 1 / 1.08);
462
+ }, { passive: false });
463
+
464
+ Object.assign(viewer, { render, repaint, moved, zoomAt, resize });
465
+ resize();
466
+ requestAnimationFrame(frame);
467
+ return viewer;
468
+ }
469
+
324
470
  // --------------------------------------------------------------- wall ---
325
- // createWall(canvas, { palettes, motifs, painters, presets }) paints a
326
- // wall that fills the canvas, and handles drag, pinch, wheel and the
327
- // double tap. It returns the wall: `state` to read or change, then
471
+ // createWall(canvas, { palettes, motifs, painters, presets, material })
472
+ // is a viewer that paints a wall of tiles. It returns the wall, which
473
+ // is the viewer with more on it: `state` to read or change, then
328
474
  // `rebuild(true)` to repaint the tiles or `rebuild(false)` to redraw
329
475
  // the wall with the tiles it has. `applyPreset(name)`, `newDesign()`
330
476
  // and `zoomAt(x, y, factor)` do the usual things. Set `onChange(kind)`
331
477
  // to hear about them ('preset', 'design', 'zoom') and `onInteract()`
332
- // to hear the first touch.
478
+ // to hear the first touch. `material`, if given, may supply the
479
+ // painting hooks above plus `lay` ({ shift, turn }, how far a tile
480
+ // strays from its cell), `gapOf(S, state)` (the grout, in pixels),
481
+ // `age(ctx, t)` (what age does to one tile, drawn over it in the
482
+ // tile's own frame) and `finish(ctx, W, H, state, pal)` (over the wall).
333
483
  export function createWall(canvas, cfg) {
334
- const ctx = canvas.getContext('2d');
335
- const DPR = Math.min(window.devicePixelRatio || 1, 2);
336
484
  const palettes = cfg.palettes, motifs = cfg.motifs, presets = cfg.presets || {};
337
485
  const painters = cfg.painters || PAINTERS;
486
+ const material = cfg.material || null, m = material || {};
487
+ const lay = m.lay || { shift: 0.014, turn: 0.016 };
338
488
  const firstMotif = Object.keys(motifs)[0];
339
489
  for (const p of Object.values(presets)) if (!p.motif) p.motif = firstMotif;
340
490
 
341
- const state = {
491
+ const wall = createViewer(canvas, { paint, scale: 120, minZoom: 40, maxZoom: 260 });
492
+ const state = Object.assign(wall.state, {
342
493
  seed: 1,
343
494
  repeat: 'module', // module | rotate | single | checker
344
495
  pal: Object.keys(palettes)[0],
@@ -346,16 +497,15 @@ export function createWall(canvas, cfg) {
346
497
  density: 3, // how much of the design is drawn, 1..5
347
498
  hand: 0.5, // wobble of the brush
348
499
  brush: 1, // line weight
349
- scale: 120, // pixels per tile
350
- panX: 0, panY: 0,
351
500
  bands: true,
352
501
  grout: true,
353
502
  age: false,
354
- };
355
- const wall = { canvas, ctx, state, palettes, motifs, painters, presets, preset: '', W: 0, H: 0, onChange: null, onInteract: null };
356
- const tcfg = { palettes, motifs, painters };
503
+ });
504
+ Object.assign(wall, { palettes, motifs, painters, material, presets });
505
+ const tcfg = { palettes, motifs, painters, material };
506
+ const DPR = wall.DPR;
357
507
 
358
- let tiles = { A: [], B: [] }, needTiles = true, dirty = true;
508
+ let tiles = { A: [], B: [] }, needTiles = true;
359
509
 
360
510
  function buildTiles() {
361
511
  const o = tileOpts(tcfg, state);
@@ -367,18 +517,15 @@ export function createWall(canvas, cfg) {
367
517
  needTiles = false;
368
518
  }
369
519
 
370
- function render() {
520
+ function paint(ctx, st, W, H, dpr, ox, oy) {
371
521
  if (needTiles) buildTiles();
372
522
  const pal = palettes[state.pal];
373
- const W = wall.W, H = wall.H;
374
- ctx.setTransform(1, 0, 0, 1, 0, 0);
523
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
375
524
  ctx.fillStyle = pal.grout;
376
- ctx.fillRect(0, 0, canvas.width, canvas.height);
377
- ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
525
+ ctx.fillRect(0, 0, W, H);
378
526
 
379
527
  const S = state.scale;
380
- const gap = state.grout ? Math.max(1.2, S * 0.022) : 0;
381
- const ox = W / 2 + state.panX, oy = H / 2 + state.panY;
528
+ const gap = state.grout ? (m.gapOf ? m.gapOf(S, state) : Math.max(1.2, S * 0.022)) : 0;
382
529
  const i0 = Math.floor(-ox / S) - 1, i1 = Math.ceil((W - ox) / S) + 1;
383
530
  const j0 = Math.floor(-oy / S) - 1, j1 = Math.ceil((H - oy) / S) + 1;
384
531
  const s = S - gap;
@@ -392,11 +539,13 @@ export function createWall(canvas, cfg) {
392
539
  else if (state.repeat === 'checker' && ((i + j) & 1)) set = tiles.B;
393
540
  const img = set[Math.floor(rng() * set.length)];
394
541
  ctx.save();
395
- ctx.translate(cx + (rng() - 0.5) * S * 0.014 * state.hand, cy + (rng() - 0.5) * S * 0.014 * state.hand);
396
- ctx.rotate(rot + (rng() - 0.5) * 0.016 * state.hand);
542
+ ctx.translate(cx + (rng() - 0.5) * S * lay.shift * state.hand, cy + (rng() - 0.5) * S * lay.shift * state.hand);
543
+ ctx.rotate(rot + (rng() - 0.5) * lay.turn * state.hand);
397
544
  ctx.scale(fx, fy);
398
545
  ctx.drawImage(img, -s / 2, -s / 2, s, s);
399
- if (state.age) {
546
+ if (state.age && m.age) {
547
+ m.age(ctx, { i, j, rng, s, S, pal, state, cx: (i + 0.5) * S, cy: (j + 0.5) * S, fx, fy, rot });
548
+ } else if (state.age) {
400
549
  // a warm cast on some, a craze on a few, a chipped corner on fewer
401
550
  if (rng() < 0.5) { ctx.fillStyle = `rgba(120, 85, 30, ${0.04 + rng() * 0.1})`; ctx.fillRect(-s / 2, -s / 2, s, s); }
402
551
  if (rng() < 0.18) {
@@ -423,26 +572,14 @@ export function createWall(canvas, cfg) {
423
572
  ctx.restore();
424
573
  }
425
574
  }
426
- if (state.age) {
575
+ if (m.finish) m.finish(ctx, W, H, state, pal);
576
+ else if (state.age) {
427
577
  ctx.fillStyle = 'rgba(90, 60, 20, 0.05)';
428
578
  ctx.fillRect(0, 0, W, H);
429
579
  }
430
580
  }
431
581
 
432
- function rebuild(rebuildTiles) { if (rebuildTiles) needTiles = true; dirty = true; }
433
- function frame() {
434
- if (dirty) { dirty = false; render(); }
435
- requestAnimationFrame(frame);
436
- }
437
- function resize() {
438
- wall.W = window.innerWidth; wall.H = window.innerHeight;
439
- canvas.width = Math.round(wall.W * DPR); canvas.height = Math.round(wall.H * DPR);
440
- rebuild(false);
441
- }
442
- window.addEventListener('resize', resize);
443
- resize();
444
- requestAnimationFrame(frame);
445
-
582
+ function rebuild(rebuildTiles) { if (rebuildTiles) needTiles = true; wall.repaint(); }
446
583
  const changed = kind => { if (wall.onChange) wall.onChange(kind); };
447
584
 
448
585
  function applyPreset(name) {
@@ -461,118 +598,70 @@ export function createWall(canvas, cfg) {
461
598
  rebuild(true);
462
599
  changed('design');
463
600
  }
601
+ // tiles are cached at a pixel size: repaint them once the zoom settles
602
+ let zoomTimer = 0;
603
+ wall.onZoom = () => { clearTimeout(zoomTimer); zoomTimer = setTimeout(() => rebuild(true), 160); };
604
+ wall.onDoubleTap = newDesign;
464
605
 
465
- // drag to pan, pinch or wheel to zoom, double-tap for a new design
466
- const pointers = new Map();
467
- let pinchDist = 0, pinchMid = null, lastTap = 0, lastTapX = 0, lastTapY = 0, zoomTimer = 0;
468
-
469
- function zoomAt(sx, sy, factor) {
470
- const next = Math.max(40, Math.min(260, state.scale * factor));
471
- factor = next / state.scale;
472
- state.panX = sx - wall.W / 2 - (sx - wall.W / 2 - state.panX) * factor;
473
- state.panY = sy - wall.H / 2 - (sy - wall.H / 2 - state.panY) * factor;
474
- state.scale = next;
475
- // tiles are cached at a pixel size: repaint them once the zoom settles
476
- clearTimeout(zoomTimer);
477
- zoomTimer = setTimeout(() => rebuild(true), 160);
478
- rebuild(false);
479
- changed('zoom');
480
- }
481
-
482
- canvas.addEventListener('pointerdown', e => {
483
- canvas.setPointerCapture(e.pointerId);
484
- pointers.set(e.pointerId, [e.clientX, e.clientY]);
485
- if (pointers.size === 1) {
486
- const now = performance.now();
487
- if (now - lastTap < 320 && Math.hypot(e.clientX - lastTapX, e.clientY - lastTapY) < 40) {
488
- newDesign();
489
- lastTap = 0;
490
- } else { lastTap = now; lastTapX = e.clientX; lastTapY = e.clientY; }
491
- } else if (pointers.size === 2) {
492
- const [a, b] = [...pointers.values()];
493
- pinchDist = Math.hypot(a[0] - b[0], a[1] - b[1]);
494
- pinchMid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
495
- }
496
- if (wall.onInteract) wall.onInteract();
497
- });
498
- canvas.addEventListener('pointermove', e => {
499
- if (!pointers.has(e.pointerId)) return;
500
- const prev = pointers.get(e.pointerId);
501
- pointers.set(e.pointerId, [e.clientX, e.clientY]);
502
- if (pointers.size === 1) {
503
- state.panX += e.clientX - prev[0];
504
- state.panY += e.clientY - prev[1];
505
- rebuild(false);
506
- } else if (pointers.size === 2) {
507
- const [a, b] = [...pointers.values()];
508
- const dist = Math.hypot(a[0] - b[0], a[1] - b[1]);
509
- const mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
510
- if (pinchMid) { state.panX += mid[0] - pinchMid[0]; state.panY += mid[1] - pinchMid[1]; }
511
- if (pinchDist > 0) zoomAt(mid[0], mid[1], dist / pinchDist);
512
- else rebuild(false);
513
- pinchDist = dist; pinchMid = mid;
514
- }
515
- });
516
- const endPointer = e => {
517
- pointers.delete(e.pointerId);
518
- if (pointers.size < 2) { pinchDist = 0; pinchMid = null; }
519
- };
520
- canvas.addEventListener('pointerup', endPointer);
521
- canvas.addEventListener('pointercancel', endPointer);
522
- canvas.addEventListener('wheel', e => {
523
- e.preventDefault();
524
- zoomAt(e.clientX, e.clientY, e.deltaY < 0 ? 1.08 : 1 / 1.08);
525
- }, { passive: false });
526
-
527
- Object.assign(wall, { rebuild, render, applyPreset, newDesign, zoomAt, resize, DPR });
606
+ Object.assign(wall, { rebuild, applyPreset, newDesign });
607
+ wall.rebuild(false);
528
608
  return wall;
529
609
  }
530
610
 
531
- // -------------------------------------------------------------- panel ---
532
- // mountPanel(wall, { fileName, defaultPreset }) wires the standard
533
- // control panel: the elements with the ids repeat, motif, palette,
534
- // density, hand, brush, zoom, bands, grout, age, newDesign, mood,
535
- // save, panel, panelHead, panelToggle, presetsBody, panelBody, the
536
- // `.tab` buttons, the `.card[data-preset]` cards (each with a canvas
537
- // for its thumbnail) and the `#title` overlay. It reads the query
538
- // string (?preset=, ?seed=, ?repeat=, ?pal=, ?motif=, ?density=,
539
- // ?hand=, ?zoom=, ?bands=0, ?age=1) and applies it. Anything missing
540
- // from the page is skipped.
541
- export function mountPanel(wall, opts) {
542
- opts = opts || {};
543
- const doc = opts.document || document;
611
+ // ------------------------------------------------------------- chrome ---
612
+ // mountChrome(viewer, spec) wires the standard page chrome around any
613
+ // viewer: the `#panel` with `#panelHead` and `#panelToggle`, the `.tab`
614
+ // buttons switching `#presetsBody` and `#panelBody`, the
615
+ // `.card[data-preset]` cards (each holding a canvas for its thumbnail),
616
+ // the `#title` overlay that fades on first touch, the `#save` button,
617
+ // the `#mood` line, and the controls the spec lists. It reads the
618
+ // query string and applies it. Anything missing from the page is
619
+ // skipped.
620
+ //
621
+ // The spec: `presets` (name -> settings), `applyPreset(name)`,
622
+ // `thumb(ctx, settings)` to paint a 52px card, `controls`, a list of
623
+ // `{ id, key, q, kind, fmt, valId, keep, change }`: `kind` is 'select',
624
+ // 'range' or 'check'; `key` is the field of `viewer.state` (the id by
625
+ // default); `q` is its name in the query string (the key by default);
626
+ // `fmt` renders the value beside a range; `valId` is where
627
+ // (`<id>Val` by default); `keep` leaves the preset marked when the
628
+ // query string sets it; `change(value)` is what to do after. Then
629
+ // `newId` and `onNew` for the button that starts over, `mood(state)`
630
+ // for the line under it, `query(q)` for anything else in the query
631
+ // string, `fileName` and `suffix(state)` for the saved png, and
632
+ // `ready()` once everything is applied.
633
+ export function mountChrome(viewer, spec) {
634
+ const doc = spec.document || document;
544
635
  const $ = id => doc.getElementById(id);
545
- const { state, presets } = wall;
636
+ const { state } = viewer;
637
+ const presets = spec.presets || {};
638
+ const controls = spec.controls || [];
546
639
  const presetCards = doc.querySelectorAll('.card[data-preset]');
547
640
  const markPreset = name => presetCards.forEach(c => c.classList.toggle('on', c.dataset.preset === name));
548
- const set = (id, v) => { const el = $(id); if (el) el.value = v; };
549
641
  const text = (id, v) => { const el = $(id); if (el) el.textContent = v; };
550
- const check = (id, v) => { const el = $(id); if (el) el.checked = v; };
551
-
552
- function syncZoom() {
553
- set('zoom', Math.round(state.scale)); text('zoomVal', Math.round(state.scale) + 'px');
554
- }
555
- function syncControls() {
556
- set('repeat', state.repeat);
557
- set('palette', state.pal);
558
- set('motif', state.motif);
559
- set('density', state.density); text('densityVal', state.density);
560
- set('hand', state.hand); text('handVal', Number(state.hand).toFixed(2));
561
- set('brush', state.brush); text('brushVal', Number(state.brush).toFixed(1));
562
- syncZoom();
563
- check('bands', state.bands); check('grout', state.grout); check('age', state.age);
564
- text('mood', 'design nº ' + state.seed);
565
- markPreset(wall.preset);
642
+ const valId = c => c.valId || c.id + 'Val';
643
+ const keyOf = c => c.key || c.id;
644
+
645
+ function sync() {
646
+ for (const c of controls) {
647
+ const el = $(c.id), v = state[keyOf(c)];
648
+ if (!el) continue;
649
+ if (c.kind === 'check') el.checked = !!v;
650
+ else el.value = v;
651
+ if (c.kind === 'range') text(valId(c), c.fmt ? c.fmt(v) : String(v));
652
+ }
653
+ if (spec.mood) text('mood', spec.mood(state));
654
+ markPreset(viewer.preset);
566
655
  }
567
- wall.onChange = kind => { if (kind === 'zoom') syncZoom(); else syncControls(); };
656
+ viewer.onChange = () => sync();
568
657
 
569
- presetCards.forEach(c => c.addEventListener('click', () => wall.applyPreset(c.dataset.preset)));
658
+ presetCards.forEach(c => c.addEventListener('click', () => { spec.applyPreset(c.dataset.preset); sync(); }));
570
659
 
571
- // each preset card shows its own wall, four tiles of it
572
- for (const card of presetCards) {
660
+ // each preset card shows its own small piece of wall
661
+ if (spec.thumb) for (const card of presetCards) {
573
662
  const p = presets[card.dataset.preset], tc = card.querySelector('canvas');
574
663
  if (!p || !tc) continue;
575
- paintThumb(wall, p, tc.getContext('2d'), 52, 2);
664
+ spec.thumb(tc.getContext('2d'), p);
576
665
  }
577
666
 
578
667
  // tabs
@@ -586,25 +675,27 @@ export function mountPanel(wall, opts) {
586
675
  });
587
676
  }
588
677
 
589
- const edited = () => { wall.preset = ''; markPreset(''); };
678
+ const edited = () => { viewer.preset = ''; markPreset(''); };
679
+ const parse = (c, el) => c.kind === 'check' ? el.checked : c.kind === 'range' ? (c.int ? parseInt(el.value, 10) : parseFloat(el.value)) : el.value;
680
+ for (const c of controls) {
681
+ const el = $(c.id);
682
+ if (!el) continue;
683
+ el.addEventListener(c.kind === 'range' ? 'input' : 'change', () => {
684
+ const v = parse(c, el);
685
+ state[keyOf(c)] = v;
686
+ if (c.kind === 'range') text(valId(c), c.fmt ? c.fmt(v) : String(v));
687
+ if (!c.keep) edited();
688
+ if (c.change) c.change(v);
689
+ });
690
+ }
590
691
  const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); };
591
- on('repeat', 'change', e => { state.repeat = e.target.value; edited(); wall.rebuild(true); });
592
- on('palette', 'change', e => { state.pal = e.target.value; edited(); wall.rebuild(true); });
593
- on('motif', 'change', e => { state.motif = e.target.value; edited(); wall.rebuild(true); });
594
- on('density', 'input', e => { state.density = parseInt(e.target.value, 10); text('densityVal', state.density); edited(); wall.rebuild(true); });
595
- on('hand', 'input', e => { state.hand = parseFloat(e.target.value); text('handVal', state.hand.toFixed(2)); edited(); wall.rebuild(true); });
596
- on('brush', 'input', e => { state.brush = parseFloat(e.target.value); text('brushVal', state.brush.toFixed(1)); edited(); wall.rebuild(true); });
597
- on('zoom', 'input', e => { state.scale = parseInt(e.target.value, 10); text('zoomVal', state.scale + 'px'); edited(); wall.rebuild(true); });
598
- on('bands', 'change', e => { state.bands = e.target.checked; edited(); wall.rebuild(true); });
599
- on('grout', 'change', e => { state.grout = e.target.checked; wall.rebuild(false); });
600
- on('age', 'change', e => { state.age = e.target.checked; wall.rebuild(false); });
601
- on('newDesign', 'click', () => wall.newDesign());
692
+ if (spec.onNew) on(spec.newId || 'newDesign', 'click', () => { spec.onNew(); sync(); });
602
693
 
603
694
  on('save', 'click', () => {
604
- wall.canvas.toBlob(blob => {
695
+ viewer.canvas.toBlob(blob => {
605
696
  const a = doc.createElement('a');
606
697
  a.href = URL.createObjectURL(blob);
607
- a.download = (opts.fileName || 'wall') + '-' + state.seed + '.png';
698
+ a.download = (spec.fileName || 'wall') + '-' + (spec.suffix ? spec.suffix(state) : state.seed) + '.png';
608
699
  a.click();
609
700
  setTimeout(() => URL.revokeObjectURL(a.href), 4000);
610
701
  });
@@ -616,6 +707,7 @@ export function mountPanel(wall, opts) {
616
707
  panel.classList.toggle('closed');
617
708
  text('panelToggle', panel.classList.contains('closed') ? '+' : '−');
618
709
  });
710
+ // on a phone the open panel would cover the art; start it folded
619
711
  if (window.innerWidth < 520) {
620
712
  panel.classList.add('closed');
621
713
  text('panelToggle', '+');
@@ -629,25 +721,69 @@ export function mountPanel(wall, opts) {
629
721
  titleGone = true;
630
722
  if (titleEl) titleEl.classList.add('gone');
631
723
  }
632
- wall.onInteract = dismissTitle;
724
+ viewer.onInteract = dismissTitle;
633
725
  setTimeout(dismissTitle, 7000);
634
726
 
635
- // shareable settings, e.g. ?preset=triana or ?seed=4242&repeat=rotate&pal=coimbra&motif=laceria
727
+ // the query string: a preset, then any control by its key, within
728
+ // what the page's own element allows
636
729
  const q = new URLSearchParams(location.search);
637
- wall.applyPreset(q.get('preset') || opts.defaultPreset || Object.keys(presets)[0]);
638
- if (q.has('seed')) { state.seed = parseInt(q.get('seed'), 10) || state.seed; wall.preset = ''; }
639
- if (q.has('repeat') && REPEATS.includes(q.get('repeat'))) state.repeat = q.get('repeat');
640
- if (q.has('pal') && wall.palettes[q.get('pal')]) state.pal = q.get('pal');
641
- if (q.has('motif') && wall.motifs[q.get('motif')]) state.motif = q.get('motif');
642
- const de = parseInt(q.get('density'), 10);
643
- if (de >= 1 && de <= 5) state.density = de;
644
- const ha = parseFloat(q.get('hand'));
645
- if (ha >= 0 && ha <= 1) state.hand = ha;
646
- const z = parseInt(q.get('zoom'), 10);
647
- if (z >= 40 && z <= 260) state.scale = z;
648
- if (q.get('bands') === '0') state.bands = false;
649
- if (q.get('age') === '1') state.age = true;
650
- syncControls();
651
- wall.rebuild(true);
652
- return { syncControls, dismissTitle };
730
+ spec.applyPreset(q.get('preset') || spec.defaultPreset || Object.keys(presets)[0]);
731
+ for (const c of controls) {
732
+ const k = keyOf(c), qn = c.q || k;
733
+ if (!q.has(qn)) continue;
734
+ const el = $(c.id), raw = q.get(qn);
735
+ let v;
736
+ if (c.kind === 'check') { if (raw !== '0' && raw !== '1') continue; v = raw === '1'; }
737
+ else if (c.kind === 'range') {
738
+ v = c.int ? parseInt(raw, 10) : parseFloat(raw);
739
+ if (!(v >= parseFloat(el ? el.min : -Infinity) && v <= parseFloat(el ? el.max : Infinity))) continue;
740
+ } else {
741
+ if (el && ![...el.options].some(o => o.value === raw)) continue;
742
+ v = raw;
743
+ }
744
+ state[k] = v;
745
+ if (!c.keep) viewer.preset = '';
746
+ }
747
+ if (spec.query) spec.query(q);
748
+ sync();
749
+ if (spec.ready) spec.ready();
750
+ return { sync, dismissTitle, markPreset };
751
+ }
752
+
753
+ // -------------------------------------------------------------- panel ---
754
+ // mountPanel(wall, { fileName, defaultPreset }) is mountChrome with the
755
+ // tile wall's controls: selects `repeat`, `motif` and `palette`; ranges
756
+ // `density`, `hand`, `brush` and `zoom` with `densityVal`, `handVal`,
757
+ // `brushVal` and `zoomVal` beside them; checkboxes `bands`, `grout` and
758
+ // `age`; the `newDesign` button. The query string takes ?preset=,
759
+ // ?seed=, ?repeat=, ?pal=, ?motif=, ?density=, ?hand=, ?zoom=, ?bands=0
760
+ // and ?age=1.
761
+ export function mountPanel(wall, opts) {
762
+ opts = opts || {};
763
+ const { state } = wall;
764
+ const tiles = () => wall.rebuild(true), face = () => wall.rebuild(false);
765
+ return mountChrome(wall, {
766
+ document: opts.document,
767
+ presets: wall.presets,
768
+ defaultPreset: opts.defaultPreset,
769
+ applyPreset: name => wall.applyPreset(name),
770
+ thumb: (g, p) => paintThumb(wall, p, g, 52, 2),
771
+ controls: [
772
+ { id: 'repeat', kind: 'select', change: tiles },
773
+ { id: 'palette', key: 'pal', kind: 'select', change: tiles },
774
+ { id: 'motif', kind: 'select', change: tiles },
775
+ { id: 'density', kind: 'range', int: true, change: tiles },
776
+ { id: 'hand', kind: 'range', fmt: v => Number(v).toFixed(2), change: tiles },
777
+ { id: 'brush', kind: 'range', fmt: v => Number(v).toFixed(1), change: tiles },
778
+ { id: 'zoom', key: 'scale', q: 'zoom', kind: 'range', int: true, fmt: v => Math.round(v) + 'px', keep: true, change: tiles },
779
+ { id: 'bands', kind: 'check', keep: true, change: tiles },
780
+ { id: 'grout', kind: 'check', keep: true, change: face },
781
+ { id: 'age', kind: 'check', keep: true, change: face },
782
+ ],
783
+ newId: 'newDesign', onNew: () => wall.newDesign(),
784
+ mood: s => 'design nº ' + s.seed,
785
+ query: q => { if (q.has('seed')) { state.seed = parseInt(q.get('seed'), 10) || state.seed; wall.preset = ''; } },
786
+ fileName: opts.fileName,
787
+ ready: tiles,
788
+ });
653
789
  }