anvilsign in

collin/mahjong

1import type { Tile } from '../game/tiles';
2import type { SeatId } from '../game/types';
3
4/**
5 * The tiles in the middle of the table, as things with weight.
6 *
7 * Pure and deterministic: no DOM, no clock, no randomness. Where the world's
8 * measurements come from is `geometry.ts`; what gets thrown into it and when is
9 * `pool.ts`; drawing it is `ui/Pool.tsx`. Anything random — the scatter on a
10 * placed tile, where a rebuilt pile's tiles sit — is decided by the caller and
11 * arrives as a spawn impulse, which is what lets the same hand come back to the
12 * same pile after a refresh.
13 *
14 * Tiles are rectangles and they are solved as rectangles: two of them can lean
15 * against each other at any angle but never share the same ground. Everything is
16 * in CSS pixels, table-local, and seconds.
17 */
18
19/** One fixed step. Small enough that a hard flick can't tunnel a wall. */
20export const FIXED_DT = 1 / 120;
21/**
22 * Most catch-up a single frame will simulate. A tab that was in the background
23 * for a minute comes back to a settled pile, not to a spin through 7200 steps.
24 */
25const MAX_SUBSTEPS = 8;
26
27/** Falls onto the felt in about half a second from a normal throw. */
28const GRAVITY = 2600;
29/** Tiles are dense and land flat; they do not bounce much. */
30const Z_RESTITUTION = 0.34;
31/** Below this the tile is flat on the felt: sliding, and in the way of others. */
32const ON_FELT = 8;
33/**
34 * How high a standing stack of two reaches. A tile still above this sails over
35 * the wall — which is exactly what a *placed* tile does, and what a thrown one
36 * must not need to do.
37 */
38export const WALL_HEIGHT = 30;
39
40/**
41 * Felt friction: an exponential part that kills speed, and a constant part that
42 * actually brings it to a stop rather than to an asymptote.
43 *
44 * Deliberately light. A tile thrown hard should cross the square, come off the
45 * far side and barge through what is already lying there before it settles —
46 * heavier friction ate the throw in the first few inches and every discard
47 * ended up looking the same however it was let go of.
48 */
49const FELT_DAMP = 2.6;
50const FELT_STOP = 70;
51const SPIN_DAMP = 3.4;
52const SPIN_STOP = 0.9;
53
54/**
55 * Roughly how much longer a tile keeps travelling after it lands, as a time.
56 * Aiming a throw means solving for where it comes to *rest*, not where it first
57 * touches down, so `pool.ts` adds this to the flight time.
58 */
59export const SLIDE_TIME = 1 / FELT_DAMP;
60
61/** Off the inside of the wall square, and off another tile. Bouncy enough that
62 * a hard throw ricochets instead of sticking where it first lands. */
63const BOUND_RESTITUTION = 0.55;
64const BOUND_FRICTION = 0.9;
65const TILE_RESTITUTION = 0.42;
66/** How much of a glancing blow becomes spin. Tiles are light and skate. */
67const SPIN_TRANSFER = 0.06;
68
69/** Asleep after this many consecutive steps of going nowhere. */
70const SLEEP_SPEED = 7;
71const SLEEP_SPIN = 0.2;
72const SLEEP_STEPS = 10;
73/**
74 * Overlap small enough to live with. Without this a crowded pool never sleeps:
75 * a tile squeezed between its neighbours and the pool's edge gets pushed out of
76 * contact and shoved back into it on every step, for ever. A fifth of a pixel is
77 * not something you can see, and it is what lets the pile go quiet.
78 */
79const CONTACT_SLOP = 0.2;
80/**
81 * A body moving this slowly for this long is put to sleep whatever it thinks it
82 * is doing. The backstop that guarantees the pile always settles — counted from
83 * when it last woke, not from when it was thrown.
84 */
85const AWAKE_LIMIT = 600;
86
87/** Pulls a tile that landed short of the pool in towards the rest of them. */
88const ENTRY_PULL = 700;
89/**
90 * How long a tile gets to find its own way into the pool before it is simply
91 * put there. A discard is game state made visible — it has to be in the middle
92 * where it can be seen and counted — so a tile that has got itself wedged
93 * against a standing stack, or is bouncing between two of them, cannot be left
94 * out there. Two seconds is far longer than any real throw takes to settle.
95 */
96const ENTRY_GRACE = 240;
97
98/** How fast a tile drawn at hand size shrinks to the size it is in the pool. */
99const SCALE_EASE = 6;
100
101export interface Rect {
102 x: number;
103 y: number;
104 w: number;
105 h: number;
106}
107
108/** Anything the collision routines can treat as a rotated rectangle. */
109interface Box {
110 x: number;
111 y: number;
112 w: number;
113 h: number;
114 angle: number;
115}
116
117export interface Body {
118 tile: Tile;
119 /** Who threw it — for the fly-out when it is claimed, not for any marking. */
120 seat: SeatId;
121 /** Centre on the felt plane. */
122 x: number;
123 y: number;
124 vx: number;
125 vy: number;
126 /** Height above the felt, and its rate. Only ever >= 0. */
127 z: number;
128 vz: number;
129 angle: number;
130 spin: number;
131 w: number;
132 h: number;
133 /**
134 * Render-only: what to multiply the drawn size by, easing to 1. A tile is
135 * drawn big in a hand so it can be read, and small in the pool because that is
136 * the size it is in the wall, so a thrown one has to settle from one to the
137 * other. Eased here rather than in the renderer so it does not run at a
138 * different speed on a different frame rate.
139 */
140 scale: number;
141 /**
142 * Whether it has ever been inside the pool. Until it has, it is free to fly
143 * over the wall from a seat's edge; once it has, the pool keeps it.
144 */
145 entered: boolean;
146 resting: boolean;
147 /** Consecutive slow steps, counting towards sleep. */
148 still: number;
149 /** Steps lived, for the grace period on getting into the pool. */
150 age: number;
151 /** Steps since it last woke, for the backstop on settling. */
152 awake: number;
153}
154
155/** A collision loud enough to hear. `strength` is 0..1. */
156export interface Impact {
157 x: number;
158 y: number;
159 strength: number;
160}
161
162export interface World {
163 /** Where tiles come to rest — inside the wall square. */
164 bounds: Rect;
165 /** Stacks of two still standing. Half and spent stacks are not obstacles. */
166 walls: Rect[];
167 bodies: Body[];
168 /** Left-over time from the last frame, so steps stay a fixed size. */
169 carry: number;
170}
171
172export interface Spawn {
173 tile: Tile;
174 seat: SeatId;
175 x: number;
176 y: number;
177 vx: number;
178 vy: number;
179 z: number;
180 vz: number;
181 angle: number;
182 spin: number;
183 w: number;
184 h: number;
185 /** Drawn this much bigger to start with, easing to its pool size. */
186 scale?: number;
187 /** Already settled — a pile being rebuilt after a reload or an undo. */
188 atRest?: boolean;
189}
190
191export function createWorld(bounds: Rect, walls: Rect[] = []): World {
192 return { bounds, walls, bodies: [], carry: 0 };
193}
194
195export function addBody(world: World, s: Spawn): Body {
196 const body: Body = {
197 tile: s.tile,
198 seat: s.seat,
199 x: s.x,
200 y: s.y,
201 vx: s.atRest ? 0 : s.vx,
202 vy: s.atRest ? 0 : s.vy,
203 z: s.atRest ? 0 : s.z,
204 vz: s.atRest ? 0 : s.vz,
205 angle: s.angle,
206 spin: s.atRest ? 0 : s.spin,
207 w: s.w,
208 h: s.h,
209 scale: s.atRest ? 1 : s.scale ?? 1,
210 entered: !!s.atRest,
211 resting: !!s.atRest,
212 still: s.atRest ? SLEEP_STEPS : 0,
213 age: 0,
214 awake: 0,
215 };
216 world.bodies.push(body);
217 // A tile dropped straight into a settled pile still has to make room.
218 if (s.atRest) separate(world, body);
219 return body;
220}
221
222// ---- rotated rectangles ---------------------------------------------------
223
224/** Distance from a box's centre to its edge, measured along `ax`. */
225function reach(b: Box, ax: { x: number; y: number }): number {
226 const c = Math.cos(b.angle);
227 const s = Math.sin(b.angle);
228 return (
229 Math.abs(c * ax.x + s * ax.y) * (b.w / 2) + Math.abs(-s * ax.x + c * ax.y) * (b.h / 2)
230 );
231}
232
233/** The rotated rectangle's own bounding box, for the pool's straight edges. */
234function aabbHalf(b: Box) {
235 const c = Math.abs(Math.cos(b.angle));
236 const s = Math.abs(Math.sin(b.angle));
237 return { x: (b.w / 2) * c + (b.h / 2) * s, y: (b.w / 2) * s + (b.h / 2) * c };
238}
239
240/** Enough to skip a pair without doing the real work. */
241const circumradius = (b: Box) => Math.hypot(b.w, b.h) / 2;
242
243/**
244 * Separating axis test between two rectangles at any angle. Returns the
245 * shallowest way out — the direction to push `b` away from `a`, and by how much
246 * — or null if they are clear of each other.
247 *
248 * Four axes is all a pair of rectangles needs: each box's two edge normals.
249 */
250function overlapOf(a: Box, b: Box): { nx: number; ny: number; depth: number } | null {
251 const ca = Math.cos(a.angle);
252 const sa = Math.sin(a.angle);
253 const cb = Math.cos(b.angle);
254 const sb = Math.sin(b.angle);
255 const axes = [
256 { x: ca, y: sa },
257 { x: -sa, y: ca },
258 { x: cb, y: sb },
259 { x: -sb, y: cb },
260 ];
261
262 const dx = b.x - a.x;
263 const dy = b.y - a.y;
264 let depth = Infinity;
265 let nx = 0;
266 let ny = 0;
267
268 for (const ax of axes) {
269 const gap = reach(a, ax) + reach(b, ax) - Math.abs(dx * ax.x + dy * ax.y);
270 if (gap <= 0) return null;
271 if (gap < depth) {
272 depth = gap;
273 // Always pointing from a towards b, so callers need not guess.
274 const sign = dx * ax.x + dy * ax.y < 0 ? -1 : 1;
275 nx = ax.x * sign;
276 ny = ax.y * sign;
277 }
278 }
279 return { nx, ny, depth };
280}
281
282/** A standing stack, as something the tests above can chew on. */
283const boxOf = (r: Rect): Box => ({
284 x: r.x + r.w / 2,
285 y: r.y + r.h / 2,
286 w: r.w,
287 h: r.h,
288 angle: 0,
289});
290
291// ---- stepping -------------------------------------------------------------
292
293const inside = (r: Rect, x: number, y: number) =>
294 x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
295
296/**
297 * Run the world forward. `elapsed` is real seconds since the last call; it is
298 * consumed in fixed steps so the result does not depend on the frame rate.
299 * Returns the impacts worth a sound.
300 */
301export function advance(world: World, elapsed: number): Impact[] {
302 world.carry += Math.max(0, elapsed);
303 let steps = Math.floor(world.carry / FIXED_DT);
304 if (steps > MAX_SUBSTEPS) {
305 // Drop the backlog rather than working through it.
306 world.carry = 0;
307 steps = MAX_SUBSTEPS;
308 } else {
309 world.carry -= steps * FIXED_DT;
310 }
311
312 const impacts: Impact[] = [];
313 for (let i = 0; i < steps; i++) step(world, impacts);
314 return impacts;
315}
316
317/** One fixed step. Exported for the tests, which drive it directly. */
318export function step(world: World, impacts: Impact[] = []): Impact[] {
319 const dt = FIXED_DT;
320
321 for (const b of world.bodies) {
322 if (b.scale !== 1) {
323 b.scale += (1 - b.scale) * Math.min(1, SCALE_EASE * dt);
324 if (Math.abs(b.scale - 1) < 0.002) b.scale = 1;
325 }
326 if (b.resting) continue;
327 b.age++;
328 b.awake++;
329
330 // --- through the air ---
331 if (b.z > 0 || b.vz !== 0) {
332 b.vz -= GRAVITY * dt;
333 b.z += b.vz * dt;
334 if (b.z <= 0) {
335 const landing = Math.abs(b.vz);
336 b.z = 0;
337 // Below a knock it stops dead rather than shivering out a bounce.
338 b.vz = landing > 40 ? landing * Z_RESTITUTION : 0;
339 const strength = Math.min(1, landing / 900);
340 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
341 }
342 }
343
344 b.x += b.vx * dt;
345 b.y += b.vy * dt;
346 b.angle += b.spin * dt;
347
348 if (inside(world.bounds, b.x, b.y)) b.entered = true;
349 else if (b.age > ENTRY_GRACE) {
350 // Out of time going the long way round. Put it in, gently.
351 b.entered = true;
352 b.z = 0;
353 b.vz = 0;
354 clampInto(world.bounds, b);
355 }
356
357 // --- on the felt ---
358 // Strictly z <= 0, not ON_FELT: friction is between the tile and the cloth,
359 // so a tile still in the air keeps the speed it was thrown with. ON_FELT is
360 // only about being low enough to be in another tile's way.
361 if (b.z <= 0) {
362 damp(b, dt);
363 // A tile that fell short skids in rather than sitting outside the pool.
364 if (!b.entered) pullIn(world, b, dt);
365 }
366
367 // A tile still above the wall is clear of it.
368 if (b.z < WALL_HEIGHT) {
369 for (const wall of world.walls) hitWall(b, wall, impacts);
370 }
371
372 // The pool's edge is the inside face of the wall, and it is only as tall as
373 // the wall — a tile lobbed high is over the top of it, not stopped by it.
374 if (b.entered && b.z < WALL_HEIGHT) keepInBounds(world, b, impacts);
375 }
376
377 collideTiles(world, impacts);
378 // Being shoved by a neighbour can put a tile back over the edge, and a tile
379 // that then fell asleep out there would stay out there. Only awake ones need
380 // it: resolvePair never moves a tile that has settled.
381 for (const b of world.bodies) {
382 if (b.entered && !b.resting && b.z < WALL_HEIGHT) clampInto(world.bounds, b);
383 }
384 // Deciding to sleep comes last, so it judges where the step actually left
385 // things — before, a contact resolved after the decision would undo it and a
386 // crowded pool would stay awake for ever.
387 for (const b of world.bodies) if (!b.resting) trySleep(b);
388 return impacts;
389}
390
391/**
392 * The table has been re-measured — the window resized, or the wall was eaten
393 * further back. The tiles keep where they are, but a pool that shrank must not
394 * leave any of them stranded outside it, and the ones it moves have to wake up
395 * so they can settle again.
396 */
397export function reshape(world: World, bounds: Rect, walls: Rect[]) {
398 world.bounds = bounds;
399 world.walls = walls;
400 for (const b of world.bodies) {
401 if (!b.entered) continue;
402 const x = b.x;
403 const y = b.y;
404 clampInto(bounds, b);
405 if (b.x !== x || b.y !== y) wake(b);
406 }
407}
408
409function damp(b: Body, dt: number) {
410 const k = Math.exp(-FELT_DAMP * dt);
411 b.vx *= k;
412 b.vy *= k;
413 b.spin *= Math.exp(-SPIN_DAMP * dt);
414
415 const speed = Math.hypot(b.vx, b.vy);
416 if (speed > 0) {
417 const next = Math.max(0, speed - FELT_STOP * dt);
418 b.vx = (b.vx / speed) * next;
419 b.vy = (b.vy / speed) * next;
420 }
421 const spin = Math.abs(b.spin);
422 if (spin > 0) b.spin = Math.sign(b.spin) * Math.max(0, spin - SPIN_STOP * dt);
423}
424
425/** Nudges a tile that landed outside the pool towards the rest of them. */
426function pullIn(world: World, b: Body, dt: number) {
427 const cx = world.bounds.x + world.bounds.w / 2;
428 const cy = world.bounds.y + world.bounds.h / 2;
429 const dx = cx - b.x;
430 const dy = cy - b.y;
431 const d = Math.hypot(dx, dy) || 1;
432 b.vx += (dx / d) * ENTRY_PULL * dt;
433 b.vy += (dy / d) * ENTRY_PULL * dt;
434}
435
436/** Bounce off a standing stack, corner to corner if that is how it hits. */
437function hitWall(b: Body, wall: Rect, impacts: Impact[]) {
438 const hit = overlapOf(boxOf(wall), b);
439 if (!hit || hit.depth <= CONTACT_SLOP) return;
440
441 const speed = Math.hypot(b.vx, b.vy);
442 b.x += hit.nx * hit.depth;
443 b.y += hit.ny * hit.depth;
444 // Reflect whatever was heading into the wall; keep what was sliding along it.
445 const into = b.vx * hit.nx + b.vy * hit.ny;
446 if (into < 0) {
447 b.vx -= hit.nx * into * (1 + BOUND_RESTITUTION);
448 b.vy -= hit.ny * into * (1 + BOUND_RESTITUTION);
449 }
450 b.spin *= 0.7;
451 b.resting = false;
452 b.still = 0;
453 const strength = Math.min(1, speed / 1100);
454 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
455}
456
457/** The pool's edge. Once a tile is in, it stays in — this is the invariant the
458 * tests pin, since a discard that slid off the table would be lost. */
459function keepInBounds(world: World, b: Body, impacts: Impact[]) {
460 const half = aabbHalf(b);
461 const { x, y, w, h } = world.bounds;
462 // A pool narrower than a tile would otherwise fight itself; centre instead.
463 const minX = w <= half.x * 2 ? x + w / 2 : x + half.x;
464 const maxX = w <= half.x * 2 ? x + w / 2 : x + w - half.x;
465 const minY = h <= half.y * 2 ? y + h / 2 : y + half.y;
466 const maxY = h <= half.y * 2 ? y + h / 2 : y + h - half.y;
467
468 let hit = 0;
469 if (b.x < minX) {
470 b.x = minX;
471 hit = Math.max(hit, Math.abs(b.vx));
472 b.vx = Math.abs(b.vx) * BOUND_RESTITUTION;
473 b.vy *= BOUND_FRICTION;
474 } else if (b.x > maxX) {
475 b.x = maxX;
476 hit = Math.max(hit, Math.abs(b.vx));
477 b.vx = -Math.abs(b.vx) * BOUND_RESTITUTION;
478 b.vy *= BOUND_FRICTION;
479 }
480 if (b.y < minY) {
481 b.y = minY;
482 hit = Math.max(hit, Math.abs(b.vy));
483 b.vy = Math.abs(b.vy) * BOUND_RESTITUTION;
484 b.vx *= BOUND_FRICTION;
485 } else if (b.y > maxY) {
486 b.y = maxY;
487 hit = Math.max(hit, Math.abs(b.vy));
488 b.vy = -Math.abs(b.vy) * BOUND_RESTITUTION;
489 b.vx *= BOUND_FRICTION;
490 }
491 // Only a real knock counts as being disturbed. A tile held against the edge
492 // by its neighbours is clamped every single step, and treating that as a knock
493 // would keep the whole pool awake for ever.
494 if (hit > SLEEP_SPEED) {
495 b.still = 0;
496 const strength = Math.min(1, hit / 1100);
497 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
498 }
499}
500
501/**
502 * Tile against tile.
503 *
504 * Only tiles flat on the felt take part, so a thrown tile passes over the pile
505 * instead of shouldering through it, and a cheap circle test throws out the pairs
506 * that are nowhere near before the real rectangle test runs. Pairs where both
507 * tiles have settled are left alone entirely, which is nearly all of them.
508 */
509function collideTiles(world: World, impacts: Impact[]) {
510 const bodies = world.bodies;
511 for (let i = 0; i < bodies.length; i++) {
512 const a = bodies[i];
513 if (a.z > ON_FELT) continue;
514 for (let j = i + 1; j < bodies.length; j++) {
515 const b = bodies[j];
516 if (b.z > ON_FELT) continue;
517 if (a.resting && b.resting) continue;
518 if (Math.hypot(b.x - a.x, b.y - a.y) > circumradius(a) + circumradius(b)) continue;
519 resolvePair(a, b, impacts);
520 }
521 }
522}
523
524function resolvePair(a: Body, b: Body, impacts: Impact[]) {
525 const hit = overlapOf(a, b);
526 if (!hit) return;
527 // Resting in contact is not a collision. See CONTACT_SLOP.
528 const depth = hit.depth - CONTACT_SLOP;
529 if (depth <= 0) return;
530 const { nx, ny } = hit;
531
532 // Push apart. A tile that has settled is the heavy one: a tile thrown into a
533 // pool shoulders in, rather than the pool scattering out of its way.
534 const aShare = a.resting === b.resting ? 0.5 : a.resting ? 0 : 1;
535 const bShare = 1 - aShare;
536 a.x -= nx * depth * aShare;
537 a.y -= ny * depth * aShare;
538 b.x += nx * depth * bShare;
539 b.y += ny * depth * bShare;
540
541 // Impulse along the way out, plus a spin kick off what is left over.
542 //
543 // Only a genuine approach speed counts, and only that wakes anything. Nudging
544 // two touching tiles apart is not a collision: a jammed corner of the pool is
545 // corrected by a fraction of a pixel every step for as long as it is jammed,
546 // and treating each of those as a shove would keep the pile awake for ever.
547 const rvx = b.vx - a.vx;
548 const rvy = b.vy - a.vy;
549 const along = rvx * nx + rvy * ny;
550 if (along >= -SLEEP_SPEED) return;
551
552 const jolt = -along * (1 + TILE_RESTITUTION) * 0.5;
553 a.vx -= nx * jolt;
554 a.vy -= ny * jolt;
555 b.vx += nx * jolt;
556 b.vy += ny * jolt;
557
558 const tangent = rvx * -ny + rvy * nx;
559 a.spin -= tangent * SPIN_TRANSFER * 0.06;
560 b.spin += tangent * SPIN_TRANSFER * 0.06;
561
562 const strength = Math.min(1, Math.abs(along) / 900);
563 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
564
565 // Whatever was asleep has been shoved, so it is awake now.
566 wake(a);
567 wake(b);
568}
569
570function wake(b: Body) {
571 if (b.resting) b.awake = 0;
572 b.resting = false;
573 b.still = 0;
574}
575
576function sleep(b: Body) {
577 b.vx = 0;
578 b.vy = 0;
579 b.spin = 0;
580 b.z = 0;
581 b.vz = 0;
582 b.resting = true;
583 b.awake = 0;
584}
585
586function trySleep(b: Body) {
587 const speed = Math.hypot(b.vx, b.vy);
588 const slow =
589 b.entered && b.z <= 0 && b.vz === 0 && speed < SLEEP_SPEED && Math.abs(b.spin) < SLEEP_SPIN;
590 if (slow && ++b.still >= SLEEP_STEPS) return sleep(b);
591 if (!slow) b.still = 0;
592 // Backstop: shuffling about in a crowded pool for this long is settled enough.
593 if (b.entered && b.awake > AWAKE_LIMIT && speed < SLEEP_SPEED * 4) sleep(b);
594}
595
596/**
597 * Make room for a tile placed straight into a settled pile, without running
598 * time. Used when a pile is rebuilt — a reload, an undo — where the tiles have
599 * to be somewhere sensible immediately and nothing should appear to move.
600 */
601function separate(world: World, body: Body, passes = 16) {
602 // Which way to go when two tiles are exactly on top of each other. Stepping
603 // by the golden angle fans successive tiles out in every direction, where a
604 // fixed axis would march them all one way and pack them against a pool edge.
605 const escape = world.bodies.indexOf(body) * 2.39996;
606
607 for (let p = 0; p < passes; p++) {
608 let moved = false;
609 for (const other of world.bodies) {
610 if (other === body) continue;
611 const hit = overlapOf(other, body);
612 if (!hit || hit.depth <= CONTACT_SLOP) continue;
613 if (Math.hypot(body.x - other.x, body.y - other.y) < 0.0001) {
614 body.x += Math.cos(escape + p) * hit.depth;
615 body.y += Math.sin(escape + p) * hit.depth;
616 } else {
617 body.x += hit.nx * hit.depth;
618 body.y += hit.ny * hit.depth;
619 }
620 moved = true;
621 }
622 clampInto(world.bounds, body);
623 if (!moved) break;
624 }
625}
626
627function clampInto(r: Rect, b: Body) {
628 const half = aabbHalf(b);
629 const minX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + half.x;
630 const maxX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + r.w - half.x;
631 const minY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + half.y;
632 const maxY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + r.h - half.y;
633 b.x = Math.min(maxX, Math.max(minX, b.x));
634 b.y = Math.min(maxY, Math.max(minY, b.y));
635}
636
637/** Whether everything has settled — what the render loop idles on. */
638export const settled = (world: World) =>
639 world.bodies.every((b) => b.resting && b.scale === 1);
640
641/** How far outside the pool a tile is sitting. The tests' invariant. */
642export function outside(b: Body, pool: Rect): number {
643 const half = aabbHalf(b);
644 return Math.max(
645 0,
646 pool.x + half.x - b.x,
647 b.x - (pool.x + pool.w - half.x),
648 pool.y + half.y - b.y,
649 b.y - (pool.y + pool.h - half.y),
650 );
651}
652
653/** Whether two tiles are sharing ground, which they must never do at rest. */
654export function overlapping(a: Body, b: Body): number {
655 const hit = overlapOf(a, b);
656 return hit ? hit.depth : 0;
657}
658
659/** Scale a tile is drawn at, given how high it is. Sells the arc on a flat
660 * canvas; the renderer offsets the shadow by the same height. */
661export const zScale = (z: number) => 1 + z * 0.0016;
662
663/**
664 * The upward kick that puts a tile back on the felt after `seconds` in the air.
665 * How a throw is aimed: pick how long it should take, and the horizontal speed
666 * follows from the distance.
667 */
668export const liftFor = (seconds: number) => (GRAVITY * seconds) / 2;
669
670/** How high that kick gets — worth checking against WALL_HEIGHT. */
671export const peakOf = (vz: number) => (vz * vz) / (2 * GRAVITY);