anvilsign in

collin/mahjong

1import { useEffect, useRef, useState } from 'react';
2import type { TableCtl } from '../game/ctl';
3import { barge, knock } from '../game/sound';
4import { aabbOf, centreLimits, faceOn, type Rect } from '../table/physics';
5import type { TablePool } from '../table/pool';
6import type { SeatId } from '../game/types';
7import {
8 exposePool,
9 holdOn,
10 isHeld,
11 keyHeld,
12 noteImpacts,
13 onCollidersChange,
14 owedTime,
15 pausingOnHit,
16 recentImpacts,
17 showingColliders,
18} from './colliders';
19import { EDGE_SEAT } from './rotation';
20import { drawShadow, drawTile, loadArt, type Art } from './tileArt';
21
22/**
23 * The tiles in the middle of the table, drawn.
24 *
25 * A canvas rather than elements, and it spans the whole table rather than just
26 * the centre. The span is the point: `.slot` and `.seat` both clip their own
27 * contents, which is exactly why a tile cannot be animated out of a strip as a
28 * div — on the canvas there is nothing to clip it, so a tile lifted out of a
29 * hand and thrown crosses the table in one piece.
30 *
31 * The loop stops as soon as the pile has settled, and starts again when the
32 * state changes, a tile is picked up, or the window resizes, so a table nobody
33 * is touching costs nothing.
34 */
35export function Pool({
36 game,
37 pool,
38 viewSeat = 0,
39}: {
40 game: TableCtl;
41 pool: TablePool;
42 /** The seat drawn at the bottom of this screen — see App. An edge the physics
43 * reports belongs to whoever is drawn there, not to seat 0 by birthright. */
44 viewSeat?: SeatId;
45}) {
46 const canvasRef = useRef<HTMLCanvasElement>(null);
47 const art = useSheet();
48
49 // What the loop reads. Refreshed on every render, read on every frame.
50 const live = useRef({ state: game.state, art, viewSeat });
51 live.current = { state: game.state, art, viewSeat };
52
53 // Poked by the effect below, and by the gesture through pool.wake.
54 const wake = useRef<() => void>(() => {});
55
56 useEffect(() => {
57 const canvas = canvasRef.current;
58 const table = canvas?.parentElement;
59 const ctx = canvas?.getContext('2d');
60 if (!canvas || !table || !ctx) return;
61
62 pool.attach(table);
63 exposePool(pool);
64 const stopDragging = dragging(table as HTMLElement, pool, () => wake.current());
65
66 let frame = 0;
67 let previous = 0;
68
69 const resize = () => {
70 const dpr = window.devicePixelRatio || 1;
71 const w = Math.round(table.clientWidth * dpr);
72 const h = Math.round(table.clientHeight * dpr);
73 if (canvas.width !== w || canvas.height !== h) {
74 canvas.width = w;
75 canvas.height = h;
76 }
77 // The square moved, so the colliders and the launch points have too.
78 pool.invalidate();
79 run();
80 };
81
82 const tick = (now: number) => {
83 frame = 0;
84 // First frame after waking has no previous time to measure against.
85 const dt = previous ? Math.min(0.05, (now - previous) / 1000) : 0;
86 previous = now;
87
88 pool.sync(live.current.state);
89 // A tile in the fingers goes over the table's own buttons — seat 0 throws
90 // from the *right-hand end* of its row, which is directly under the undo
91 // button — so while one is being carried they stop taking the pointer.
92 table.classList.toggle('carrying', !!pool.held);
93 // The loudest contact this frame is the one you would actually hear; the
94 // rest of a scatter is the same event.
95 // Frozen on a contact: the world only moves when it is asked to, a fixed
96 // step at a time, so the moment can be walked through rather than watched.
97 const impacts = isHeld() ? pool.advance(owedTime()) : pool.advance(dt, pausingOnHit());
98 noteImpacts(impacts);
99 if (pausingOnHit() && !isHeld() && impacts.length) holdOn(impacts);
100 let loudest = 0;
101 for (const i of impacts) {
102 // A contact quiet enough not to be worth hearing still counts as a tile
103 // arriving in somebody's lap, which is why the two thresholds differ.
104 if (i.strength > AUDIBLE) loudest = Math.max(loudest, i.strength);
105 // Straight into somebody's tiles — the wall square is nobody's, so this
106 // is a hand or a set that has been laid down.
107 if (i.into !== undefined) shove(pool, table, i.into, i.seat, i.strength);
108 else if (i.edge) {
109 const at = ((EDGE_SEAT[i.edge] + live.current.viewSeat) % 4) as SeatId;
110 shove(pool, table, at, i.seat, i.strength);
111 }
112 }
113 if (loudest > 0) knock(loudest);
114 paint(ctx, canvas, pool, live.current.art);
115
116 // Keep going while anything is moving; otherwise wait to be poked. A held
117 // world is never running: it is stepped by hand and repainted each time.
118 if (!isHeld() && !pool.settled) frame = requestAnimationFrame(tick);
119 else previous = 0;
120 };
121
122 const run = () => {
123 if (!frame) frame = requestAnimationFrame(tick);
124 };
125 wake.current = run;
126 pool.wake = run;
127
128 const observer = new ResizeObserver(resize);
129 observer.observe(table);
130 const stopColliders = onCollidersChange(run);
131 const onKey = (e: KeyboardEvent) => {
132 if (keyHeld(e)) e.preventDefault();
133 };
134 window.addEventListener('keydown', onKey);
135 resize();
136
137 return () => {
138 stopDragging();
139 window.removeEventListener('keydown', onKey);
140 stopColliders();
141 observer.disconnect();
142 if (frame) cancelAnimationFrame(frame);
143 wake.current = () => {};
144 pool.wake = () => {};
145 pool.detach();
146 };
147 }, [pool]);
148
149 // Any change to the table — a discard, a claim, an undo, a new hand — is a
150 // reason to look again.
151 useEffect(() => {
152 wake.current();
153 });
154
155 return <canvas className="tile-pool" ref={canvasRef} aria-hidden />;
156}
157
158/**
159 * Picking a discard up and putting it somewhere else.
160 *
161 * A discard's position is not part of the game — the engine neither knows nor
162 * cares where in the middle a tile is lying — so the pile is free to be handled
163 * the way a real one is: take hold of a tile, carry it over the top of the
164 * others, and either set it down or send it skidding off with a flick.
165 *
166 * The listener is on the table and it *captures*, because the tiles are drawn
167 * on a canvas that has no elements to hit. It hit-tests the pile first and only
168 * takes the gesture when a tile is actually under the finger; anything else is
169 * let straight through to whatever it was really aimed at — a tile in a hand,
170 * the settings button, the wall.
171 */
172function dragging(table: HTMLElement, pool: TablePool, wake: () => void) {
173 let samples: { x: number; y: number; t: number }[] = [];
174
175 const at = (e: PointerEvent) => {
176 const r = table.getBoundingClientRect();
177 return { x: e.clientX - r.left, y: e.clientY - r.top, t: e.timeStamp };
178 };
179
180 const down = (e: PointerEvent) => {
181 // Only the primary button, and only where there is a tile to take hold of.
182 if (e.button !== 0) return;
183 const p = at(e);
184 if (!pool.grabAt(p.x, p.y)) return;
185 e.stopPropagation();
186 e.preventDefault();
187 samples = [p];
188 try {
189 table.setPointerCapture?.(e.pointerId);
190 } catch {
191 // Uncaptured still works while the pointer stays over the table.
192 }
193 wake();
194 };
195
196 const move = (e: PointerEvent) => {
197 if (!pool.dragging) return;
198 e.stopPropagation();
199 const p = at(e);
200 // Only the tail matters, and only the recent tail: a flick is the last few
201 // milliseconds of a drag, not an average over the whole of it.
202 samples.push(p);
203 if (samples.length > 6) samples.shift();
204 pool.dragTo(p.x, p.y);
205 wake();
206 };
207
208 const up = (e: PointerEvent) => {
209 if (!pool.dragging) return;
210 e.stopPropagation();
211 const p = at(e);
212 samples.push(p);
213 const first = samples[0];
214 const dt = (p.t - first.t) / 1000;
215 const vx = dt > 0 ? (p.x - first.x) / dt : 0;
216 const vy = dt > 0 ? (p.y - first.y) / dt : 0;
217 // A flick that curves puts a turn on the tile, as one out of a hand does.
218 const spin = dt > 0 ? ((p.x - first.x) * 0.004) / dt / 100 : 0;
219 pool.releaseGrab(vx, vy, spin);
220 samples = [];
221 wake();
222 };
223
224 table.addEventListener('pointerdown', down, true);
225 table.addEventListener('pointermove', move, true);
226 table.addEventListener('pointerup', up, true);
227 table.addEventListener('pointercancel', up, true);
228 return () => {
229 table.removeEventListener('pointerdown', down, true);
230 table.removeEventListener('pointermove', move, true);
231 table.removeEventListener('pointerup', up, true);
232 table.removeEventListener('pointercancel', up, true);
233 };
234}
235
236/** The sheet and the green back, once, shared by every tile drawn. */
237function useSheet(): Art {
238 const [art, setArt] = useState<Art>({ faces: null, back: null });
239 useEffect(() => {
240 let alive = true;
241 void loadArt().then((a) => alive && setArt(a));
242 return () => {
243 alive = false;
244 };
245 }, []);
246 return art;
247}
248
249/** How high a tile in somebody's fingers is held above the felt. */
250const HELD_Z = 52;
251
252/** Quieter than this and the contact is not worth a clack of its own. */
253const AUDIBLE = 0.12;
254
255/** How long the knocked row rocks for, in seconds. Matches `shoved` in the CSS,
256 * which is the other half of it: the table waits at least this long. */
257const SHAKE = 0.34;
258
259/**
260 * A tile has ended up in this seat's tiles — knocked into them, or simply come
261 * to a stop off the table on their side. Either way it is theirs to complain
262 * about, and how hard it arrived only decides how loudly.
263 *
264 * Their row takes the knock — straight on the element rather than through
265 * React, because this happens inside the physics loop and re-rendering four
266 * strips to shake one of them would be absurd — and the table says something
267 * about it. Not for the thrower's own edge: you cannot be barged by your own
268 * discard, and everybody's tile passes over their own row on the way out.
269 */
270function shove(
271 pool: TablePool,
272 table: HTMLElement,
273 seat: SeatId,
274 thrower: SeatId | undefined,
275 strength: number,
276) {
277 if (seat === thrower) return;
278 // Hold the table while it is being said and while the row is still rocking.
279 // The computer plays on a timer of its own, and a 碰 called over the top of
280 // somebody objecting to the tile lands the objection on nobody.
281 pool.heckle(Math.max(SHAKE, barge(strength)));
282 const hand = table.querySelector<HTMLElement>(`[data-seat="${seat}"] .hand`);
283 if (!hand || hand.classList.contains('shoved')) return;
284 hand.classList.add('shoved');
285 hand.addEventListener('animationend', () => hand.classList.remove('shoved'), { once: true });
286}
287
288function paint(
289 ctx: CanvasRenderingContext2D,
290 canvas: HTMLCanvasElement,
291 pool: TablePool,
292 art: Art,
293) {
294 const dpr = window.devicePixelRatio || 1;
295 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
296 ctx.clearRect(0, 0, canvas.width / dpr, canvas.height / dpr);
297
298 const bodies = pool.bodies;
299 const held = pool.held;
300 const departing = pool.departing;
301
302 // Shadows in one pass of their own, offset before rotation, so the light comes
303 // from one direction across the whole pool rather than turning with each tile.
304 for (const b of bodies) {
305 drawShadow(ctx, b.x, b.y, b.z, b.angle, b.w, b.h, b.scale, faceOn(b), b.flipAxis);
306 }
307 if (held) drawShadow(ctx, held.x, held.y, HELD_Z, held.angle, held.w, held.h, 1, 1, 0);
308
309 const newest = pool.newest;
310 for (const b of bodies) {
311 drawTile(ctx, art, {
312 x: b.x,
313 y: b.y,
314 z: b.z,
315 angle: b.angle,
316 w: b.w * b.scale,
317 h: b.h * b.scale,
318 facing: faceOn(b),
319 axis: b.flipAxis,
320 code: b.tile,
321 lit: b === newest,
322 });
323 }
324
325 // On its way to whoever called it — lifted, turning, and fading as it goes.
326 for (const { body: b, fade } of departing) {
327 ctx.save();
328 ctx.globalAlpha = fade;
329 drawTile(ctx, art, {
330 x: b.x,
331 y: b.y,
332 z: b.z,
333 angle: b.angle,
334 w: b.w * b.scale,
335 h: b.h * b.scale,
336 facing: faceOn(b),
337 axis: b.flipAxis,
338 code: b.tile,
339 lit: true,
340 });
341 ctx.restore();
342 }
343
344 // Whatever is in your fingers is above everything else on the table.
345 if (held) {
346 drawTile(ctx, art, {
347 x: held.x,
348 y: held.y,
349 z: HELD_Z,
350 angle: held.angle,
351 w: held.w,
352 h: held.h,
353 facing: 1,
354 axis: 0,
355 code: held.tile,
356 lit: true,
357 });
358 }
359
360 // Over the top of all of it, or there would be no point to it.
361 if (showingColliders()) colliders(ctx, pool);
362}
363
364/**
365 * Every boundary the physics uses, drawn where it actually is.
366 *
367 * Solid the felt — the fence that keeps a tile on the table, measured
368 * out to where each seat's tiles begin (table/geometry.ts).
369 * Solid each standing stack of two. Half stacks are not drawn because
370 * they are not colliders: a tile goes over them.
371 * Dashed the wall square's opening. Only where a throw is *aimed*; it
372 * stops nothing, which is why the pile spills out of it.
373 * Dotted, in where the moving tile's own centre is allowed to be — the felt
374 * less that tile's half width. This is the line a bounce happens
375 * at, and it is half a tile inside the solid one, which is what
376 * makes a bounce look early when it is not.
377 * Per tile the rotated rectangle it really collides with, and, fainter, the
378 * upright box the felt's straight edges use instead. The two come
379 * apart as a tile turns, and that difference is worth seeing.
380 */
381function colliders(ctx: CanvasRenderingContext2D, pool: TablePool) {
382 const world = pool.world;
383 if (!world) return;
384
385 const line = (r: Rect) => ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
386
387 ctx.save();
388 ctx.lineWidth = 1;
389
390 // The table's own edge, and every tile standing on it.
391 ctx.strokeStyle = '#ff2d20';
392 line(world.bounds);
393 for (const w of world.walls) {
394 if (!w.angle) {
395 line(w.rect);
396 continue;
397 }
398 // Turned, so it is drawn turned — the wall square stands on its corner.
399 ctx.save();
400 ctx.translate(w.rect.x + w.rect.w / 2, w.rect.y + w.rect.h / 2);
401 ctx.rotate(w.angle);
402 ctx.strokeRect(-w.rect.w / 2, -w.rect.h / 2, w.rect.w, w.rect.h);
403 ctx.restore();
404 }
405
406 // Where a throw is aimed. Not a fence — see TableGeometry.pool.
407 const aim = pool.poolRect;
408 if (aim) {
409 ctx.setLineDash([5, 5]);
410 ctx.strokeStyle = 'rgba(255, 45, 32, 0.45)';
411 line(aim);
412 ctx.setLineDash([]);
413 }
414
415 // Whatever is still moving: what it collides with, and what it is held by.
416 const live = world.bodies.find((b) => !b.resting) ?? pool.newest;
417
418 for (const b of world.bodies) {
419 // A tile in the fingers is held over everything and collides with nothing,
420 // so it gets no box: the boxes are what is solid.
421 if (b.carried) continue;
422 ctx.strokeStyle = b === live ? 'rgba(255, 45, 32, 0.9)' : 'rgba(255, 45, 32, 0.35)';
423 ctx.save();
424 ctx.translate(b.x, b.y);
425 ctx.rotate(b.angle);
426 ctx.strokeRect(-b.w / 2, -b.h / 2, b.w, b.h);
427 ctx.restore();
428
429 // The upright box the felt's edges are worked out from. Only for the one in
430 // flight: sixty of them at once is a red mess, not a picture.
431 if (b === live && b.angle % Math.PI !== 0) {
432 ctx.setLineDash([2, 3]);
433 ctx.strokeStyle = 'rgba(255, 45, 32, 0.5)';
434 line(aabbOf(b));
435 ctx.setLineDash([]);
436 }
437 }
438
439 if (live) {
440 // The box that tile's centre is held inside, and where the centre is now.
441 ctx.setLineDash([2, 3]);
442 ctx.strokeStyle = 'rgba(255, 45, 32, 0.75)';
443 line(centreLimits(world.bounds, live));
444 ctx.setLineDash([]);
445 ctx.fillStyle = '#ff2d20';
446 ctx.fillRect(live.x - 1.5, live.y - 1.5, 3, 3);
447 }
448
449 // How the last few throws actually left. Faint line: the flick, as it was
450 // let go of. Bright line: where the tile was actually sent. When those two
451 // disagree the tile leaves on a line nobody threw, which is the other way a
452 // bounce can be a bounce off nothing — see TablePool.throws.
453 ctx.font = '9px ui-monospace, monospace';
454 ctx.textBaseline = 'bottom';
455 for (const t of pool.throws) {
456 const ray = (dx: number, dy: number, len: number) => {
457 const d = Math.hypot(dx, dy) || 1;
458 ctx.beginPath();
459 ctx.moveTo(t.x, t.y);
460 ctx.lineTo(t.x + (dx / d) * len, t.y + (dy / d) * len);
461 ctx.stroke();
462 };
463 ctx.strokeStyle = 'rgba(90, 200, 250, 0.35)';
464 ray(t.fx, t.fy, 90);
465 ctx.strokeStyle = 'rgba(90, 200, 250, 0.9)';
466 ray(t.vx, t.vy, 130);
467 ctx.fillStyle = 'rgba(90, 200, 250, 0.9)';
468 ctx.fillText(t.how, t.x + 6, t.y - 4);
469 ctx.fillRect(t.x - 2, t.y - 2, 4, 4);
470 }
471
472 // Where contact was actually made, fading out. One of these with no box under
473 // it is the interesting case: a bounce off something that is not drawn is a
474 // bounce off something that is not a collider.
475 ctx.font = '9px ui-monospace, monospace';
476 ctx.textBaseline = 'bottom';
477 for (const m of recentImpacts(!isHeld())) {
478 const fade = 1 - m.age / 90;
479 ctx.strokeStyle = `rgba(255, 214, 10, ${fade})`;
480 ctx.fillStyle = `rgba(255, 214, 10, ${fade})`;
481 ctx.beginPath();
482 ctx.moveTo(m.x - 5, m.y);
483 ctx.lineTo(m.x + 5, m.y);
484 ctx.moveTo(m.x, m.y - 5);
485 ctx.lineTo(m.x, m.y + 5);
486 ctx.stroke();
487 if (m.kind) ctx.fillText(m.kind, m.x + 6, m.y - 2);
488 }
489
490 ctx.restore();
491}
492