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: Barrier[];
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: Barrier[] = [];
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 // The whole square is set at an angle — see `--wall-turn` in styles.css — so
93 // a stack's box is not what `getBoundingClientRect` reports, which is only the
94 // upright box *around* the turned one. What is true either way is the centre
95 // it reports and the size the layout gave it, and those two plus the angle are
96 // the stack itself.
97 for (const el of ring.querySelectorAll<HTMLElement>('[data-stack]')) {
98 const i = Number(el.dataset.stack);
99 // Which way this stack is lying, told rather than deduced: the layout knows
100 // it exactly, and a turned box's bounding rect cannot say.
101 const turn = ((Number(el.dataset.angle) || 0) * Math.PI) / 180;
102 const around = local(el.getBoundingClientRect());
103 const r: Rect = {
104 x: around.x + around.w / 2 - el.offsetWidth / 2,
105 y: around.y + around.h / 2 - el.offsetHeight / 2,
106 w: el.offsetWidth,
107 h: el.offsetHeight,
108 };
109 short = Math.max(short, Math.min(r.w, r.h));
110 const stack = stacks[i];
111 if (stack && isBarrier(stack)) {
112 walls.push({ rect: r, angle: turn });
113 barriers.push({ rect: r, angle: turn });
114 }
115 }
116 if (short === 0) return null;
117
118 // `.wall-ring` is the opening itself — the walls hang off its edges — so the
119 // pool is simply its box. (It used to be the wall's outside, which is why this
120 // had to subtract the wall's own thickness.)
121 //
122 // Taken at the size the layout gave it rather than the size it covers once
123 // turned: the opening is the same opening whichever way round the square is
124 // standing, and this is only ever where a *tapped* discard is aimed. A flick
125 // is not aimed at anything — it goes where it was thrown.
126 const around = local(ring.getBoundingClientRect());
127 const openW = Math.max(short, ring.offsetWidth);
128 const openH = Math.max(short, ring.offsetHeight);
129 const ringRect: Rect = {
130 x: around.x + around.w / 2 - openW / 2,
131 y: around.y + around.h / 2 - openH / 2,
132 w: openW,
133 h: openH,
134 };
135 const pool: Rect = ringRect;
136
137 const launch: Partial<Record<SeatId, Point>> = {};
138 const throwFrom: Partial<Record<SeatId, Point>> = {};
139 for (const seat of SEATS) {
140 const hand = table.querySelector<HTMLElement>(`[data-seat="${seat}"] .hand`);
141 if (!hand) continue;
142 const r = hand.getBoundingClientRect();
143 if (r.width === 0 && r.height === 0) continue;
144 // A rotated element's bounding box is still centred on the element, so this
145 // is the right point whichever edge the seat is sitting at.
146 launch[seat] = { x: r.left + r.width / 2 - base.left, y: r.top + r.height / 2 - base.top };
147
148 // The end of the row rather than the middle of it. That is where the tile
149 // just drawn is sitting and which hand it is in, so it is where a throw
150 // comes from — measured off the last cell, so it is the right end of the
151 // *row* whichever way round the seat is turned.
152 const end = hand.querySelector<HTMLElement>('.hand-cell:last-child');
153 const er = end?.getBoundingClientRect();
154 throwFrom[seat] = er
155 ? { x: er.left + er.width / 2 - base.left, y: er.top + er.height / 2 - base.top }
156 : launch[seat];
157
158 // Every tile this seat has on the table, one collider each. A row of them
159 // is adjacent, so a hand comes out as a solid wall without being described
160 // as one anywhere — the same trick the wall square is measured with.
161 const slot = table.querySelector<HTMLElement>(`[data-seat="${seat}"]`);
162 for (const el of slot?.querySelectorAll<HTMLElement>('.hand .tile, .melds .tile') ?? []) {
163 const t = local(el.getBoundingClientRect());
164 if (t.w > 0 && t.h > 0) barriers.push({ rect: t, seat });
165 }
166 }
167
168 // The glass, not the green. Nothing meets this in play — it is only there so
169 // a tile that got past everybody's tiles is still on the table afterwards.
170 const felt: Rect = { x: 0, y: 0, w: base.width, h: base.height };
171
172 return {
173 size: { w: base.width, h: base.height },
174 pool,
175 felt,
176 walls,
177 barriers,
178 tile: poolTile(table, short),
179 launch,
180 throwFrom,
181 };
182}
183
184/**
185 * How big a tile in the middle is drawn: the same size as the tiles being
186 * played with.
187 *
188 * It used to be the size of a tile in the wall, which is much smaller, and that
189 * was a mistake you could see rather than measure — a tile thrown from a hand
190 * shrank as it crossed the table, so it read as being dropped away from you into
191 * the distance rather than skidded across a flat one. They are the same tiles,
192 * so they are the same size.
193 *
194 * A seat's strip is rotated by a right angle, which swaps its bounding box, and
195 * a tile is always taller than it is wide — so the narrower side is the width
196 * whichever edge is measured. Falls back to the wall's own tile if no hand has
197 * been dealt yet.
198 */
199function poolTile(table: HTMLElement, fallback: number): { w: number; h: number } {
200 const el = table.querySelector<HTMLElement>('.hand .tile');
201 const r = el?.getBoundingClientRect();
202 const w = r && r.width > 0 ? Math.min(r.width, r.height) : fallback;
203 return { w, h: w * 1.375 };
204}
205
206export const centreOf = (r: Rect): Point => ({ x: r.x + r.w / 2, y: r.y + r.h / 2 });
207
208/**
209 * Whether a seat has a clear line into the middle — the throw gate.
210 *
211 * Not a rule bolted on beside the physics; it *is* the physics, asked ahead of
212 * time. While a standing stack of two is between a seat and the pool, a tile
213 * flicked from there would hit it, so the seat cannot throw and has to place the
214 * tile over the wall instead (tap-tap, or 打出). As the hand eats the square,
215 * gaps open and seats come good one at a time.
216 *
217 * Aim is not just dead ahead: a fan of lines spread across the pool means a gap
218 * off to one side counts, which is how you would actually throw it.
219 */
220export function canThrow(geo: TableGeometry, seat: SeatId): boolean {
221 const from = throwsFrom(geo, seat);
222 return !!from && canThrowFrom(geo, from);
223}
224
225/**
226 * Where a tile this seat plays actually starts from — the end of the row, not
227 * the middle of it. The same point `pool.ts` launches from, and it has to be:
228 * asking whether the line is clear from somewhere the tile is not is how a tile
229 * gets waved through and then stopped dead by a stack it was never clear of.
230 */
231const throwsFrom = (geo: TableGeometry, seat: SeatId): Point | undefined =>
232 geo.throwFrom[seat] ?? geo.launch[seat];
233
234/**
235 * The same question asked from a particular point rather than from a seat.
236 *
237 * This is the one that matters for a tile somebody is holding: they have picked
238 * it up and can carry it anywhere, so what decides whether it can be slid in is
239 * the line from wherever they let go of it — not the line from the hand it came
240 * out of. Judging a throw released out over the square by the view from the
241 * player's own edge called almost everything a lob.
242 */
243export function canThrowFrom(geo: TableGeometry, from: Point): boolean {
244 if (inRect(geo.pool, from)) return true;
245 return aimPoints(geo).some((to) => clearLine(geo.walls, from, to));
246}
247
248export const inRect = (r: Rect, p: Point) =>
249 p.x >= r.x && p.x <= r.x + r.w && p.y >= r.y && p.y <= r.y + r.h;
250
251/** Somewhere in the pool this seat could actually get a tile to, or null. */
252export function aimAt(geo: TableGeometry, seat: SeatId): Point | null {
253 const from = throwsFrom(geo, seat);
254 if (!from) return null;
255 const open = aimPoints(geo).filter((to) => clearLine(geo.walls, from, to));
256 if (open.length === 0) return null;
257 // The most central thing reachable, so a tile lands among the others rather
258 // than hugging whichever edge it squeezed past.
259 const c = centreOf(geo.pool);
260 return open.reduce((best, p) =>
261 Math.hypot(p.x - c.x, p.y - c.y) < Math.hypot(best.x - c.x, best.y - c.y) ? p : best,
262 );
263}
264
265/**
266 * Landing spots to try for: a grid over the whole pool, not a line through its
267 * middle.
268 *
269 * A throw only has to *get inside* the square — once past the wall the tile
270 * slides to a stop wherever it ends up. So the near corners matter as much as
271 * the centre, and they matter more: they sit much closer to the seat, which is
272 * what makes a gap well off to one side worth aiming through at all. Aiming
273 * only at the middle would call a seat walled in when it plainly is not.
274 */
275function aimPoints(geo: TableGeometry): Point[] {
276 const { x, y, w, h } = geo.pool;
277 // Fine rather than coarse, and it costs nothing: this runs once when a tile
278 // is let go of, not per frame. A sparse grid missed narrow gaps and called a
279 // throw impossible when a tile would plainly have gone through, and sliding is
280 // what a discard should be whenever it can be.
281 const steps = [0.06, 0.2, 0.35, 0.5, 0.65, 0.8, 0.94];
282 const out: Point[] = [];
283 for (const u of steps) for (const v of steps) out.push({ x: x + w * u, y: y + h * v });
284 return out;
285}
286
287/** Segment against every standing stack, by the slab method. */
288function clearLine(walls: Barrier[], from: Point, to: Point): boolean {
289 return !walls.some((w) => segmentHitsRect(from, to, w.rect, w.angle));
290}
291
292export function segmentHitsRect(a: Point, b: Point, r: Rect, angle = 0): boolean {
293 // A turned box is the same box asked from where it is standing: put the
294 // segment into its frame and the slabs are axis-aligned again.
295 if (angle) {
296 const cx = r.x + r.w / 2;
297 const cy = r.y + r.h / 2;
298 const c = Math.cos(-angle);
299 const s = Math.sin(-angle);
300 const into = (p: Point): Point => ({
301 x: cx + (p.x - cx) * c - (p.y - cy) * s,
302 y: cy + (p.x - cx) * s + (p.y - cy) * c,
303 });
304 return segmentHitsRect(into(a), into(b), r);
305 }
306 const dx = b.x - a.x;
307 const dy = b.y - a.y;
308 let t0 = 0;
309 let t1 = 1;
310
311 // Each axis clips the span of the segment that could still be inside.
312 const slab = (p: number, d: number, lo: number, hi: number): boolean => {
313 if (Math.abs(d) < 1e-9) return p >= lo && p <= hi;
314 const near = (lo - p) / d;
315 const far = (hi - p) / d;
316 t0 = Math.max(t0, Math.min(near, far));
317 t1 = Math.min(t1, Math.max(near, far));
318 return t1 >= t0;
319 };
320
321 if (!slab(a.x, dx, r.x, r.x + r.w)) return false;
322 if (!slab(a.y, dy, r.y, r.y + r.h)) return false;
323 return t1 >= t0;
324}