anvilsign in

collin/mahjong

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