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