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