anvilsign in

collin/mahjong

1import type { NetThrow } from '../game/ctl';
2import type { GameState } from '../game/engine';
3import { makeRng, type Tile } from '../game/tiles';
4import type { SeatId } from '../game/types';
5import { SEAT_ROT } from '../ui/rotation';
6import {
7 aimAt,
8 canThrow,
9 canThrowFrom,
10 centreOf,
11 measure,
12 type Point,
13 type TableGeometry,
14} from './geometry';
15import {
16 addBody,
17 advance as advanceWorld,
18 createWorld,
19 liftFor,
20 reshape,
21 settled,
22 drop,
23 lift,
24 tileAt,
25 SLIDE_TIME,
26 type Body,
27 type Impact,
28 type Rect,
29 type World,
30} from './physics';
31
32const SEATS: SeatId[] = [0, 1, 2, 3];
33
34/**
35 * The tiles in the middle, kept honest against the game state.
36 *
37 * This *diffs* rather than listening for events, and that is the whole design.
38 * A discard is identified by which seat threw it and how many it had thrown
39 * before — and those keys never shift, because discards are only ever pushed and
40 * `engine.executeClaim` only ever pops the one on top. So every way the pile can
41 * change is the same code path: a key that has appeared is a tile to throw in, a
42 * key that has gone is a tile to take out. Undo, 下一局, a claim, and picking up
43 * a saved game all fall out of that without the engine knowing this exists.
44 *
45 * Nothing here is stored in the game state, so there is no save format to
46 * change. A pile is rebuilt from the discards it can see, seeded off the hand
47 * number and each tile's place in it, which is why a refresh mid-hand comes back
48 * to the pile it had rather than a freshly scattered one.
49 */
50
51/** How long a placed tile is in the air. Long enough to arc over the wall. */
52const PLACE_FLIGHT = 0.62;
53/** A flicked tile hops rather than lofts — across the table, not over a wall. */
54const THROW_LIFT = 0.18;
55/** Fastest flick we will honour, px/s. Beyond this it is a slip, not a throw. */
56export const MAX_THROW_SPEED = 3600;
57/** How long a claimed tile takes to leave the table for the seat taking it. */
58const TAKE_FLIGHT = 0.34;
59
60/** A tile on its way off the table, no longer part of the pile. */
61interface Leaving {
62 body: Body;
63 tx: number;
64 ty: number;
65 /** 0 to 1. */
66 t: number;
67}
68
69/**
70 * Whether a tile turns over on its way in.
71 *
72 * Off for now. Like `LOB_WHEN_WALLED` below, the tumble is kept whole — the
73 * flip is a real axis in `physics.ts` and the renderer already squashes the
74 * tile along it — and this is the only switch that reaches it, so putting it
75 * back is one word rather than a rewrite.
76 */
77const TUMBLE: boolean = false;
78
79/**
80 * Whether a wall standing in the way turns a discard into a lob over the top
81 * rather than a flick across the table.
82 *
83 * Back on now that the square is a square again. It was off while the wall ran
84 * along the edges of the middle, where there was nothing much to get over and
85 * everything read better slid; a square standing in the middle with the pool
86 * inside it is the other case, and a tile slid flat at it simply bounces off
87 * and ends up lying outside — which is not where a discard goes. As the square
88 * is eaten the gaps open and the slide comes back on its own, seat by seat.
89 */
90const LOB_WHEN_WALLED: boolean = true;
91
92/** How many sandbox throws stay on the table before the oldest is swept off.
93 * A wall's worth: enough to test a crowded pool, not enough to bury it. */
94const LOOSE_LIMIT = 60;
95
96/**
97 * The join tile is the size every other tile is — `geo.tile`, which is the size
98 * of a tile in a hand, because they are the same tiles. It was drawn bigger for
99 * a while so the code would be easier to read, and a tile in the middle that is
100 * not tile-sized reads as a card lying on the table rather than as one of the
101 * set. A phone leans in the extra inch.
102 */
103const JOIN_SCALE = 1;
104/** How it lies. Nothing on a table is ever quite square to it. */
105const JOIN_ANGLE = -0.07;
106
107/** Let go of moving faster than this and it was a flick, not a place. Slow
108 * enough that putting a tile down deliberately never sends it skidding. */
109const DRAG_FLICK = 260;
110
111/** A tile lifted out of a hand and carried about. Drawn, but not simulated. */
112export interface Held {
113 seat: SeatId;
114 tile: Tile;
115 /** Where it came from in that seat's hand, so the caller knows what to play. */
116 index: number;
117 x: number;
118 y: number;
119 angle: number;
120 /** The size it was in the hand — it shrinks to pool size once thrown. */
121 w: number;
122 h: number;
123}
124
125/** One throw, as the overlay wants to see it: let go of at (x, y) along
126 * (fx, fy), and actually sent along (vx, vy). `how` says why they differ. */
127export interface ThrowMark {
128 x: number;
129 y: number;
130 fx: number;
131 fy: number;
132 vx: number;
133 vy: number;
134 how: string;
135}
136
137/** A throw that has been let go of, waiting for the discard it belongs to. */
138interface Release {
139 seat: SeatId;
140 x: number;
141 y: number;
142 angle: number;
143 w: number;
144 h: number;
145 vx: number;
146 vy: number;
147 spin: number;
148}
149
150export class TablePool {
151 world: World | null = null;
152 geo: TableGeometry | null = null;
153 /** The tile in somebody's fingers, if any. */
154 held: Held | null = null;
155 /**
156 * Poke the render loop. Set by ui/Pool.tsx while it is mounted; a gesture
157 * calls it so a carried tile follows the finger without waiting on a re-render.
158 */
159 wake: () => void = () => {};
160
161 private table: HTMLElement | null = null;
162 /** Bodies by `seat:index` into that seat's discards. */
163 private entries = new Map<string, Body>();
164 private release: Release | null = null;
165 /** When the throw was let go of. Online its discard takes a round-trip to
166 * come back, so a release has to be able to outlive a few frames. */
167 private releasedAt = 0;
168 /** What the wall looked like when we last measured, so we know to re-measure. */
169 private measuredAt = '';
170 private hand = -1;
171 /** The tile currently on the table to be claimed, so it can be marked. */
172 private newestKey: string | null = null;
173 /** How many melds each seat had last time, to spot who took a tile. */
174 private melds = [0, 0, 0, 0];
175 /** Tiles on their way off the table. Drawn, but out of the physics. */
176 private leaving: Leaving[] = [];
177 /**
178 * The last few throws: where each was let go of, the line it was let go
179 * *along*, and the line it actually left on.
180 *
181 * Read by the collider overlay and by nothing else. A throw is not always
182 * sent where it was aimed — a flick with standing wall in front of it is
183 * lobbed rather than slid, and one whose line misses the square altogether is
184 * re-aimed at the middle of it — and a tile that leaves on a line nobody
185 * threw reads exactly like a tile that bounced off something invisible.
186 */
187 throws: ThrowMark[] = [];
188 /** The discard being dragged about, if any. */
189 private carried: Body | null = null;
190 /**
191 * Sandbox throws: real tiles in the real world, but belonging to no discard,
192 * so the reconciler never looks at them — nothing in `entries` means nothing
193 * to cull. See `throwLoose`.
194 */
195 private loose: Body[] = [];
196 /**
197 * The tile with the room's QR on its face — a real body in the real world,
198 * belonging to no discard, so the reconciler never looks at it.
199 *
200 * It is a tile like any other. It takes a knock from a discard thrown at it,
201 * it slides, it can be picked up and put somewhere less in the way, and it
202 * throws a shadow on the felt. What is different about it is only its face,
203 * which the renderer paints rather than cutting out of the sheet, and its
204 * size, which a phone has to be able to read from across the table.
205 */
206 joinTile: Body | null = null;
207 /** When the table will have stopped talking. See `heckle`. */
208 private quietAt = 0;
209
210 // Which seats can throw, as a string, so the seats can re-render when it
211 // changes. Read through useSyncExternalStore, the same way the game is.
212 private openness = '----';
213 private listeners = new Set<() => void>();
214
215 attach(table: HTMLElement) {
216 this.table = table;
217 this.measuredAt = '';
218 }
219
220 detach() {
221 this.table = null;
222 this.world = null;
223 this.geo = null;
224 this.loose = [];
225 this.joinTile = null;
226 this.carried = null;
227 this.held = null;
228 this.release = null;
229 this.entries.clear();
230 this.leaving = [];
231 this.measuredAt = '';
232 }
233
234 subscribe = (cb: () => void) => {
235 this.listeners.add(cb);
236 return () => this.listeners.delete(cb);
237 };
238
239 /** Which seats have a clear line in, as a string — cheap to compare. */
240 getSnapshot = () => this.openness;
241
242 /** Force a re-measure — the window resized, or the layout changed under us. */
243 invalidate() {
244 this.measuredAt = '';
245 }
246
247 /**
248 * Whether this seat can flick a tile in, or has to lift it over the wall.
249 * Unmeasured (or compact, where there is no square) means no.
250 */
251 canThrow(seat: SeatId): boolean {
252 return this.openness[seat] === 'y';
253 }
254
255 /** Where the middle of the table is, for a gesture working out its aim. */
256 get poolCentre(): Point | null {
257 return this.geo ? centreOf(this.geo.pool) : null;
258 }
259
260 /** Whether a point is already inside the square — a tile dropped there stays. */
261 inPool(x: number, y: number): boolean {
262 const p = this.geo?.pool;
263 if (!p) return false;
264 return x >= p.x && x <= p.x + p.w && y >= p.y && y <= p.y + p.h;
265 }
266
267 /** Whether a tile let go of *here* has a clear line in. Not the same question
268 * as `canThrow(seat)`: a carried tile is wherever the player took it. */
269 canThrowFrom(x: number, y: number): boolean {
270 return !!this.geo && canThrowFrom(this.geo, { x, y });
271 }
272
273 /** Where the pool sits on the table, for the patch of it you can reach into. */
274 get poolRect(): Rect | null {
275 return this.geo?.pool ?? null;
276 }
277
278 /**
279 * Take hold of whatever discard is under the finger.
280 *
281 * The pile is a pile of tiles, so the thing you do to it is pick one up and
282 * put it somewhere else — which is what everybody does to a pool of discards
283 * while waiting for their turn. It comes up out of the pile and is carried
284 * over the top of it rather than ploughing through it.
285 */
286 grabAt(x: number, y: number): boolean {
287 if (!this.world) return false;
288 const b = tileAt(this.world, x, y);
289 if (!b) return false;
290 lift(b);
291 this.carried = b;
292 return true;
293 }
294
295 /** Follow the finger. A carried tile is placed, not pushed. */
296 dragTo(x: number, y: number, angle?: number) {
297 const b = this.carried;
298 if (!b) return;
299 b.x = x;
300 b.y = y;
301 if (angle !== undefined) b.angle = angle;
302 }
303
304 /**
305 * Let go. Slowly, and it is put down where it is; flicked, and it goes off
306 * across the felt at the speed it left the fingers — the same throw a tile
307 * gets out of a hand, made from the middle of the table instead.
308 */
309 releaseGrab(vx: number, vy: number, spin: number) {
310 const b = this.carried;
311 if (!b) return;
312 this.carried = null;
313 const speed = Math.hypot(vx, vy);
314 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
315 const flick = speed > DRAG_FLICK;
316 drop(b, flick ? vx * scale : 0, flick ? vy * scale : 0, flick ? spin : 0);
317 }
318
319 /** Whether a discard is in somebody's fingers right now. */
320 get dragging(): boolean {
321 return !!this.carried;
322 }
323
324 // ---- the tile in your fingers -----------------------------------------
325
326 /** Lifted out of a hand. From here the canvas draws it, not the DOM. */
327 pickUp(held: Held) {
328 this.held = held;
329 }
330
331 moveHeld(x: number, y: number, angle?: number) {
332 if (!this.held) return;
333 this.held.x = x;
334 this.held.y = y;
335 if (angle !== undefined) this.held.angle = angle;
336 }
337
338 /** Put it back in the hand — the throw was not committed to. */
339 cancelHeld() {
340 this.held = null;
341 }
342
343 /**
344 * Let go of it. The body is not made here: the reconciler owns every tile in
345 * the pool, so this leaves the throw where the next `sync` will find it and
346 * the caller goes on to call `game.discard`. The held tile stays drawn until
347 * that happens, so there is no frame with nothing on screen.
348 */
349 throwHeld(vx: number, vy: number, spin: number) {
350 const h = this.held;
351 if (!h) return;
352 const speed = Math.hypot(vx, vy);
353 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
354 this.release = {
355 seat: h.seat,
356 x: h.x,
357 y: h.y,
358 angle: h.angle,
359 w: h.w,
360 h: h.h,
361 vx: vx * scale,
362 vy: vy * scale,
363 spin,
364 };
365 this.releasedAt = Date.now();
366 }
367
368 /**
369 * A throw that is not a discard.
370 *
371 * The tile stays in the hand, the game does not move, and the body goes
372 * straight into the world rather than waiting for a discard to arrive and
373 * claim it. For throwing the same tile a hundred times with the colliders
374 * drawn, which is the only way to tell a bounce that is wrong from a bounce
375 * that only looks wrong.
376 */
377 throwLoose(vx: number, vy: number, spin: number) {
378 const h = this.held;
379 const geo = this.geo;
380 const world = this.world;
381 if (!h || !geo || !world) return;
382 const speed = Math.hypot(vx, vy);
383 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
384 this.loose.push(
385 this.fling(geo, h.tile, {
386 seat: h.seat,
387 x: h.x,
388 y: h.y,
389 angle: h.angle,
390 w: h.w,
391 h: h.h,
392 vx: vx * scale,
393 vy: vy * scale,
394 spin,
395 }),
396 );
397 // Oldest off the table first, or an afternoon of this buries the felt and
398 // every throw lands on a pile instead of on the thing being tested.
399 while (this.loose.length > LOOSE_LIMIT) this.drop(this.loose.shift()!);
400 this.held = null;
401 }
402
403 /** Sweep the sandbox's tiles away and start again. */
404 clearLoose() {
405 for (const b of this.loose) this.drop(b);
406 this.loose = [];
407 }
408
409 private drop(body: Body) {
410 const at = this.world?.bodies.indexOf(body) ?? -1;
411 if (at >= 0) this.world!.bodies.splice(at, 1);
412 }
413
414 /**
415 * A throw that happened on somebody's phone, arriving over the wire in their
416 * own frame: `u` along their edge, `vy` into the table. It is stood at their
417 * side of this screen and turned into the table's coordinates, so the tile
418 * flies in from off their edge — from where they are sitting, as a thrown
419 * tile should. The discard it belongs to arrives through the state as usual;
420 * this only decides how it enters.
421 */
422 throwFromNet(seat: SeatId, t: NetThrow) {
423 const geo = this.geo;
424 if (!geo) return;
425 const f = geo.felt;
426 // Just beyond the felt, where the thrower's strip is.
427 const m = geo.tile.h * 1.4;
428 const u = Math.min(1, Math.max(0, t.u));
429 let x: number;
430 let y: number;
431 let vx: number;
432 let vy: number;
433 // Each seat's frame: x runs to the player's right along their edge, y into
434 // the table. The screen rotation for each seat is what `ROT` says it is.
435 switch (seat) {
436 case 0:
437 x = f.x + u * f.w;
438 y = f.y + f.h + m;
439 vx = t.vx;
440 vy = -t.vy;
441 break;
442 case 1:
443 x = f.x + f.w + m;
444 y = f.y + (1 - u) * f.h;
445 vx = -t.vy;
446 vy = -t.vx;
447 break;
448 case 2:
449 x = f.x + (1 - u) * f.w;
450 y = f.y - m;
451 vx = -t.vx;
452 vy = t.vy;
453 break;
454 default:
455 x = f.x - m;
456 y = f.y + u * f.h;
457 vx = t.vy;
458 vy = t.vx;
459 break;
460 }
461 const speed = Math.hypot(vx, vy);
462 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
463 this.release = {
464 seat,
465 x,
466 y,
467 // Facing its thrower, the way a tile lifted from their hand would be.
468 angle: (SEAT_ROT[seat] * Math.PI) / 180,
469 w: geo.tile.w,
470 h: geo.tile.h,
471 vx: vx * scale,
472 vy: vy * scale,
473 spin: t.spin,
474 };
475 this.releasedAt = Date.now();
476 }
477
478 // ---- keeping up with the game ----------------------------------------
479
480 /** Bring the pile in line with the state. Cheap when nothing has changed. */
481 sync(state: GameState) {
482 this.remeasure(state);
483 const geo = this.geo;
484 const world = this.world;
485 if (!geo || !world) return;
486
487 // A new hand is a new pile, and nothing should fly anywhere.
488 const fresh = state.handNumber !== this.hand;
489 this.hand = state.handNumber;
490 // The pile it was shoved to the edge of has just been swept away, so the
491 // QR goes back where a thing to be scanned belongs. Left alone it would
492 // spend an evening being nudged further into a corner.
493 if (fresh && this.joinTile) {
494 const c = centreOf(geo.pool);
495 this.joinTile.x = c.x;
496 this.joinTile.y = c.y;
497 this.joinTile.z = 0;
498 this.joinTile.vx = 0;
499 this.joinTile.vy = 0;
500 this.joinTile.vz = 0;
501 this.joinTile.angle = JOIN_ANGLE;
502 this.joinTile.spin = 0;
503 }
504
505 const want = new Set<string>();
506 const added: { key: string; seat: SeatId; index: number; tile: Tile }[] = [];
507 for (const seat of SEATS) {
508 const discards = state.players[seat].discards;
509 for (let i = 0; i < discards.length; i++) {
510 const key = `${seat}:${i}`;
511 want.add(key);
512 if (!this.entries.has(key)) added.push({ key, seat, index: i, tile: discards[i] });
513 }
514 }
515
516 const taken: Body[] = [];
517 for (const [key, body] of this.entries) {
518 if (want.has(key)) continue;
519 const at = world.bodies.indexOf(body);
520 if (at >= 0) world.bodies.splice(at, 1);
521 // Claimed out from under the finger holding it.
522 if (this.carried === body) this.carried = null;
523 this.entries.delete(key);
524 taken.push(body);
525 }
526
527 // Exactly one tile off the table is somebody taking it — a 碰, a 吃, a 槓,
528 // or a discard being taken back. It goes to whoever now has a meld they did
529 // not have a moment ago, and failing that back to the seat that threw it,
530 // which is what an undo is. Several at once is the hand ending, and those
531 // simply go.
532 const claimer = SEATS.find((q) => state.players[q].melds.length > this.melds[q]);
533 this.melds = SEATS.map((q) => state.players[q].melds.length);
534 if (taken.length === 1 && !fresh) {
535 const to = geo.launch[claimer ?? taken[0].seat];
536 if (to) this.leaving.push({ body: taken[0], tx: to.x, ty: to.y, t: 0 });
537 }
538
539 // One tile at a time is somebody playing, and it gets thrown. Several at
540 // once is a pile being rebuilt — a save picked up, an undo, a fresh deal —
541 // and those tiles were thrown long ago, so they are simply already there.
542 const rebuilding = fresh || added.length > 1;
543 for (const a of added) {
544 this.entries.set(a.key, rebuilding ? this.settle(geo, state, a) : this.launch(geo, state, a));
545 }
546
547 // A throw is good for exactly one discard. At a local table the discard is
548 // in the state before the next frame, so the tile has either just arrived
549 // or is never going to; online it is out on a round-trip, so the release
550 // waits — but not forever, in case the host turned the move down.
551 if (added.length || (this.release && Date.now() - this.releasedAt > 2500)) {
552 this.release = null;
553 this.held = null;
554 }
555
556 const ld = state.lastDiscard;
557 this.newestKey = ld ? `${ld.from}:${state.players[ld.from].discards.length - 1}` : null;
558 }
559
560 /**
561 * Whether the room's QR is lying on the table.
562 *
563 * Called every frame with the answer, so it comes and goes with the room
564 * itself: no server to reach and there is simply no tile, which is the whole
565 * of the offline story. Adding it is idempotent; the body it makes is the
566 * one that stays until the room does.
567 */
568 setJoinTile(show: boolean) {
569 const world = this.world;
570 const geo = this.geo;
571 if (!world || !geo) return;
572 if (!show) {
573 if (this.joinTile) {
574 const at = world.bodies.indexOf(this.joinTile);
575 if (at >= 0) world.bodies.splice(at, 1);
576 if (this.carried === this.joinTile) this.carried = null;
577 this.joinTile = null;
578 }
579 return;
580 }
581 if (this.joinTile && world.bodies.includes(this.joinTile)) return;
582 this.joinTile = this.placeJoinTile(geo);
583 }
584
585 /** Lay it in the middle of the felt, at rest. */
586 private placeJoinTile(geo: TableGeometry): Body {
587 const c = centreOf(geo.pool);
588 return addBody(this.world!, {
589 // Never drawn from the sheet — the renderer paints this one's face — so
590 // the tile it claims to be is only what the physics needs it not to be
591 // undefined.
592 tile: 0 as Tile,
593 seat: 0,
594 x: c.x,
595 y: c.y,
596 vx: 0,
597 vy: 0,
598 z: 0,
599 vz: 0,
600 angle: JOIN_ANGLE,
601 spin: 0,
602 w: geo.tile.w * JOIN_SCALE,
603 h: geo.tile.h * JOIN_SCALE,
604 atRest: true,
605 });
606 }
607
608 /** Run the physics on. Returns impacts worth a sound. */
609 advance(seconds: number, stopOnImpact = false): Impact[] {
610 this.carryOff(seconds);
611 return this.world ? advanceWorld(this.world, seconds, stopOnImpact) : [];
612 }
613
614 /** Tiles leaving the table, lifted and carried off to the seat taking them. */
615 private carryOff(seconds: number) {
616 if (this.leaving.length === 0) return;
617 for (const l of this.leaving) {
618 l.t = Math.min(1, l.t + seconds / TAKE_FLIGHT);
619 // Ease out, so it leaves quickly and arrives gently.
620 const k = 1 - (1 - l.t) * (1 - l.t);
621 l.body.x += (l.tx - l.body.x) * k * 0.5;
622 l.body.y += (l.ty - l.body.y) * k * 0.5;
623 // Up off the table on the way, the way a tile picked up would be.
624 l.body.z = Math.sin(l.t * Math.PI) * 40;
625 l.body.angle += seconds * 2.2;
626 }
627 this.leaving = this.leaving.filter((l) => l.t < 1);
628 }
629
630 /** What is on its way off, and how far gone, for the renderer to fade. */
631 get departing(): { body: Body; fade: number }[] {
632 return this.leaving.map((l) => ({ body: l.body, fade: 1 - l.t }));
633 }
634
635 get bodies(): Body[] {
636 return this.world?.bodies ?? [];
637 }
638
639 /** The tile on the table, if there is one — drawn lit, as a lifted tile is. */
640 get newest(): Body | null {
641 return (this.newestKey && this.entries.get(this.newestKey)) || null;
642 }
643
644 /**
645 * A tile is still on its way to the middle. The computer players hold off
646 * while this is true — nobody at a real table reaches across for a tile that
647 * has not landed, and a 碰 called over one still turning over in the air looks
648 * like it was snatched out of flight.
649 */
650 get throwInFlight(): boolean {
651 const b = this.newest;
652 return !!b && !b.resting;
653 }
654
655 /**
656 * Somebody is being told off for where they put that tile. Held for as long
657 * as the line takes to say, told to us by whoever is saying it.
658 */
659 heckle(seconds: number) {
660 this.quietAt = Math.max(this.quietAt, Date.now() + seconds * 1000);
661 }
662
663 /**
664 * Whether the table is mid-something and a computer player should wait: a
665 * tile still in the air, or a player still complaining about the last one.
666 * Reaching for a tile over the top of somebody objecting to it lands the
667 * objection on nobody.
668 */
669 get busy(): boolean {
670 return this.throwInFlight || Date.now() < this.quietAt;
671 }
672
673 /** Nothing is moving, so the render loop can stop until something changes. */
674 get settled(): boolean {
675 return (
676 !this.held &&
677 !this.carried &&
678 this.leaving.length === 0 &&
679 (!this.world || settled(this.world))
680 );
681 }
682
683 // ---- measuring ---------------------------------------------------------
684
685 /**
686 * Re-read the table when the wall's shape has changed or the window has. The
687 * pile keeps its positions across a re-measure: the wall shrinking does not
688 * move the tiles already on the felt.
689 */
690 private remeasure(state: GameState) {
691 const table = this.table;
692 if (!table) return;
693 // Every tile on the table is a collider now, so the shape of each hand and
694 // each set laid down is part of what has to be re-read — not just the wall.
695 const hands = state.players.map((p) => `${p.hand.length}.${p.melds.length}.${p.flowers.length}`);
696 const stamp = `${state.drawnFront}/${state.drawnBack}/${hands.join(',')}/${Math.round(
697 table.clientWidth,
698 )}x${Math.round(table.clientHeight)}`;
699 if (stamp === this.measuredAt) return;
700
701 const was = this.geo;
702 const geo = measure(table);
703 this.measuredAt = geo ? stamp : '';
704 this.geo = geo;
705 if (!geo) {
706 this.world = null;
707 this.entries.clear();
708 this.setOpenness('----');
709 return;
710 }
711 // What keeps a tile in is the tiles: the stacks still standing, the sets
712 // laid down, and the hands beyond them. `felt` is the table's own edge and
713 // is only there so a tile that got past all of that is still on the table.
714 if (!this.world) {
715 this.world = createWorld(geo.felt, geo.barriers);
716 } else {
717 // The table changed size under the pile, so the pile changes with it.
718 // Before it moves anything about.
719 this.rescale(was, geo);
720 reshape(this.world, geo.felt, geo.barriers);
721 }
722 // Only here, never per frame: a hundred-odd ray casts is nothing once a
723 // draw, and a great deal every sixtieth of a second.
724 this.setOpenness(SEATS.map((s) => (canThrow(geo, s) ? 'y' : '-')).join(''));
725 }
726
727 /**
728 * The window was resized, so every tile in the middle is the wrong size and
729 * in the wrong place.
730 *
731 * A tile in the pool is drawn the size the tiles in the hands are, and those
732 * are sized off the window — so a pile dealt into a small window and then
733 * looked at full-screen was a pile of small tiles among big ones, which is a
734 * mistake you can see rather than measure. The same goes for where they are
735 * lying: the square they were thrown into has moved and stretched, and tiles
736 * left at their old coordinates bunch into whichever corner the square used
737 * to reach. `reshape` clamps them back inside, which stops them being lost
738 * but stacks them along an edge.
739 *
740 * So the pile is mapped from the old square into the new one and scaled by
741 * the same ratio the tiles are — the pile you had, at the size the table is
742 * now. Velocities go with it, so a tile still skidding when the window moves
743 * carries on skidding at the same speed relative to the felt rather than
744 * suddenly crossing it faster or slower than it was.
745 */
746 private rescale(was: TableGeometry | null, geo: TableGeometry) {
747 const world = this.world;
748 if (!world || !was || was.pool.w <= 0 || was.pool.h <= 0 || was.tile.w <= 0) return;
749 const k = geo.tile.w / was.tile.w;
750 const sx = geo.pool.w / was.pool.w;
751 const sy = geo.pool.h / was.pool.h;
752 // A discard thrown does not resize the table; only a resize does.
753 if (Math.abs(k - 1) < 0.001 && Math.abs(sx - 1) < 0.001 && Math.abs(sy - 1) < 0.001) return;
754 const map = (b: { x: number; y: number }) => {
755 b.x = geo.pool.x + (b.x - was.pool.x) * sx;
756 b.y = geo.pool.y + (b.y - was.pool.y) * sy;
757 };
758 for (const b of world.bodies) {
759 map(b);
760 b.w *= k;
761 b.h *= k;
762 b.z *= k;
763 b.vx *= sx;
764 b.vy *= sy;
765 b.vz *= k;
766 }
767 // On their way to whoever claimed them: the seat they are flying at has
768 // moved too, and `geo.launch` is where it moved to.
769 for (const l of this.leaving) {
770 const to = geo.launch[l.body.seat];
771 if (!to) continue;
772 l.tx = to.x;
773 l.ty = to.y;
774 }
775 // And the tile in somebody's fingers, which the canvas is drawing at the
776 // size it was lifted at.
777 if (this.held) {
778 this.held.w *= k;
779 this.held.h *= k;
780 }
781 }
782
783 private setOpenness(next: string) {
784 if (next === this.openness) return;
785 this.openness = next;
786 for (const cb of this.listeners) cb();
787 }
788
789 // ---- putting tiles in -------------------------------------------------
790
791 /** A tile that is simply there already — a rebuilt pile. */
792 private settle(
793 geo: TableGeometry,
794 state: GameState,
795 a: { seat: SeatId; index: number; tile: Tile },
796 ): Body {
797 const rng = this.seeded(state, a);
798 const { pool } = geo;
799 // Bunched towards the middle rather than spread evenly to the edges, which
800 // is what a pool thrown into from four sides actually looks like.
801 const spread = 0.3;
802 return addBody(this.world!, {
803 tile: a.tile,
804 seat: a.seat,
805 x: pool.x + pool.w * (0.5 + (rng() - 0.5) * 2 * spread),
806 y: pool.y + pool.h * (0.5 + (rng() - 0.5) * 2 * spread),
807 vx: 0,
808 vy: 0,
809 z: 0,
810 vz: 0,
811 angle: (rng() - 0.5) * Math.PI,
812 spin: 0,
813 w: geo.tile.w,
814 h: geo.tile.h,
815 atRest: true,
816 });
817 }
818
819 /**
820 * A tile let go of by a hand: what a flick actually becomes.
821 *
822 * Its own method because a throw is not always a discard — the sandbox
823 * behind ?colliders throws the same tile over and over without the game
824 * moving at all, and it has to be the *same* throw or there would be no
825 * point testing with it.
826 */
827 private fling(geo: TableGeometry, tile: Tile, thrown: Release): Body {
828 // The flick is the throw. Where the tile goes and how fast it gets there
829 // are both the hand's business, and nothing here touches either — a tile
830 // that leaves at an angle to the flick that made it reads as a bounce off
831 // something invisible, and there is nothing there to bounce off.
832 //
833 // The one thing still decided here is *height*, which is not aim. With a
834 // standing wall in front of the throw a flat tile would only skid into it,
835 // so it is lofted over instead: exactly as far as it was thrown, simply in
836 // the air for the first part of the way. A tile that carries past the
837 // square and out into the open stays there — the middle is not a box, and
838 // where a discard came to rest is where somebody threw it.
839 //
840 // Asked from where the tile actually *is*, not from the seat: a player who
841 // carried it out over the square has a clear line even though the seat they
842 // came from does not.
843 const set = this.inPool(thrown.x, thrown.y);
844 const walled = !set && LOB_WHEN_WALLED && !this.canThrowFrom(thrown.x, thrown.y);
845 const { vx, vy } = thrown;
846 let vz = 0;
847 const speed = Math.hypot(vx, vy);
848 let flipTurns = 0;
849 let flipOver = 0;
850 let how = set ? 'slide, from inside the square' : 'slide';
851
852 if (walled) {
853 how = 'lob — over the wall, same line';
854 vz = liftFor(PLACE_FLIGHT);
855 // Long enough in the air to turn over properly, and harder means more.
856 flipOver = PLACE_FLIGHT;
857 flipTurns = speed > 1300 ? 2 : 1;
858 } else if (!set) {
859 // A skated tile leaves the fingers off the cloth, and turns over on its
860 // way down — harder means longer in the air and more turns in it.
861 const hop = THROW_LIFT + Math.min(0.22, (speed / MAX_THROW_SPEED) * 0.28);
862 vz = liftFor(hop);
863 flipOver = hop;
864 flipTurns = speed > 2200 ? 2 : speed > 600 ? 1 : 0;
865 }
866 if (!TUMBLE) flipTurns = 0;
867
868 this.throws.push({ x: thrown.x, y: thrown.y, fx: thrown.vx, fy: thrown.vy, vx, vy, how });
869 if (this.throws.length > 6) this.throws.shift();
870
871 return addBody(this.world!, {
872 tile: tile,
873 seat: thrown.seat,
874 x: thrown.x,
875 y: thrown.y,
876 vx,
877 vy,
878 z: 0,
879 vz,
880 angle: thrown.angle,
881 spin: thrown.spin,
882 flipTurns,
883 flipOver,
884 // It tumbles across its line of travel, the way a thrown tile does.
885 flipAxis: Math.atan2(vy, vx),
886 w: geo.tile.w,
887 h: geo.tile.h,
888 // It was drawn at hand size a moment ago; it shrinks on the way down.
889 scale: thrown.w / geo.tile.w,
890 });
891 }
892
893 /** A tile arriving now: thrown if somebody threw it, placed over the wall if
894 * it was tapped, and flat and quick if a bot's wall happens to be open. */
895 private launch(
896 geo: TableGeometry,
897 state: GameState,
898 a: { seat: SeatId; index: number; tile: Tile },
899 ): Body {
900 const rng = this.seeded(state, a);
901 const thrown = this.release?.seat === a.seat ? this.release : null;
902
903 if (thrown) return this.fling(geo, a.tile, thrown);
904
905 // Off the end of the hand, not the middle of it — a tile is thrown from the
906 // hand holding it, which is the one at the right-hand end of the row.
907 const from = geo.throwFrom[a.seat] ?? geo.launch[a.seat] ?? centreOf(geo.pool);
908 const open = !LOB_WHEN_WALLED || this.canThrow(a.seat);
909 const target = this.aimFor(geo, a.seat, rng);
910 const flight = open ? 0.34 + rng() * 0.1 : PLACE_FLIGHT;
911 // A slide is aimed at where it comes to *rest*, since it keeps going after
912 // it lands and SLIDE_TIME is roughly how much further. A lob is aimed at
913 // where it touches *down*, because it has to come down on the inside of the
914 // wall — solving for the resting place lands it short, against the outside.
915 const reach = open ? flight + SLIDE_TIME : flight;
916
917 const vx = (target.x - from.x) / reach;
918 const vy = (target.y - from.y) / reach;
919 return addBody(this.world!, {
920 tile: a.tile,
921 seat: a.seat,
922 x: from.x,
923 y: from.y,
924 vx,
925 vy,
926 z: 0,
927 vz: liftFor(flight),
928 angle: (rng() - 0.5) * Math.PI,
929 spin: (rng() - 0.5) * (open ? 7 : 2.5),
930 // It turns over on its way in, whichever way it is going.
931 flipTurns: TUMBLE ? 1 : 0,
932 flipOver: flight,
933 flipAxis: Math.atan2(vy, vx),
934 w: geo.tile.w,
935 h: geo.tile.h,
936 });
937 }
938
939 /** Where a tile from this seat is headed, with a little scatter. */
940 private aimFor(geo: TableGeometry, seat: SeatId, rng: () => number): Point {
941 const base = aimAt(geo, seat) ?? centreOf(geo.pool);
942 const jitter = Math.min(geo.pool.w, geo.pool.h) * 0.22;
943 return { x: base.x + (rng() - 0.5) * jitter, y: base.y + (rng() - 0.5) * jitter };
944 }
945
946 /**
947 * A tile's own random stream. Keyed on the hand and its place in that seat's
948 * discards, so the same tile scatters the same way every time it is rebuilt —
949 * a refresh mid-hand puts the pile back exactly as it was.
950 */
951 private seeded(state: GameState, a: { seat: SeatId; index: number; tile: Tile }) {
952 return makeRng(state.handNumber * 7919 + a.seat * 977 + a.index * 31 + a.tile + 1);
953 }
954}