anvilsign in

collin/mahjong

1import type { GameState } from '../game/engine';
2import { makeRng, type Tile } from '../game/tiles';
3import type { SeatId } from '../game/types';
4import {
5 aimAt,
6 canThrow,
7 canThrowFrom,
8 centreOf,
9 measure,
10 type Point,
11 type TableGeometry,
12} from './geometry';
13import {
14 addBody,
15 advance as advanceWorld,
16 createWorld,
17 liftFor,
18 reshape,
19 settled,
20 stir,
21 SLIDE_TIME,
22 type Body,
23 type Impact,
24 type Rect,
25 type World,
26} from './physics';
27
28const SEATS: SeatId[] = [0, 1, 2, 3];
29
30/**
31 * The tiles in the middle, kept honest against the game state.
32 *
33 * This *diffs* rather than listening for events, and that is the whole design.
34 * A discard is identified by which seat threw it and how many it had thrown
35 * before — and those keys never shift, because discards are only ever pushed and
36 * `engine.executeClaim` only ever pops the one on top. So every way the pile can
37 * change is the same code path: a key that has appeared is a tile to throw in, a
38 * key that has gone is a tile to take out. Undo, 下一局, a claim, and picking up
39 * a saved game all fall out of that without the engine knowing this exists.
40 *
41 * Nothing here is stored in the game state, so there is no save format to
42 * change. A pile is rebuilt from the discards it can see, seeded off the hand
43 * number and each tile's place in it, which is why a refresh mid-hand comes back
44 * to the pile it had rather than a freshly scattered one.
45 */
46
47/** How long a placed tile is in the air. Long enough to arc over the wall. */
48const PLACE_FLIGHT = 0.62;
49/** A flicked tile hops rather than lofts — across the table, not over a wall. */
50const THROW_LIFT = 0.18;
51/** Fastest flick we will honour, px/s. Beyond this it is a slip, not a throw. */
52export const MAX_THROW_SPEED = 3600;
53/** How long a claimed tile takes to leave the table for the seat taking it. */
54const TAKE_FLIGHT = 0.34;
55
56/** A tile on its way off the table, no longer part of the pile. */
57interface Leaving {
58 body: Body;
59 tx: number;
60 ty: number;
61 /** 0 to 1. */
62 t: number;
63}
64
65/**
66 * Whether a wall standing in the way turns a discard into a lob over the top
67 * rather than a flick across the table.
68 *
69 * Off for now, deliberately: every discard slides, because sliding is what a
70 * discard should look like. The lob is kept whole below and this is the only
71 * switch that reaches it — when there is a rule for when a throw is called for
72 * instead, it goes here and nothing else has to move.
73 */
74const LOB_WHEN_WALLED: boolean = false;
75
76/** A tile lifted out of a hand and carried about. Drawn, but not simulated. */
77export interface Held {
78 seat: SeatId;
79 tile: Tile;
80 /** Where it came from in that seat's hand, so the caller knows what to play. */
81 index: number;
82 x: number;
83 y: number;
84 angle: number;
85 /** The size it was in the hand — it shrinks to pool size once thrown. */
86 w: number;
87 h: number;
88}
89
90/** A throw that has been let go of, waiting for the discard it belongs to. */
91interface Release {
92 seat: SeatId;
93 x: number;
94 y: number;
95 angle: number;
96 w: number;
97 h: number;
98 vx: number;
99 vy: number;
100 spin: number;
101}
102
103export class TablePool {
104 world: World | null = null;
105 geo: TableGeometry | null = null;
106 /** The tile in somebody's fingers, if any. */
107 held: Held | null = null;
108 /**
109 * Poke the render loop. Set by ui/Pool.tsx while it is mounted; a gesture
110 * calls it so a carried tile follows the finger without waiting on a re-render.
111 */
112 wake: () => void = () => {};
113
114 private table: HTMLElement | null = null;
115 /** Bodies by `seat:index` into that seat's discards. */
116 private entries = new Map<string, Body>();
117 private release: Release | null = null;
118 /** What the wall looked like when we last measured, so we know to re-measure. */
119 private measuredAt = '';
120 private hand = -1;
121 /** The tile currently on the table to be claimed, so it can be marked. */
122 private newestKey: string | null = null;
123 /** How many melds each seat had last time, to spot who took a tile. */
124 private melds = [0, 0, 0, 0];
125 /** Tiles on their way off the table. Drawn, but out of the physics. */
126 private leaving: Leaving[] = [];
127
128 // Which seats can throw, as a string, so the seats can re-render when it
129 // changes. Read through useSyncExternalStore, the same way the game is.
130 private openness = '----';
131 private listeners = new Set<() => void>();
132
133 attach(table: HTMLElement) {
134 this.table = table;
135 this.measuredAt = '';
136 }
137
138 detach() {
139 this.table = null;
140 this.world = null;
141 this.geo = null;
142 this.held = null;
143 this.release = null;
144 this.entries.clear();
145 this.leaving = [];
146 this.measuredAt = '';
147 }
148
149 subscribe = (cb: () => void) => {
150 this.listeners.add(cb);
151 return () => this.listeners.delete(cb);
152 };
153
154 /** Which seats have a clear line in, as a string — cheap to compare. */
155 getSnapshot = () => this.openness;
156
157 /** Force a re-measure — the window resized, or the layout changed under us. */
158 invalidate() {
159 this.measuredAt = '';
160 }
161
162 /**
163 * Whether this seat can flick a tile in, or has to lift it over the wall.
164 * Unmeasured (or compact, where there is no square) means no.
165 */
166 canThrow(seat: SeatId): boolean {
167 return this.openness[seat] === 'y';
168 }
169
170 /** Where the middle of the table is, for a gesture working out its aim. */
171 get poolCentre(): Point | null {
172 return this.geo ? centreOf(this.geo.pool) : null;
173 }
174
175 /** Whether a point is already inside the square — a tile dropped there stays. */
176 inPool(x: number, y: number): boolean {
177 const p = this.geo?.pool;
178 if (!p) return false;
179 return x >= p.x && x <= p.x + p.w && y >= p.y && y <= p.y + p.h;
180 }
181
182 /** Whether a tile let go of *here* has a clear line in. Not the same question
183 * as `canThrow(seat)`: a carried tile is wherever the player took it. */
184 canThrowFrom(x: number, y: number): boolean {
185 return !!this.geo && canThrowFrom(this.geo, { x, y });
186 }
187
188 /** Where the pool sits on the table, for the patch of it you can reach into. */
189 get poolRect(): Rect | null {
190 return this.geo?.pool ?? null;
191 }
192
193 /**
194 * Push the tiles in the middle about — washing them, the way everybody does
195 * to a pool of discards while waiting. Purely cosmetic: where a discard is
196 * lying is not part of the game.
197 */
198 stir(x: number, y: number, vx: number, vy: number) {
199 if (!this.world || !this.geo) return;
200 // A finger's worth: about a tile across.
201 stir(this.world, x, y, vx, vy, this.geo.tile.w * 0.6);
202 }
203
204 // ---- the tile in your fingers -----------------------------------------
205
206 /** Lifted out of a hand. From here the canvas draws it, not the DOM. */
207 pickUp(held: Held) {
208 this.held = held;
209 }
210
211 moveHeld(x: number, y: number, angle?: number) {
212 if (!this.held) return;
213 this.held.x = x;
214 this.held.y = y;
215 if (angle !== undefined) this.held.angle = angle;
216 }
217
218 /** Put it back in the hand — the throw was not committed to. */
219 cancelHeld() {
220 this.held = null;
221 }
222
223 /**
224 * Let go of it. The body is not made here: the reconciler owns every tile in
225 * the pool, so this leaves the throw where the next `sync` will find it and
226 * the caller goes on to call `game.discard`. The held tile stays drawn until
227 * that happens, so there is no frame with nothing on screen.
228 */
229 throwHeld(vx: number, vy: number, spin: number) {
230 const h = this.held;
231 if (!h) return;
232 const speed = Math.hypot(vx, vy);
233 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
234 this.release = {
235 seat: h.seat,
236 x: h.x,
237 y: h.y,
238 angle: h.angle,
239 w: h.w,
240 h: h.h,
241 vx: vx * scale,
242 vy: vy * scale,
243 spin,
244 };
245 }
246
247 // ---- keeping up with the game ----------------------------------------
248
249 /** Bring the pile in line with the state. Cheap when nothing has changed. */
250 sync(state: GameState) {
251 this.remeasure(state);
252 const geo = this.geo;
253 const world = this.world;
254 if (!geo || !world) return;
255
256 // A new hand is a new pile, and nothing should fly anywhere.
257 const fresh = state.handNumber !== this.hand;
258 this.hand = state.handNumber;
259
260 const want = new Set<string>();
261 const added: { key: string; seat: SeatId; index: number; tile: Tile }[] = [];
262 for (const seat of SEATS) {
263 const discards = state.players[seat].discards;
264 for (let i = 0; i < discards.length; i++) {
265 const key = `${seat}:${i}`;
266 want.add(key);
267 if (!this.entries.has(key)) added.push({ key, seat, index: i, tile: discards[i] });
268 }
269 }
270
271 const taken: Body[] = [];
272 for (const [key, body] of this.entries) {
273 if (want.has(key)) continue;
274 const at = world.bodies.indexOf(body);
275 if (at >= 0) world.bodies.splice(at, 1);
276 this.entries.delete(key);
277 taken.push(body);
278 }
279
280 // Exactly one tile off the table is somebody taking it — a 碰, a 吃, a 槓,
281 // or a discard being taken back. It goes to whoever now has a meld they did
282 // not have a moment ago, and failing that back to the seat that threw it,
283 // which is what an undo is. Several at once is the hand ending, and those
284 // simply go.
285 const claimer = SEATS.find((q) => state.players[q].melds.length > this.melds[q]);
286 this.melds = SEATS.map((q) => state.players[q].melds.length);
287 if (taken.length === 1 && !fresh) {
288 const to = geo.launch[claimer ?? taken[0].seat];
289 if (to) this.leaving.push({ body: taken[0], tx: to.x, ty: to.y, t: 0 });
290 }
291
292 // One tile at a time is somebody playing, and it gets thrown. Several at
293 // once is a pile being rebuilt — a save picked up, an undo, a fresh deal —
294 // and those tiles were thrown long ago, so they are simply already there.
295 const rebuilding = fresh || added.length > 1;
296 for (const a of added) {
297 this.entries.set(a.key, rebuilding ? this.settle(geo, state, a) : this.launch(geo, state, a));
298 }
299
300 // A throw is good for exactly one discard, and the tile it belonged to has
301 // either just arrived or is never going to.
302 if (added.length || this.release) {
303 this.release = null;
304 this.held = null;
305 }
306
307 const ld = state.lastDiscard;
308 this.newestKey = ld ? `${ld.from}:${state.players[ld.from].discards.length - 1}` : null;
309 }
310
311 /** Run the physics on. Returns impacts worth a sound. */
312 advance(seconds: number): Impact[] {
313 this.carryOff(seconds);
314 return this.world ? advanceWorld(this.world, seconds) : [];
315 }
316
317 /** Tiles leaving the table, lifted and carried off to the seat taking them. */
318 private carryOff(seconds: number) {
319 if (this.leaving.length === 0) return;
320 for (const l of this.leaving) {
321 l.t = Math.min(1, l.t + seconds / TAKE_FLIGHT);
322 // Ease out, so it leaves quickly and arrives gently.
323 const k = 1 - (1 - l.t) * (1 - l.t);
324 l.body.x += (l.tx - l.body.x) * k * 0.5;
325 l.body.y += (l.ty - l.body.y) * k * 0.5;
326 // Up off the table on the way, the way a tile picked up would be.
327 l.body.z = Math.sin(l.t * Math.PI) * 40;
328 l.body.angle += seconds * 2.2;
329 }
330 this.leaving = this.leaving.filter((l) => l.t < 1);
331 }
332
333 /** What is on its way off, and how far gone, for the renderer to fade. */
334 get departing(): { body: Body; fade: number }[] {
335 return this.leaving.map((l) => ({ body: l.body, fade: 1 - l.t }));
336 }
337
338 get bodies(): Body[] {
339 return this.world?.bodies ?? [];
340 }
341
342 /** The tile on the table, if there is one — drawn lit, as a lifted tile is. */
343 get newest(): Body | null {
344 return (this.newestKey && this.entries.get(this.newestKey)) || null;
345 }
346
347 /**
348 * A tile is still on its way to the middle. The computer players hold off
349 * while this is true — nobody at a real table reaches across for a tile that
350 * has not landed, and a 碰 called over one still turning over in the air looks
351 * like it was snatched out of flight.
352 */
353 get throwInFlight(): boolean {
354 const b = this.newest;
355 return !!b && !b.resting;
356 }
357
358 /** Nothing is moving, so the render loop can stop until something changes. */
359 get settled(): boolean {
360 return !this.held && this.leaving.length === 0 && (!this.world || settled(this.world));
361 }
362
363 // ---- measuring ---------------------------------------------------------
364
365 /**
366 * Re-read the table when the wall's shape has changed or the window has. The
367 * pile keeps its positions across a re-measure: the wall shrinking does not
368 * move the tiles already on the felt.
369 */
370 private remeasure(state: GameState) {
371 const table = this.table;
372 if (!table) return;
373 const stamp = `${state.drawnFront}/${state.drawnBack}/${Math.round(
374 table.clientWidth,
375 )}x${Math.round(table.clientHeight)}`;
376 if (stamp === this.measuredAt) return;
377
378 const geo = measure(table, state);
379 this.measuredAt = geo ? stamp : '';
380 this.geo = geo;
381 if (!geo) {
382 this.world = null;
383 this.entries.clear();
384 this.setOpenness('----');
385 return;
386 }
387 // Bounded by the felt, not by the square: what keeps a tile in the middle is
388 // the stacks still standing, and once they are gone the pool is free to
389 // spread out through the gap the way a real one does.
390 if (!this.world) this.world = createWorld(geo.felt, geo.walls);
391 else reshape(this.world, geo.felt, geo.walls);
392 // Only here, never per frame: a hundred-odd ray casts is nothing once a
393 // draw, and a great deal every sixtieth of a second.
394 this.setOpenness(SEATS.map((s) => (canThrow(geo, s) ? 'y' : '-')).join(''));
395 }
396
397 private setOpenness(next: string) {
398 if (next === this.openness) return;
399 this.openness = next;
400 for (const cb of this.listeners) cb();
401 }
402
403 // ---- putting tiles in -------------------------------------------------
404
405 /** A tile that is simply there already — a rebuilt pile. */
406 private settle(
407 geo: TableGeometry,
408 state: GameState,
409 a: { seat: SeatId; index: number; tile: Tile },
410 ): Body {
411 const rng = this.seeded(state, a);
412 const { pool } = geo;
413 // Bunched towards the middle rather than spread evenly to the edges, which
414 // is what a pool thrown into from four sides actually looks like.
415 const spread = 0.3;
416 return addBody(this.world!, {
417 tile: a.tile,
418 seat: a.seat,
419 x: pool.x + pool.w * (0.5 + (rng() - 0.5) * 2 * spread),
420 y: pool.y + pool.h * (0.5 + (rng() - 0.5) * 2 * spread),
421 vx: 0,
422 vy: 0,
423 z: 0,
424 vz: 0,
425 angle: (rng() - 0.5) * Math.PI,
426 spin: 0,
427 w: geo.tile.w,
428 h: geo.tile.h,
429 atRest: true,
430 });
431 }
432
433 /** A tile arriving now: thrown if somebody threw it, placed over the wall if
434 * it was tapped, and flat and quick if a bot's wall happens to be open. */
435 private launch(
436 geo: TableGeometry,
437 state: GameState,
438 a: { seat: SeatId; index: number; tile: Tile },
439 ): Body {
440 const rng = this.seeded(state, a);
441 const thrown = this.release?.seat === a.seat ? this.release : null;
442
443 if (thrown) {
444 // Which of the two ways a tile goes in, decided by what is in its way.
445 //
446 // A clear line to the square means it can be *slid* — flat across the
447 // cloth, at exactly the speed it was let go at, which is what a flick
448 // wants to be. A standing wall means it has to be *thrown* instead: lifted
449 // over the top and dropped in, and then the flick's speed decides how far
450 // across the pool it lands rather than how fast it skates.
451 // Sliding is the preferred way in, and the question is asked from where
452 // the tile actually is — a player who carried it out over the square has a
453 // clear line even though the seat they came from does not. Only a tile
454 // with nothing but standing wall in front of it has to be lobbed.
455 const set = this.inPool(thrown.x, thrown.y);
456 const slide = set || !LOB_WHEN_WALLED || this.canThrowFrom(thrown.x, thrown.y);
457 let { vx, vy } = thrown;
458 let vz = 0;
459 const speed = Math.hypot(vx, vy);
460 let flipTurns = 0;
461 let flipOver = 0;
462
463 if (!slide) {
464 // Lofted over a standing wall. It still has to *land* on the table
465 // rather than sail off the far side, so there is a ceiling on how fast
466 // it can cross — but a generous one: a hard throw is meant to reach the
467 // far wall, come off it and barge through the pile, and only a limp one
468 // should drop in the middle and stay there.
469 const centre = centreOf(geo.pool);
470 const reach = PLACE_FLIGHT + SLIDE_TIME;
471 const cap = (Math.hypot(centre.x - thrown.x, centre.y - thrown.y) / reach) * 2.4;
472 const aim = Math.min(speed, cap) / (speed || 1);
473 vx *= aim;
474 vy *= aim;
475 vz = liftFor(PLACE_FLIGHT);
476 // Long enough in the air to turn over properly, and harder means more.
477 flipOver = PLACE_FLIGHT;
478 flipTurns = speed > 1300 ? 2 : 1;
479 } else if (!set) {
480 // A skated tile leaves the fingers off the cloth, and turns over on its
481 // way down — harder means longer in the air and more turns in it.
482 const hop = THROW_LIFT + Math.min(0.22, (speed / MAX_THROW_SPEED) * 0.28);
483 vz = liftFor(hop);
484 flipOver = hop;
485 flipTurns = speed > 2200 ? 2 : speed > 600 ? 1 : 0;
486 }
487
488 return addBody(this.world!, {
489 tile: a.tile,
490 seat: a.seat,
491 x: thrown.x,
492 y: thrown.y,
493 vx,
494 vy,
495 z: 0,
496 vz,
497 angle: thrown.angle,
498 spin: thrown.spin,
499 flipTurns,
500 flipOver,
501 // It tumbles across its line of travel, the way a thrown tile does.
502 flipAxis: Math.atan2(vy, vx),
503 w: geo.tile.w,
504 h: geo.tile.h,
505 // It was drawn at hand size a moment ago; it shrinks on the way down.
506 scale: thrown.w / geo.tile.w,
507 });
508 }
509
510 // Off the end of the hand, not the middle of it — a tile is thrown from the
511 // hand holding it, which is the one at the right-hand end of the row.
512 const from = geo.throwFrom[a.seat] ?? geo.launch[a.seat] ?? centreOf(geo.pool);
513 const open = !LOB_WHEN_WALLED || this.canThrow(a.seat);
514 const target = this.aimFor(geo, a.seat, rng);
515 // Aim for where it comes to *rest*, not where it first touches down: a tile
516 // keeps sliding after it lands, and SLIDE_TIME is roughly how much further.
517 const flight = open ? 0.34 + rng() * 0.1 : PLACE_FLIGHT;
518 const reach = flight + SLIDE_TIME;
519
520 const vx = (target.x - from.x) / reach;
521 const vy = (target.y - from.y) / reach;
522 return addBody(this.world!, {
523 tile: a.tile,
524 seat: a.seat,
525 x: from.x,
526 y: from.y,
527 vx,
528 vy,
529 z: 0,
530 vz: liftFor(flight),
531 angle: (rng() - 0.5) * Math.PI,
532 spin: (rng() - 0.5) * (open ? 7 : 2.5),
533 // It turns over on its way in, whichever way it is going.
534 flipTurns: 1,
535 flipOver: flight,
536 flipAxis: Math.atan2(vy, vx),
537 w: geo.tile.w,
538 h: geo.tile.h,
539 });
540 }
541
542 /** Where a tile from this seat is headed, with a little scatter. */
543 private aimFor(geo: TableGeometry, seat: SeatId, rng: () => number): Point {
544 const base = aimAt(geo, seat) ?? centreOf(geo.pool);
545 const jitter = Math.min(geo.pool.w, geo.pool.h) * 0.22;
546 return { x: base.x + (rng() - 0.5) * jitter, y: base.y + (rng() - 0.5) * jitter };
547 }
548
549 /**
550 * A tile's own random stream. Keyed on the hand and its place in that seat's
551 * discards, so the same tile scatters the same way every time it is rebuilt —
552 * a refresh mid-hand puts the pile back exactly as it was.
553 */
554 private seeded(state: GameState, a: { seat: SeatId; index: number; tile: Tile }) {
555 return makeRng(state.handNumber * 7919 + a.seat * 977 + a.index * 31 + a.tile + 1);
556 }
557}