anvilsign in

collin/mahjong

1import backUrl from '../assets/back.png';
2import tilesUrl from '../assets/tiles.svg';
3import { SPRITE_COL, SPRITE_COLS } from '../game/tiles';
4import { zScale } from '../table/physics';
5
6/**
7 * Drawing one tile, and the shadow under it.
8 *
9 * Pulled out of the renderer so the numbers in `LOOK` can be turned by hand
10 * against the real thing rather than guessed at: `tiles.html` is a page of
11 * these at every angle and size with a slider on each of them. Nothing in here
12 * knows about the game, the pool or the table — it is a tile, a canvas, and how
13 * a tile is meant to look on cloth.
14 */
15
16/** The art, as something canvas can draw. */
17export interface Art {
18 faces: HTMLImageElement | null;
19 back: HTMLImageElement | null;
20}
21
22/**
23 * Every number that decides how a tile reads. Defaults are what the table uses;
24 * the tuner hands in its own while it is being turned.
25 */
26export interface TileLook {
27 /**
28 * The line round the outside.
29 *
30 * The art already has one — a single black pixel all the way round each 128px
31 * cell — but a tile in the middle is drawn about a quarter of that, and
32 * `drawImage` box-filters that one pixel down to about a quarter of its
33 * strength. Drawn as a stroke instead of relying on the bitmap, it holds at
34 * any size.
35 */
36 edgeLine: string;
37 edgeWidth: number;
38 /**
39 * How thick a tile stands, as a fraction of its width, and where the light
40 * is — clockwise from straight up the screen, in degrees.
41 *
42 * The sides are *worked out*, not painted. The art has a bevel baked into it,
43 * which was fine while every tile stood the same way up and wrong the moment
44 * they were scattered: a painted highlight turns with the tile, so a pool of
45 * discards ended up with a different light on each one. These are the four
46 * real edges of the rotated rectangle, extruded down the screen, and only the
47 * ones actually facing you are drawn — so a tile at any angle is lit by the
48 * one light over the table.
49 */
50 depth: number;
51 /**
52 * Which way the tile's base sits from its face, clockwise from up. Down and
53 * to the left is what the art itself uses, and it is what lets you see two
54 * sides of a tile at once rather than one.
55 */
56 depthAngle: number;
57 lightAngle: number;
58 /**
59 * How much of each cell is the *painted* side, and how much is its outline,
60 * both as a fraction of the cell's width.
61 *
62 * The sheet is not a picture of a tile's face — it is a picture of a whole
63 * tile, drawn in the same oblique projection as this, with its own sides
64 * painted down the left and along the bottom and its own light coming from
65 * the top right. That was fine while every tile stood the same way up. Turned,
66 * it is a pre-rendered solid being spun, which is why a scattered pool looked
67 * like every tile had its own private sun. Cropped back to the flat face, the
68 * art is a face and the solid is worked out here.
69 */
70 artBevel: number;
71 artEdge: number;
72 /** The tile's own ivory, full on the light and full away from it. */
73 sideLight: string;
74 sideDark: string;
75 /** The shadow: how dark at rest, how much height washes it out, how far it is
76 * offset across and down, how wide it spreads, and how soft it is. */
77 shadowAlpha: number;
78 shadowFade: number;
79 shadowAcross: number;
80 shadowDown: number;
81 shadowDownZ: number;
82 shadowSpread: number;
83 shadowBlur: number;
84}
85
86export const LOOK: TileLook = {
87 edgeLine: 'rgba(52, 43, 29, 0.55)',
88 edgeWidth: 1,
89 depth: 0.125,
90 depthAngle: 225,
91 lightAngle: 35,
92 // The two greys the art shades its own sides with, so a tile is the tile it
93 // always was — only lit by one sun instead of one each.
94 sideLight: '#d7d7d7',
95 sideDark: '#9f9f9f',
96 artBevel: 0.125,
97 artEdge: 0.016,
98 shadowAlpha: 0.36,
99 shadowFade: 0.0016,
100 shadowAcross: 0.12,
101 shadowDown: 3,
102 shadowDownZ: 0.34,
103 shadowSpread: 0.004,
104 shadowBlur: 0.11,
105};
106
107/** Load the sheet and the back — the same files the CSS tiles use, so the pool
108 * cannot drift from the rest of the table. */
109export function loadArt(): Promise<Art> {
110 const load = (src: string) => {
111 const el = new Image();
112 el.src = src;
113 // Not fatal: the pool falls back to blank tiles rather than emptying out.
114 return el.decode().then(
115 () => el,
116 () => null,
117 );
118 };
119 return Promise.all([load(tilesUrl), load(backUrl)]).then(([faces, back]) => ({ faces, back }));
120}
121
122
123export interface Drawn {
124 x: number;
125 y: number;
126 z: number;
127 angle: number;
128 w: number;
129 h: number;
130 /** cos of the turn: 1 flat on its back, 0 edge on, negative face down. */
131 facing: number;
132 axis: number;
133 code: number;
134 lit: boolean;
135}
136
137/** Somewhere between two colours, `t` from the first to the second. */
138function mix(a: string, b: string, t: number): string {
139 const hex = (c: string) => [1, 3, 5].map((i) => parseInt(c.slice(i, i + 2), 16));
140 const [ar, ag, ab] = hex(a);
141 const [br, bg, bb] = hex(b);
142 const k = Math.max(0, Math.min(1, t));
143 return `rgb(${Math.round(ar + (br - ar) * k)},${Math.round(ag + (bg - ag) * k)},${Math.round(
144 ab + (bb - ab) * k,
145 )})`;
146}
147
148/**
149 * The sides of the tile you can actually see, lit by the one light.
150 *
151 * A tile is a box lying on cloth, seen from almost overhead and a little in
152 * front. What that shows of its sides is the two or three edges pointing
153 * towards the viewer — down the screen — each a quad between the top face's
154 * edge and the same edge dropped by the tile's depth. Which of them are lit is
155 * decided per edge, from the direction that edge faces on *screen*: turn the
156 * tile and the same physical side comes round to face a different way, and its
157 * shading changes with it, which is the whole point.
158 */
159function sides(ctx: CanvasRenderingContext2D, d: Drawn, w: number, h: number, look: TileLook) {
160 const depth = w * look.depth;
161 if (depth <= 0) return;
162
163 const c = Math.cos(d.angle);
164 const s = Math.sin(d.angle);
165 const corner = (x: number, y: number) => ({ x: d.x + x * c - y * s, y: d.y + x * s + y * c });
166 const box = [
167 corner(-w / 2, -h / 2),
168 corner(w / 2, -h / 2),
169 corner(w / 2, h / 2),
170 corner(-w / 2, h / 2),
171 ];
172
173 // Straight up the screen is 0, turning clockwise, so both of these read like
174 // a compass. `out` is where the tile's base sits from its face — the whole of
175 // the projection, and the only reason any side is in sight at all.
176 const lit = (look.lightAngle * Math.PI) / 180;
177 const light = { x: Math.sin(lit), y: -Math.cos(lit) };
178 const off = (look.depthAngle * Math.PI) / 180;
179 const out = { x: Math.sin(off) * depth, y: -Math.cos(off) * depth };
180
181 for (let i = 0; i < 4; i++) {
182 const a = box[i];
183 const b = box[(i + 1) % 4];
184 // Outward, in screen terms: the edge's normal, turned to point away from
185 // the middle of the tile.
186 const ex = b.x - a.x;
187 const ey = b.y - a.y;
188 const len = Math.hypot(ex, ey) || 1;
189 let nx = ey / len;
190 let ny = -ex / len;
191 if (nx * (a.x + b.x - 2 * d.x) + ny * (a.y + b.y - 2 * d.y) < 0) {
192 nx = -nx;
193 ny = -ny;
194 }
195 // Only the edges the base falls away from are in sight at all.
196 if (nx * out.x + ny * out.y <= 0.001) continue;
197
198 ctx.beginPath();
199 ctx.moveTo(a.x, a.y);
200 ctx.lineTo(b.x, b.y);
201 ctx.lineTo(b.x + out.x, b.y + out.y);
202 ctx.lineTo(a.x + out.x, a.y + out.y);
203 ctx.closePath();
204 // Facing the light is 1, facing away is 0.
205 ctx.fillStyle = mix(look.sideDark, look.sideLight, (nx * light.x + ny * light.y + 1) / 2);
206 ctx.fill();
207 ctx.strokeStyle = look.edgeLine;
208 ctx.lineWidth = look.edgeWidth;
209 ctx.stroke();
210 }
211}
212
213/**
214 * One tile: its face, its outline, and nothing else.
215 *
216 * There used to be a slab of ivory drawn under it and offset down the screen,
217 * so a sliver of the tile's own side showed along the bottom edge and it read
218 * as an object rather than a printed card. Seen at the size a discard is
219 * actually drawn it did not read as thickness — it read as a second, paler
220 * shape stuck to the bottom of every tile, and no amount of shading the thing
221 * fixed that, because the problem was that it was there at all.
222 *
223 * What gives a tile its weight now is the shadow under it and the line round
224 * it. Both of those are true at any size, which the slab never was.
225 */
226export function drawTile(
227 ctx: CanvasRenderingContext2D,
228 art: Art,
229 d: Drawn,
230 look: TileLook = LOOK,
231) {
232 const s = zScale(d.z);
233 const w = d.w * s;
234 const h = d.h * s;
235
236 // The sides first: the face sits on top of them, which is what makes the
237 // whole thing read as a block rather than a card with a border.
238 sides(ctx, d, w, h, look);
239
240 ctx.save();
241 ctx.translate(d.x, d.y);
242 // Edge on there is no face left to see, so it pinches to a line rather than
243 // through to the other side; a hair of width keeps the outline drawable.
244 squash(ctx, Math.max(0.015, Math.abs(d.facing)), d.axis);
245 ctx.rotate(d.angle);
246 face(ctx, d.code, w, h, art, d.lit, d.facing < 0, look);
247 ctx.restore();
248}
249
250/**
251 * One cell of the sheet, cut out and kept.
252 *
253 * `drawImage` with a source rectangle is allowed to sample *past* that
254 * rectangle when it resamples, and the row under every face is the sheet's own
255 * highlighted variant, whose border is bright blue. Square on and at a right
256 * angle nothing resamples across that boundary and all is well; at any other
257 * angle the blue is dragged in and every turned tile wears a blue fringe along
258 * one edge. Measured, an arbitrary rotation took the worst blue on the tile
259 * from 92 — which is the tile's own ink — to 255.
260 *
261 * Cut out once at native size there is nothing beside it to bleed, and it is
262 * the same 92 at every angle and every size.
263 *
264 * 43 columns, two rows; the second is the highlighted variant, which is what a
265 * lifted tile in a hand uses. The tile in your fingers and the one still to be
266 * claimed get it here for the same reason.
267 */
268const cells = new Map<string, HTMLCanvasElement>();
269let cellsFrom: HTMLImageElement | null = null;
270
271function cellOf(
272 sheet: HTMLImageElement,
273 tile: number,
274 lit: boolean,
275 look: TileLook,
276): HTMLCanvasElement {
277 // A different sheet — a hot reload, in practice — is a different set of cells.
278 if (cellsFrom !== sheet) {
279 cells.clear();
280 cellsFrom = sheet;
281 }
282 const key = `${tile}:${lit}:${look.artBevel}:${look.artEdge}`;
283 const had = cells.get(key);
284 if (had) return had;
285
286 const cw = sheet.naturalWidth / SPRITE_COLS;
287 const ch = sheet.naturalHeight / 2;
288 // A thickness is a thickness whichever way it is measured, so both insets are
289 // taken off the cell's *width*. The painted side is down the left and along
290 // the bottom; the other two carry only the outline.
291 const bevel = cw * look.artBevel;
292 const edge = cw * look.artEdge;
293 const sx = SPRITE_COL[tile] * cw + bevel;
294 const sy = (lit ? ch : 0) + edge;
295 const sw = cw - bevel - edge;
296 const sh = ch - edge - bevel;
297
298 const c = document.createElement('canvas');
299 c.width = Math.max(1, Math.round(sw));
300 c.height = Math.max(1, Math.round(sh));
301 c.getContext('2d')?.drawImage(sheet, sx, sy, sw, sh, 0, 0, c.width, c.height);
302 cells.set(key, c);
303 return c;
304}
305
306/**
307 * A soft silhouette under a tile.
308 *
309 * The blur is baked into a sprite once per tile size rather than applied per
310 * draw. `ctx.filter` is the obvious way to write this and the wrong one: every
311 * filtered fill makes the browser allocate and blur its own layer, so sixty
312 * tiles times sixty frames is sixty times sixty blurs a second, which is enough
313 * to make the tab stop answering. One blur, then `drawImage`.
314 *
315 * Height is sold by scaling that sprite up — a shadow that spreads and fades as
316 * the tile rises — which a fixed blur radius could not have done anyway.
317 */
318const shadows = new Map<string, HTMLCanvasElement>();
319
320function shadowSprite(w: number, h: number, blur: number): HTMLCanvasElement {
321 const key = `${Math.round(w)}x${Math.round(h)}@${blur}`;
322 const had = shadows.get(key);
323 if (had) return had;
324 // Only ever a handful — one per tile size on screen — but a window being
325 // dragged to resize walks through a lot of them.
326 if (shadows.size > 8) shadows.clear();
327
328 const pad = Math.ceil(Math.max(8, w * 0.5));
329 const c = document.createElement('canvas');
330 c.width = Math.ceil(w) + pad * 2;
331 c.height = Math.ceil(h) + pad * 2;
332 const g = c.getContext('2d');
333 if (g) {
334 g.filter = `blur(${Math.max(1.5, w * blur).toFixed(1)}px)`;
335 g.fillStyle = '#000';
336 g.translate(c.width / 2, c.height / 2);
337 g.beginPath();
338 g.roundRect(-w / 2, -h / 2, w, h, w * 0.1);
339 g.fill();
340 }
341 shadows.set(key, c);
342 return c;
343}
344
345/**
346 * Foreshortening along the axis a tile is turning about.
347 *
348 * There is no third dimension here, so an out-of-plane turn is drawn as a
349 * squash. Applied in the *table's* frame, before the tile's own flat rotation,
350 * because the axis it turns about is fixed by the direction it was thrown, not
351 * by which way the tile happens to be facing.
352 */
353function squash(ctx: CanvasRenderingContext2D, across: number, axis: number) {
354 if (across > 0.999) return;
355 ctx.rotate(axis);
356 ctx.scale(across, 1);
357 ctx.rotate(-axis);
358}
359
360export function drawShadow(
361 ctx: CanvasRenderingContext2D,
362 x: number,
363 y: number,
364 z: number,
365 angle: number,
366 w: number,
367 h: number,
368 scale: number,
369 facing: number,
370 axis: number,
371 look: TileLook = LOOK,
372) {
373 // Keyed on the tile's own size, never on the eased one — a scale that changes
374 // every frame would mean a fresh blur every frame, which is the thing this
375 // exists to avoid.
376 const sprite = shadowSprite(w, h, look.shadowBlur);
377 const spread = zScale(z) * scale * (1 + z * look.shadowSpread);
378 ctx.save();
379 ctx.globalAlpha = look.shadowAlpha - Math.min(look.shadowAlpha / 2, z * look.shadowFade);
380 ctx.translate(x + z * look.shadowAcross, y + look.shadowDown + z * look.shadowDownZ);
381 squash(ctx, Math.abs(facing), axis);
382 ctx.rotate(angle);
383 ctx.drawImage(
384 sprite,
385 (-sprite.width / 2) * spread,
386 (-sprite.height / 2) * spread,
387 sprite.width * spread,
388 sprite.height * spread,
389 );
390 ctx.restore();
391}
392
393function face(
394 ctx: CanvasRenderingContext2D,
395 tile: number,
396 w: number,
397 h: number,
398 art: Art,
399 lit: boolean,
400 backwards: boolean,
401 look: TileLook,
402) {
403 // Part-way through a turn you are looking at the back of it: the same green
404 // tile back the wall is built from. A tile always comes to rest face up, so
405 // this is only ever seen in the air.
406 if (backwards) {
407 if (art.back) ctx.drawImage(art.back, -w / 2, -h / 2, w, h);
408 else {
409 tilePath(ctx, w, h);
410 ctx.fillStyle = '#1c7a4b';
411 ctx.fill();
412 }
413 // A green back on green cloth needs the edge more than a white face does.
414 tilePath(ctx, w, h);
415 ctx.strokeStyle = look.edgeLine;
416 ctx.lineWidth = look.edgeWidth;
417 ctx.stroke();
418 return;
419 }
420
421 if (art.faces) {
422 ctx.drawImage(cellOf(art.faces, tile, lit, look), -w / 2, -h / 2, w, h);
423 } else {
424 tilePath(ctx, w, h);
425 ctx.fillStyle = '#f6f0e2';
426 ctx.fill();
427 }
428 // The edge the shrunken art no longer carries for itself.
429 tilePath(ctx, w, h);
430 ctx.strokeStyle = look.edgeLine;
431 ctx.lineWidth = look.edgeWidth;
432 ctx.stroke();
433 if (lit) {
434 // A pool of sixty tiles needs more than a lighter face to pick one out.
435 tilePath(ctx, w, h);
436 ctx.strokeStyle = '#d9b45c';
437 ctx.lineWidth = 2;
438 ctx.stroke();
439 }
440}
441
442function tilePath(ctx: CanvasRenderingContext2D, w: number, h: number) {
443 ctx.beginPath();
444 ctx.roundRect(-w / 2, -h / 2, w, h, w * 0.1);
445}