anvilsign in

collin/mahjong

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