anvilsign in

collin/mahjong

1import type { SeatId } from '../game/types';
2import type { Barrier, Rect } from './physics';
3
4/**
5 * Where everything on the table actually is, in pixels.
6 *
7 * The wall's size lives entirely in CSS — `--ws` and `--wd` in styles.css work
8 * it out from the tile, and how much of it there is to lay out is decided in
9 * `game/wall.ts` — so rather than restate any of that here and let them drift
10 * apart, this *measures* what came out.
11 * `WallRing` renders every stack as a real element tagged with its index, so the
12 * colliders come from `getBoundingClientRect()` on the things already on screen.
13 * That is the whole mapping from the HTML to the physics.
14 *
15 * Measuring is one layout flush over ~74 elements. It happens when the window
16 * resizes and when the wall's shape changes, never per frame.
17 */
18
19const SEATS: SeatId[] = [0, 1, 2, 3];
20
21export interface TableGeometry {
22 /** Table size, world units — the world's origin is the table's top left. */
23 size: { w: number; h: number };
24 /** Inside the wall square: where a discard is aimed, and where a rebuilt pile
25 * is laid out. Not a fence — see `felt`. */
26 pool: Rect;
27 /**
28 * The table itself, and nothing nearer. Not a fence anybody meets in play: it
29 * is the backstop that keeps a tile from being lost off the screen entirely,
30 * and it sits at the edge of the glass where nothing can reach it.
31 *
32 * What actually stops a tile is `barriers` — the tiles. The middle is not a
33 * box, it is a square of eighteen stacks a side with people's hands beyond,
34 * and as the wall is eaten away the pool spills out through the gaps exactly
35 * as it does on a real table, until it fetches up against somebody's tiles.
36 */
37 felt: Rect;
38 /**
39 * Stacks of two still standing. Half stacks are low enough to throw over.
40 * The throw gate's business — what the physics collides with is `barriers`,
41 * which includes these.
42 */
43 walls: Barrier[];
44 /**
45 * Everything solid, which is to say every tile on the table: the standing
46 * stacks, the sets people have laid down, and the sixteen each of them is
47 * holding. Measured off the elements themselves, like the wall — a tile you
48 * can see is a tile a thrown one hits.
49 */
50 barriers: Barrier[];
51 /** A tile in the pool is the same tile that was in the wall. */
52 tile: { w: number; h: number };
53 /** The middle of each seat's hand, if that seat's hand is on screen. */
54 launch: Partial<Record<SeatId, Point>>;
55 /** The right-hand end of each seat's hand, which is where a tile is thrown
56 * from: the tile just drawn sits there, and that is the hand you throw with. */
57 throwFrom: Partial<Record<SeatId, Point>>;
58}
59
60export interface Point {
61 x: number;
62 y: number;
63}
64
65/**
66 * Read the table. Returns null when there is no wall square to measure — the
67 * compact layout has none, and neither does a table that has not laid out yet.
68 */
69export function measure(table: HTMLElement): TableGeometry | null {
70 const ring = table.querySelector<HTMLElement>('.wall-ring');
71 if (!ring) return null;
72
73 const base = table.getBoundingClientRect();
74 if (base.width === 0 || base.height === 0) return null;
75 const local = (r: DOMRect): Rect => ({
76 x: r.left - base.left,
77 y: r.top - base.top,
78 w: r.width,
79 h: r.height,
80 });
81
82 const walls: Barrier[] = [];
83 const barriers: Barrier[] = [];
84 // A stack element is --ws by --wd (or the other way round on the left and
85 // right sides), so its narrower side is the tile's width whichever wall it is
86 // in — the fallback for sizing a pool tile before any hand has been dealt.
87 // The probe is one cell that is always there, spent wall or not.
88 const probe = ring.querySelector<HTMLElement>('.wall-probe')?.getBoundingClientRect();
89 let short = probe ? Math.min(probe.width, probe.height) : 0;
90 // Nothing in the square is turned, so a stack's bounding rect *is* the stack:
91 // the box the layout gave it, in the table's own axes. A stack on the left or
92 // right wall is lying the other way about, and its rect says so.
93 //
94 // Whether it is a barrier is read off the element too, rather than worked out
95 // again from the state: a stack of two stands as tall as the tile thrown at
96 // it (`isBarrier`), and `s2` is `WallRing` saying it drew one. The rule that a
97 // tile you can see is a tile a thrown one hits, kept by asking the thing on
98 // screen instead of a second opinion that could differ from it.
99 for (const el of ring.querySelectorAll<HTMLElement>('[data-stack]')) {
100 const r = local(el.getBoundingClientRect());
101 short = Math.max(short, Math.min(r.w, r.h));
102 if (el.classList.contains('s2')) {
103 walls.push({ rect: r });
104 barriers.push({ rect: r });
105 }
106 }
107 if (short === 0) return null;
108
109 // `.wall-ring` is the opening itself — the walls hang off its edges — so the
110 // pool is simply its box. (It used to be the wall's outside, which is why this
111 // had to subtract the wall's own thickness.) This is only ever where a
112 // *tapped* discard is aimed; a flick is not aimed at anything — it goes where
113 // it was thrown.
114 const pool: Rect = local(ring.getBoundingClientRect());
115
116 const launch: Partial<Record<SeatId, Point>> = {};
117 const throwFrom: Partial<Record<SeatId, Point>> = {};
118 for (const seat of SEATS) {
119 const hand = table.querySelector<HTMLElement>(`[data-seat="${seat}"] .hand`);
120 if (!hand) continue;
121 const r = hand.getBoundingClientRect();
122 if (r.width === 0 && r.height === 0) continue;
123 // A rotated element's bounding box is still centred on the element, so this
124 // is the right point whichever edge the seat is sitting at.
125 launch[seat] = { x: r.left + r.width / 2 - base.left, y: r.top + r.height / 2 - base.top };
126
127 // The end of the row rather than the middle of it. That is where the tile
128 // just drawn is sitting and which hand it is in, so it is where a throw
129 // comes from — measured off the last cell, so it is the right end of the
130 // *row* whichever way round the seat is turned.
131 const end = hand.querySelector<HTMLElement>('.hand-cell:last-child');
132 const er = end?.getBoundingClientRect();
133 throwFrom[seat] = er
134 ? { x: er.left + er.width / 2 - base.left, y: er.top + er.height / 2 - base.top }
135 : launch[seat];
136
137 // Every tile this seat has on the table, one collider each. A row of them
138 // is adjacent, so a hand comes out as a solid wall without being described
139 // as one anywhere — the same trick the wall square is measured with.
140 const slot = table.querySelector<HTMLElement>(`[data-seat="${seat}"]`);
141 for (const el of slot?.querySelectorAll<HTMLElement>('.hand .tile, .melds .tile') ?? []) {
142 const t = local(el.getBoundingClientRect());
143 if (t.w > 0 && t.h > 0) barriers.push({ rect: t, seat });
144 }
145 }
146
147 // The glass, not the green. Nothing meets this in play — it is only there so
148 // a tile that got past everybody's tiles is still on the table afterwards.
149 const felt: Rect = { x: 0, y: 0, w: base.width, h: base.height };
150
151 return {
152 size: { w: base.width, h: base.height },
153 pool,
154 felt,
155 walls,
156 barriers,
157 tile: poolTile(table, short),
158 launch,
159 throwFrom,
160 };
161}
162
163/**
164 * How big a tile in the middle is drawn: the same size as the tiles being
165 * played with.
166 *
167 * It used to be the size of a tile in the wall, which is much smaller, and that
168 * was a mistake you could see rather than measure — a tile thrown from a hand
169 * shrank as it crossed the table, so it read as being dropped away from you into
170 * the distance rather than skidded across a flat one. They are the same tiles,
171 * so they are the same size.
172 *
173 * A seat's strip is rotated by a right angle, which swaps its bounding box, and
174 * a tile is always taller than it is wide — so the narrower side is the width
175 * whichever edge is measured. Falls back to the wall's own tile if no hand has
176 * been dealt yet.
177 */
178function poolTile(table: HTMLElement, fallback: number): { w: number; h: number } {
179 const el = table.querySelector<HTMLElement>('.hand .tile');
180 const r = el?.getBoundingClientRect();
181 const w = r && r.width > 0 ? Math.min(r.width, r.height) : fallback;
182 return { w, h: w * 1.375 };
183}
184
185export const centreOf = (r: Rect): Point => ({ x: r.x + r.w / 2, y: r.y + r.h / 2 });
186
187/**
188 * Whether a seat has a clear line into the middle — the throw gate.
189 *
190 * Not a rule bolted on beside the physics; it *is* the physics, asked ahead of
191 * time. While a standing stack of two is between a seat and the pool, a tile
192 * flicked from there would hit it, so the seat cannot throw and has to place the
193 * tile over the wall instead (tap-tap, or 打出). As the hand eats the square,
194 * gaps open and seats come good one at a time.
195 *
196 * Aim is not just dead ahead: a fan of lines spread across the pool means a gap
197 * off to one side counts, which is how you would actually throw it.
198 */
199export function canThrow(geo: TableGeometry, seat: SeatId): boolean {
200 const from = throwsFrom(geo, seat);
201 return !!from && canThrowFrom(geo, from);
202}
203
204/**
205 * Where a tile this seat plays actually starts from — the end of the row, not
206 * the middle of it. The same point `pool.ts` launches from, and it has to be:
207 * asking whether the line is clear from somewhere the tile is not is how a tile
208 * gets waved through and then stopped dead by a stack it was never clear of.
209 */
210const throwsFrom = (geo: TableGeometry, seat: SeatId): Point | undefined =>
211 geo.throwFrom[seat] ?? geo.launch[seat];
212
213/**
214 * The same question asked from a particular point rather than from a seat.
215 *
216 * This is the one that matters for a tile somebody is holding: they have picked
217 * it up and can carry it anywhere, so what decides whether it can be slid in is
218 * the line from wherever they let go of it — not the line from the hand it came
219 * out of. Judging a throw released out over the square by the view from the
220 * player's own edge called almost everything a lob.
221 */
222export function canThrowFrom(geo: TableGeometry, from: Point): boolean {
223 if (inRect(geo.pool, from)) return true;
224 return aimPoints(geo).some((to) => clearLine(geo.walls, from, to));
225}
226
227export const inRect = (r: Rect, p: Point) =>
228 p.x >= r.x && p.x <= r.x + r.w && p.y >= r.y && p.y <= r.y + r.h;
229
230/** Somewhere in the pool this seat could actually get a tile to, or null. */
231export function aimAt(geo: TableGeometry, seat: SeatId): Point | null {
232 const from = throwsFrom(geo, seat);
233 if (!from) return null;
234 const open = aimPoints(geo).filter((to) => clearLine(geo.walls, from, to));
235 if (open.length === 0) return null;
236 // The most central thing reachable, so a tile lands among the others rather
237 // than hugging whichever edge it squeezed past.
238 const c = centreOf(geo.pool);
239 return open.reduce((best, p) =>
240 Math.hypot(p.x - c.x, p.y - c.y) < Math.hypot(best.x - c.x, best.y - c.y) ? p : best,
241 );
242}
243
244/**
245 * Landing spots to try for: a grid over the whole pool, not a line through its
246 * middle.
247 *
248 * A throw only has to *get inside* the square — once past the wall the tile
249 * slides to a stop wherever it ends up. So the near corners matter as much as
250 * the centre, and they matter more: they sit much closer to the seat, which is
251 * what makes a gap well off to one side worth aiming through at all. Aiming
252 * only at the middle would call a seat walled in when it plainly is not.
253 */
254function aimPoints(geo: TableGeometry): Point[] {
255 const { x, y, w, h } = geo.pool;
256 // Fine rather than coarse, and it costs nothing: this runs once when a tile
257 // is let go of, not per frame. A sparse grid missed narrow gaps and called a
258 // throw impossible when a tile would plainly have gone through, and sliding is
259 // what a discard should be whenever it can be.
260 const steps = [0.06, 0.2, 0.35, 0.5, 0.65, 0.8, 0.94];
261 const out: Point[] = [];
262 for (const u of steps) for (const v of steps) out.push({ x: x + w * u, y: y + h * v });
263 return out;
264}
265
266/** Segment against every standing stack, by the slab method. */
267function clearLine(walls: Barrier[], from: Point, to: Point): boolean {
268 return !walls.some((w) => segmentHitsRect(from, to, w.rect));
269}
270
271export function segmentHitsRect(a: Point, b: Point, r: Rect): boolean {
272 const dx = b.x - a.x;
273 const dy = b.y - a.y;
274 let t0 = 0;
275 let t1 = 1;
276
277 // Each axis clips the span of the segment that could still be inside.
278 const slab = (p: number, d: number, lo: number, hi: number): boolean => {
279 if (Math.abs(d) < 1e-9) return p >= lo && p <= hi;
280 const near = (lo - p) / d;
281 const far = (hi - p) / d;
282 t0 = Math.max(t0, Math.min(near, far));
283 t1 = Math.min(t1, Math.max(near, far));
284 return t1 >= t0;
285 };
286
287 if (!slab(a.x, dx, r.x, r.x + r.w)) return false;
288 if (!slab(a.y, dy, r.y, r.y + r.h)) return false;
289 return t1 >= t0;
290}