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/**
99 * How hard a tile that merely *arrived* counts as having arrived: enough for
100 * the seat it came in past to notice, deliberately under the threshold the
101 * renderer plays a clack at. Nothing was hit, so nothing should be heard.
102 */
103const ARRIVED = 0.1;
104
105/** How fast a tile drawn at hand size shrinks to the size it is in the pool. */
106const SCALE_EASE = 6;
107
108export const TAU = Math.PI * 2;
109/**
110 * How quickly whatever is left of a tumble is taken up once the tile is down.
111 * A thrown tile turns over in the air a whole number of times, so it should be
112 * face up as it lands — but a bounce or a shove can leave it part-way round, and
113 * a mahjong tile on a table is never resting on its face. This takes up the
114 * remainder, and `sleep` guarantees the rest.
115 */
116const FLIP_SETTLE = 14;
117
118export interface Rect {
119 x: number;
120 y: number;
121 w: number;
122 h: number;
123}
124
125/** Anything the collision routines can treat as a rotated rectangle. */
126interface Box {
127 x: number;
128 y: number;
129 w: number;
130 h: number;
131 angle: number;
132}
133
134export interface Body {
135 tile: Tile;
136 /** Who threw it — for the fly-out when it is claimed, not for any marking. */
137 seat: SeatId;
138 /** Centre on the felt plane. */
139 x: number;
140 y: number;
141 vx: number;
142 vy: number;
143 /** Height above the felt, and its rate. Only ever >= 0. */
144 z: number;
145 vz: number;
146 angle: number;
147 spin: number;
148 /**
149 * Turning over in the air, about an axis lying in the table — what a thrown
150 * tile does, as opposed to `angle`, which is it turning flat on the cloth.
151 * Zero, or any whole number of turns, is face up.
152 */
153 flip: number;
154 flipSpin: number;
155 /** Which way that axis points: a tile tumbles across its line of travel. */
156 flipAxis: number;
157 w: number;
158 h: number;
159 /**
160 * Render-only: what to multiply the drawn size by, easing to 1. A tile is
161 * drawn big in a hand so it can be read, and small in the pool because that is
162 * the size it is in the wall, so a thrown one has to settle from one to the
163 * other. Eased here rather than in the renderer so it does not run at a
164 * different speed on a different frame rate.
165 */
166 scale: number;
167 /**
168 * Whether it has ever been inside the pool. Until it has, it is free to fly
169 * over the wall from a seat's edge; once it has, the pool keeps it.
170 */
171 entered: boolean;
172 /**
173 * Which side of the table it is still on its way in over. Every tile is
174 * thrown from outside, so every tile has one until it lands; it is what the
175 * table reports when the tile finally gets in, since by then there is no
176 * longer an edge to read off its position.
177 */
178 over?: Edge;
179 /**
180 * Whether it has got clear of the hand it was thrown from. A tile leaves from
181 * *inside* its own row — `throwFrom` is the middle of the last cell — so on
182 * the frame it is let go it is overlapping its thrower's own tiles, and
183 * without this every throw would ricochet off the hand that made it. Your own
184 * tiles are not solid to you until you are out of them.
185 */
186 leftSeat: boolean;
187 /**
188 * In somebody's fingers. Its position is set from outside — a finger is not
189 * a force — so the solver leaves it entirely alone: it does not fall, drift,
190 * settle or take a shove, and it is held high enough to pass over everything
191 * else while it is being carried.
192 */
193 carried: boolean;
194 resting: boolean;
195 /** Consecutive slow steps, counting towards sleep. */
196 still: number;
197 /** Steps lived, for the grace period on getting into the pool. */
198 age: number;
199 /** Steps since it last woke, for the backstop on settling. */
200 awake: number;
201}
202
203/**
204 * Which edge of the middle a tile ran into. The middle stops where the four
205 * players' tiles start, so an edge is somebody's hand: a tile that reaches one
206 * hard has been thrown into their tiles, and they have something to say about
207 * it. Seats are the caller's business; this only says which way it went off.
208 */
209export type Edge = 'left' | 'right' | 'top' | 'bottom';
210
211/** A collision loud enough to hear. `strength` is 0..1. */
212export interface Impact {
213 x: number;
214 y: number;
215 strength: number;
216 /** Set when it was the edge of the table it hit, not a wall or another tile. */
217 edge?: Edge;
218 /** Whose tiles it ran into, where what it hit belonged to somebody. */
219 into?: SeatId;
220 /** Whose discard it was — you cannot be barged by your own tile. */
221 seat?: SeatId;
222}
223
224/**
225 * Something solid on the table. Everything that stops a tile is another tile:
226 * the stacks still standing in the wall, the sets people have laid down, and
227 * the sixteen everyone is holding. `seat` is whose it is, where it is somebody's
228 * — a tile thrown into a hand is a thing that hand's owner answers.
229 */
230export interface Barrier {
231 rect: Rect;
232 /** Turned, where it is turned: the wall is built as a pinwheel and the whole
233 * square is set at an angle, so its stacks are not axis-aligned boxes. */
234 angle?: number;
235 seat?: SeatId;
236}
237
238export interface World {
239 /** Where tiles come to rest — inside the wall square. */
240 bounds: Rect;
241 /** Stacks of two still standing. Half and spent stacks are not obstacles. */
242 walls: Barrier[];
243 bodies: Body[];
244 /** Left-over time from the last frame, so steps stay a fixed size. */
245 carry: number;
246 /**
247 * Overlaps pushed apart in the last step. The pile is not settled while this
248 * is non-zero, however still everything looks — two tiles asleep inside each
249 * other would otherwise stay that way for the rest of the hand, because a
250 * pile that has stopped moving stops being stepped.
251 */
252 contacts: number;
253 /** Steps spent untangling a pile that is otherwise asleep, so it cannot spin. */
254 relaxed: number;
255}
256
257export interface Spawn {
258 tile: Tile;
259 seat: SeatId;
260 x: number;
261 y: number;
262 vx: number;
263 vy: number;
264 z: number;
265 vz: number;
266 angle: number;
267 spin: number;
268 /** Whole turns to make in the air. It lands face up whatever this is. */
269 flipTurns?: number;
270 /** Seconds of flight those turns are spread over. */
271 flipOver?: number;
272 flipAxis?: number;
273 w: number;
274 h: number;
275 /** Drawn this much bigger to start with, easing to its pool size. */
276 scale?: number;
277 /** Already settled — a pile being rebuilt after a reload or an undo. */
278 atRest?: boolean;
279}
280
281export function createWorld(bounds: Rect, walls: Barrier[] = []): World {
282 return { bounds, walls, bodies: [], carry: 0, contacts: 0, relaxed: 0 };
283}
284
285export function addBody(world: World, s: Spawn): Body {
286 const body: Body = {
287 tile: s.tile,
288 seat: s.seat,
289 x: s.x,
290 y: s.y,
291 vx: s.atRest ? 0 : s.vx,
292 vy: s.atRest ? 0 : s.vy,
293 z: s.atRest ? 0 : s.z,
294 vz: s.atRest ? 0 : s.vz,
295 angle: s.angle,
296 spin: s.atRest ? 0 : s.spin,
297 flip: 0,
298 // Spread the turns over the flight, so the tile comes down as it comes back
299 // round to face up rather than being snapped there on landing.
300 flipSpin:
301 s.atRest || !s.flipTurns || !s.flipOver ? 0 : (TAU * s.flipTurns) / s.flipOver,
302 flipAxis: s.flipAxis ?? 0,
303 w: s.w,
304 h: s.h,
305 scale: s.atRest ? 1 : s.scale ?? 1,
306 entered: !!s.atRest,
307 // A rebuilt pile is already lying in the middle, not in anybody's hand.
308 leftSeat: !!s.atRest,
309 carried: false,
310 resting: !!s.atRest,
311 still: s.atRest ? SLEEP_STEPS : 0,
312 age: 0,
313 awake: 0,
314 };
315 world.bodies.push(body);
316 if (s.atRest) {
317 // A tile dropped straight into a settled pile still has to make room. This
318 // is a first shove only — the relaxing below finishes the job, which matters
319 // for a whole pile rebuilt at once when a saved game is picked up.
320 separate(world, body);
321 world.contacts++;
322 }
323 return body;
324}
325
326// ---- rotated rectangles ---------------------------------------------------
327
328/** Distance from a box's centre to its edge, measured along `ax`. */
329function reach(b: Box, ax: { x: number; y: number }): number {
330 const c = Math.cos(b.angle);
331 const s = Math.sin(b.angle);
332 return (
333 Math.abs(c * ax.x + s * ax.y) * (b.w / 2) + Math.abs(-s * ax.x + c * ax.y) * (b.h / 2)
334 );
335}
336
337/** The rotated rectangle's own bounding box, for the pool's straight edges. */
338function aabbHalf(b: Box) {
339 const c = Math.abs(Math.cos(b.angle));
340 const s = Math.abs(Math.sin(b.angle));
341 return { x: (b.w / 2) * c + (b.h / 2) * s, y: (b.w / 2) * s + (b.h / 2) * c };
342}
343
344/** Enough to skip a pair without doing the real work. */
345const circumradius = (b: Box) => Math.hypot(b.w, b.h) / 2;
346
347/**
348 * Separating axis test between two rectangles at any angle. Returns the
349 * shallowest way out — the direction to push `b` away from `a`, and by how much
350 * — or null if they are clear of each other.
351 *
352 * Four axes is all a pair of rectangles needs: each box's two edge normals.
353 */
354function overlapOf(a: Box, b: Box): { nx: number; ny: number; depth: number } | null {
355 const ca = Math.cos(a.angle);
356 const sa = Math.sin(a.angle);
357 const cb = Math.cos(b.angle);
358 const sb = Math.sin(b.angle);
359 const axes = [
360 { x: ca, y: sa },
361 { x: -sa, y: ca },
362 { x: cb, y: sb },
363 { x: -sb, y: cb },
364 ];
365
366 const dx = b.x - a.x;
367 const dy = b.y - a.y;
368 let depth = Infinity;
369 let nx = 0;
370 let ny = 0;
371
372 for (const ax of axes) {
373 const gap = reach(a, ax) + reach(b, ax) - Math.abs(dx * ax.x + dy * ax.y);
374 if (gap <= 0) return null;
375 if (gap < depth) {
376 depth = gap;
377 // Always pointing from a towards b, so callers need not guess.
378 const sign = dx * ax.x + dy * ax.y < 0 ? -1 : 1;
379 nx = ax.x * sign;
380 ny = ax.y * sign;
381 }
382 }
383 return { nx, ny, depth };
384}
385
386/** A standing stack, as something the tests above can chew on. */
387const boxOf = (r: Rect, angle = 0): Box => ({
388 x: r.x + r.w / 2,
389 y: r.y + r.h / 2,
390 w: r.w,
391 h: r.h,
392 angle,
393});
394
395// ---- stepping -------------------------------------------------------------
396
397/**
398 * Where a tile's *centre* may be for the whole of it to be inside `r`.
399 *
400 * One place rather than three, because the three have to agree: the edge holds
401 * a tile at these limits, and the moment it starts holding it is the moment the
402 * tile reaches them. Deciding that on the centre instead would mean the tile is
403 * declared in while it is still half out, and the first thing the edge did
404 * would be to shove it the rest of the way — half a tile, in one frame, at a
405 * line that is nowhere near the one you can see.
406 *
407 * A pool narrower than a tile would otherwise fight itself, so it centres.
408 */
409function limitsOf(r: Rect, b: Box) {
410 const half = aabbHalf(b);
411 return {
412 minX: r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + half.x,
413 maxX: r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + r.w - half.x,
414 minY: r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + half.y,
415 maxY: r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + r.h - half.y,
416 };
417}
418
419/** Whether the whole tile has made it in — the edge's own test for `entered`. */
420function wholly(r: Rect, b: Body): boolean {
421 const l = limitsOf(r, b);
422 return b.x >= l.minX && b.x <= l.maxX && b.y >= l.minY && b.y <= l.maxY;
423}
424
425/**
426 * Whose side of the table a tile has ended up off, if it is off any of them.
427 * The furthest it is out, so a tile that overshot a corner belongs to whichever
428 * of the two it went past by more.
429 */
430function outsideEdge(r: Rect, b: Body): Edge | undefined {
431 const out: [Edge, number][] = [
432 ['left', r.x - b.x],
433 ['right', b.x - (r.x + r.w)],
434 ['top', r.y - b.y],
435 ['bottom', b.y - (r.y + r.h)],
436 ];
437 let worst: [Edge, number] = out[0];
438 for (const one of out) if (one[1] > worst[1]) worst = one;
439 return worst[1] > 0 ? worst[0] : undefined;
440}
441
442/**
443 * Run the world forward. `elapsed` is real seconds since the last call; it is
444 * consumed in fixed steps so the result does not depend on the frame rate.
445 * Returns the impacts worth a sound.
446 */
447export function advance(world: World, elapsed: number, stopOnImpact = false): Impact[] {
448 world.carry += Math.max(0, elapsed);
449 let steps = Math.floor(world.carry / FIXED_DT);
450 if (steps > MAX_SUBSTEPS) {
451 // Drop the backlog rather than working through it.
452 world.carry = 0;
453 steps = MAX_SUBSTEPS;
454 } else {
455 world.carry -= steps * FIXED_DT;
456 }
457
458 const impacts: Impact[] = [];
459 for (let i = 0; i < steps; i++) {
460 step(world, impacts);
461 // Freeze on the step that resolved the contact, and drop what is left of
462 // the frame — the debugger wants the tile where it touched, not where it
463 // would have been fifteen milliseconds later. See ui/colliders.ts.
464 if (stopOnImpact && impacts.length) {
465 world.carry = 0;
466 break;
467 }
468 }
469 return impacts;
470}
471
472/** One fixed step. Exported for the tests, which drive it directly. */
473export function step(world: World, impacts: Impact[] = []): Impact[] {
474 const dt = FIXED_DT;
475 world.contacts = 0;
476
477 for (const b of world.bodies) {
478 if (b.scale !== 1) {
479 b.scale += (1 - b.scale) * Math.min(1, SCALE_EASE * dt);
480 if (Math.abs(b.scale - 1) < 0.002) b.scale = 1;
481 }
482 // A tile in the fingers is driven, not simulated. Nothing below applies
483 // to it, and it stays awake so it is drawn where the finger put it.
484 if (b.carried) {
485 b.still = 0;
486 b.awake = 0;
487 continue;
488 }
489 if (b.resting) continue;
490 b.age++;
491 b.awake++;
492
493 // --- through the air ---
494 if (b.z > 0 || b.vz !== 0) {
495 b.vz -= GRAVITY * dt;
496 b.z += b.vz * dt;
497 if (b.z <= 0) {
498 const landing = Math.abs(b.vz);
499 b.z = 0;
500 // Below a knock it stops dead rather than shivering out a bounce.
501 b.vz = landing > 40 ? landing * Z_RESTITUTION : 0;
502 const strength = Math.min(1, landing / 900);
503 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
504 }
505 }
506
507 b.x += b.vx * dt;
508 b.y += b.vy * dt;
509 b.angle += b.spin * dt;
510
511 // Turning over. In the air it tumbles; once it is down, whatever is left of
512 // the turn is taken up so it ends flat on its back with its face showing.
513 if (b.flipSpin !== 0) {
514 if (b.z > 0) {
515 b.flip += b.flipSpin * dt;
516 } else {
517 const target = Math.round(b.flip / TAU) * TAU;
518 b.flip += (target - b.flip) * Math.min(1, FLIP_SETTLE * dt);
519 if (Math.abs(target - b.flip) < 0.01) {
520 b.flip = target;
521 b.flipSpin = 0;
522 }
523 }
524 }
525
526 if (!b.entered) {
527 // Kept from step to step: on the step it finally gets in it is inside
528 // already, and there would be nothing left to read.
529 b.over = outsideEdge(world.bounds, b) ?? b.over;
530 // In means all of it in. Anything less and keepInBounds below would
531 // finish the job in a single frame, which is a collision with nothing.
532 if (wholly(world.bounds, b)) {
533 b.entered = true;
534 // It came in over somebody's side of the table. Said quietly — nothing
535 // was struck, so there is nothing to hear — but said, because a tile
536 // arriving past a seat is that seat's to complain about. Its own
537 // thrower's edge is every tile's way in, and the caller drops that one.
538 if (b.over) {
539 impacts.push({ x: b.x, y: b.y, strength: ARRIVED, edge: b.over, seat: b.seat });
540 }
541 b.over = undefined;
542 } else if (b.age > ENTRY_GRACE) {
543 // Out of time going the long way round. Put it in, gently — but this is
544 // still a tile that ended up off the table on somebody's side.
545 if (b.over) {
546 impacts.push({ x: b.x, y: b.y, strength: ARRIVED, edge: b.over, seat: b.seat });
547 }
548 b.entered = true;
549 b.over = undefined;
550 b.z = 0;
551 b.vz = 0;
552 clampInto(world.bounds, b);
553 }
554 }
555
556 // --- on the felt ---
557 // Strictly z <= 0, not ON_FELT: friction is between the tile and the cloth,
558 // so a tile still in the air keeps the speed it was thrown with. ON_FELT is
559 // only about being low enough to be in another tile's way.
560 if (b.z <= 0) {
561 damp(b, dt);
562 // A tile that fell short skids in rather than sitting outside the pool.
563 if (!b.entered) pullIn(world, b, dt);
564 }
565
566 // A tile still above the wall is clear of it.
567 if (b.z < WALL_HEIGHT) {
568 let inOwnHand = false;
569 for (const wall of world.walls) {
570 if (wall.seat === b.seat && !b.leftSeat) {
571 // Still inside the row it was thrown from: note it, but pass through.
572 const over = overlapOf(boxOf(wall.rect, wall.angle), b);
573 if (over && over.depth > CONTACT_SLOP) inOwnHand = true;
574 continue;
575 }
576 hitWall(b, wall, impacts);
577 }
578 if (!inOwnHand) b.leftSeat = true;
579 }
580
581 // The pool's edge is the inside face of the wall, and it is only as tall as
582 // the wall — a tile lobbed high is over the top of it, not stopped by it.
583 if (b.entered && b.z < WALL_HEIGHT) keepInBounds(world, b, impacts);
584 }
585
586 collideTiles(world, impacts);
587 // Being shoved by a neighbour can put a tile back over the edge, and a tile
588 // that then fell asleep out there would stay out there. Only awake ones need
589 // it: resolvePair never moves a tile that has settled.
590 // Resting tiles included: they get pushed about by the untangling above, and
591 // a tile shoved over the edge must not be left there just because it is asleep.
592 for (const b of world.bodies) {
593 if (b.entered && b.z < WALL_HEIGHT) clampInto(world.bounds, b);
594 }
595 // Deciding to sleep comes last, so it judges where the step actually left
596 // things — before, a contact resolved after the decision would undo it and a
597 // crowded pool would stay awake for ever.
598 for (const b of world.bodies) if (!b.resting) trySleep(b);
599
600 // A pile that has stopped moving but is still untangling itself keeps being
601 // stepped, up to a point. Without the limit a configuration that cannot quite
602 // be resolved would keep the loop running for the rest of the hand.
603 world.relaxed = world.contacts > 0 && world.bodies.every((b) => b.resting) ? world.relaxed + 1 : 0;
604 return impacts;
605}
606
607/**
608 * The table has been re-measured — the window resized, or the wall was eaten
609 * further back. The tiles keep where they are, but a pool that shrank must not
610 * leave any of them stranded outside it, and the ones it moves have to wake up
611 * so they can settle again.
612 */
613export function reshape(world: World, bounds: Rect, walls: Barrier[]) {
614 world.bounds = bounds;
615 world.walls = walls;
616 for (const b of world.bodies) {
617 if (!b.entered) continue;
618 const x = b.x;
619 const y = b.y;
620 clampInto(bounds, b);
621 if (b.x !== x || b.y !== y) wake(b);
622 }
623
624 // A wall that has moved may be standing where a tile is lying. Anything it
625 // has come to overlap is woken, and the solver shoves it clear over the next
626 // few steps — which is a wall being pushed across a table taking the discards
627 // along in front of it, and is the whole reason you would push one.
628 //
629 // Only what is awake gets looked at each step, so without this a tile that
630 // had gone to sleep would sit inside the wall and stay there.
631 for (const b of world.bodies) {
632 if (b.z >= WALL_HEIGHT || b.carried) continue;
633 for (const w of world.walls) {
634 // Your own tiles are not solid to you until you are clear of them.
635 if (w.seat === b.seat && !b.leftSeat) continue;
636 const hit = overlapOf(boxOf(w.rect, w.angle), b);
637 if (hit && hit.depth > CONTACT_SLOP) {
638 wake(b);
639 break;
640 }
641 }
642 }
643}
644
645function damp(b: Body, dt: number) {
646 const k = Math.exp(-FELT_DAMP * dt);
647 b.vx *= k;
648 b.vy *= k;
649 b.spin *= Math.exp(-SPIN_DAMP * dt);
650
651 const speed = Math.hypot(b.vx, b.vy);
652 if (speed > 0) {
653 const next = Math.max(0, speed - FELT_STOP * dt);
654 b.vx = (b.vx / speed) * next;
655 b.vy = (b.vy / speed) * next;
656 }
657 const spin = Math.abs(b.spin);
658 if (spin > 0) b.spin = Math.sign(b.spin) * Math.max(0, spin - SPIN_STOP * dt);
659}
660
661/** Nudges a tile that landed outside the pool towards the rest of them. */
662function pullIn(world: World, b: Body, dt: number) {
663 const cx = world.bounds.x + world.bounds.w / 2;
664 const cy = world.bounds.y + world.bounds.h / 2;
665 const dx = cx - b.x;
666 const dy = cy - b.y;
667 const d = Math.hypot(dx, dy) || 1;
668 b.vx += (dx / d) * ENTRY_PULL * dt;
669 b.vy += (dy / d) * ENTRY_PULL * dt;
670}
671
672/** Bounce off whatever is standing there, corner to corner if that is how it
673 * hits — a stack of the wall, a laid-down set, somebody's hand. */
674function hitWall(b: Body, wall: Barrier, impacts: Impact[]) {
675 const hit = overlapOf(boxOf(wall.rect, wall.angle), b);
676 if (!hit || hit.depth <= CONTACT_SLOP) return;
677
678 const speed = Math.hypot(b.vx, b.vy);
679 b.x += hit.nx * hit.depth;
680 b.y += hit.ny * hit.depth;
681 // Reflect whatever was heading into the wall; keep what was sliding along it.
682 const into = b.vx * hit.nx + b.vy * hit.ny;
683 if (into < 0) {
684 b.vx -= hit.nx * into * (1 + BOUND_RESTITUTION);
685 b.vy -= hit.ny * into * (1 + BOUND_RESTITUTION);
686 }
687 b.spin *= 0.7;
688 b.resting = false;
689 b.still = 0;
690 const strength = Math.min(1, speed / 1100);
691 if (wall.seat !== undefined) {
692 // Into somebody's tiles. Reported however gently it arrived — their row is
693 // theirs, and a discard rolling into it is an event whatever speed it got
694 // there at. Which of them are loud enough to hear is the caller's business.
695 if (speed > SLEEP_SPEED) {
696 impacts.push({ x: b.x, y: b.y, strength, into: wall.seat, seat: b.seat });
697 }
698 } else if (strength > 0.12) {
699 impacts.push({ x: b.x, y: b.y, strength });
700 }
701}
702
703/** The pool's edge. Once a tile is in, it stays in — this is the invariant the
704 * tests pin, since a discard that slid off the table would be lost. */
705function keepInBounds(world: World, b: Body, impacts: Impact[]) {
706 const { minX, maxX, minY, maxY } = limitsOf(world.bounds, b);
707
708 let hit = 0;
709 let edge: Edge | undefined;
710 if (b.x < minX) {
711 b.x = minX;
712 hit = Math.max(hit, Math.abs(b.vx));
713 edge = 'left';
714 b.vx = Math.abs(b.vx) * BOUND_RESTITUTION;
715 b.vy *= BOUND_FRICTION;
716 } else if (b.x > maxX) {
717 b.x = maxX;
718 hit = Math.max(hit, Math.abs(b.vx));
719 edge = 'right';
720 b.vx = -Math.abs(b.vx) * BOUND_RESTITUTION;
721 b.vy *= BOUND_FRICTION;
722 }
723 if (b.y < minY) {
724 b.y = minY;
725 if (Math.abs(b.vy) > hit) edge = 'top';
726 hit = Math.max(hit, Math.abs(b.vy));
727 b.vy = Math.abs(b.vy) * BOUND_RESTITUTION;
728 b.vx *= BOUND_FRICTION;
729 } else if (b.y > maxY) {
730 b.y = maxY;
731 if (Math.abs(b.vy) > hit) edge = 'bottom';
732 hit = Math.max(hit, Math.abs(b.vy));
733 b.vy = -Math.abs(b.vy) * BOUND_RESTITUTION;
734 b.vx *= BOUND_FRICTION;
735 }
736 // Only a real knock counts as being disturbed. A tile held against the edge
737 // by its neighbours is clamped every single step, and treating that as a knock
738 // would keep the whole pool awake for ever.
739 //
740 // Anything that does arrive under its own steam is reported, however gently:
741 // the edge is where somebody's tiles are, so a discard rolling into them is
742 // an event whatever speed it got there at. Which of them are loud enough to
743 // be worth a sound is the caller's business.
744 if (hit > SLEEP_SPEED) {
745 b.still = 0;
746 impacts.push({ x: b.x, y: b.y, strength: Math.min(1, hit / 1100), edge, seat: b.seat });
747 }
748}
749
750/**
751 * Tile against tile.
752 *
753 * Only tiles flat on the felt take part, so a thrown tile passes over the pile
754 * instead of shouldering through it, and a cheap circle test throws out the pairs
755 * that are nowhere near before the real rectangle test runs. Pairs where both
756 * tiles have settled are left alone entirely, which is nearly all of them.
757 */
758function collideTiles(world: World, impacts: Impact[]) {
759 const bodies = world.bodies;
760 for (let i = 0; i < bodies.length; i++) {
761 const a = bodies[i];
762 if (a.z > ON_FELT) continue;
763 for (let j = i + 1; j < bodies.length; j++) {
764 const b = bodies[j];
765 if (b.z > ON_FELT) continue;
766 if (Math.hypot(b.x - a.x, b.y - a.y) > circumradius(a) + circumradius(b)) continue;
767 // Two tiles that have both settled are still pushed apart if they are
768 // inside each other — they are just not woken up for it. Skipping the pair
769 // outright was how a pile could end up with tiles sharing ground and stay
770 // that way, since nothing steps a pile that has stopped moving.
771 resolvePair(a, b, impacts, world);
772 }
773 }
774}
775
776function resolvePair(a: Body, b: Body, impacts: Impact[], world: World) {
777 const hit = overlapOf(a, b);
778 if (!hit) return;
779 // Resting in contact is not a collision. See CONTACT_SLOP.
780 const depth = hit.depth - CONTACT_SLOP;
781 if (depth <= 0) return;
782 const { nx, ny } = hit;
783
784 world.contacts++;
785 // Push apart. A tile that has settled is the heavy one: a tile thrown into a
786 // pool shoulders in, rather than the pool scattering out of its way.
787 const aShare = a.resting === b.resting ? 0.5 : a.resting ? 0 : 1;
788 const bShare = 1 - aShare;
789 a.x -= nx * depth * aShare;
790 a.y -= ny * depth * aShare;
791 b.x += nx * depth * bShare;
792 b.y += ny * depth * bShare;
793
794 // Impulse along the way out, plus a spin kick off what is left over.
795 //
796 // Only a genuine approach speed counts, and only that wakes anything. Nudging
797 // two touching tiles apart is not a collision: a jammed corner of the pool is
798 // corrected by a fraction of a pixel every step for as long as it is jammed,
799 // and treating each of those as a shove would keep the pile awake for ever.
800 const rvx = b.vx - a.vx;
801 const rvy = b.vy - a.vy;
802 const along = rvx * nx + rvy * ny;
803 if (along >= -SLEEP_SPEED) return;
804
805 const jolt = -along * (1 + TILE_RESTITUTION) * 0.5;
806 a.vx -= nx * jolt;
807 a.vy -= ny * jolt;
808 b.vx += nx * jolt;
809 b.vy += ny * jolt;
810
811 const tangent = rvx * -ny + rvy * nx;
812 a.spin -= tangent * SPIN_TRANSFER * 0.06;
813 b.spin += tangent * SPIN_TRANSFER * 0.06;
814
815 const strength = Math.min(1, Math.abs(along) / 900);
816 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
817
818 // Whatever was asleep has been shoved, so it is awake now.
819 wake(a);
820 wake(b);
821}
822
823function wake(b: Body) {
824 if (b.resting) b.awake = 0;
825 b.resting = false;
826 b.still = 0;
827}
828
829function sleep(b: Body) {
830 b.vx = 0;
831 b.vy = 0;
832 b.spin = 0;
833 b.z = 0;
834 b.vz = 0;
835 // Face up, always. A tile lying face down in the discards would be a tile
836 // nobody can read, so this is a guarantee and not an easing.
837 b.flip = Math.round(b.flip / TAU) * TAU;
838 b.flipSpin = 0;
839 b.resting = true;
840 b.awake = 0;
841}
842
843function trySleep(b: Body) {
844 const speed = Math.hypot(b.vx, b.vy);
845 const slow =
846 b.entered &&
847 b.z <= 0 &&
848 b.vz === 0 &&
849 b.flipSpin === 0 &&
850 speed < SLEEP_SPEED &&
851 Math.abs(b.spin) < SLEEP_SPIN;
852 if (slow && ++b.still >= SLEEP_STEPS) return sleep(b);
853 if (!slow) b.still = 0;
854 // Backstop: shuffling about in a crowded pool for this long is settled enough.
855 if (b.entered && b.awake > AWAKE_LIMIT && speed < SLEEP_SPEED * 4) sleep(b);
856}
857
858/**
859 * Make room for a tile placed straight into a settled pile, without running
860 * time. Used when a pile is rebuilt — a reload, an undo — where the tiles have
861 * to be somewhere sensible immediately and nothing should appear to move.
862 */
863function separate(world: World, body: Body, passes = 16) {
864 // Which way to go when two tiles are exactly on top of each other. Stepping
865 // by the golden angle fans successive tiles out in every direction, where a
866 // fixed axis would march them all one way and pack them against a pool edge.
867 const escape = world.bodies.indexOf(body) * 2.39996;
868
869 for (let p = 0; p < passes; p++) {
870 let moved = false;
871 for (const other of world.bodies) {
872 if (other === body) continue;
873 const hit = overlapOf(other, body);
874 if (!hit || hit.depth <= CONTACT_SLOP) continue;
875 if (Math.hypot(body.x - other.x, body.y - other.y) < 0.0001) {
876 body.x += Math.cos(escape + p) * hit.depth;
877 body.y += Math.sin(escape + p) * hit.depth;
878 } else {
879 body.x += hit.nx * hit.depth;
880 body.y += hit.ny * hit.depth;
881 }
882 moved = true;
883 }
884 clampInto(world.bounds, body);
885 if (!moved) break;
886 }
887}
888
889function clampInto(r: Rect, b: Body) {
890 const { minX, maxX, minY, maxY } = limitsOf(r, b);
891 b.x = Math.min(maxX, Math.max(minX, b.x));
892 b.y = Math.min(maxY, Math.max(minY, b.y));
893}
894
895/**
896 * How long a motionless pile is allowed to keep untangling itself before the
897 * result is accepted as good enough. Anything still overlapping after this is
898 * doing so by a fraction of a pixel, and the loop has better things to do than
899 * keep running over it.
900 */
901const RELAX_LIMIT = 90;
902
903/** Whether everything has settled — what the render loop idles on. */
904export const settled = (world: World) =>
905 world.bodies.every((b) => b.resting && b.scale === 1) &&
906 (world.contacts === 0 || world.relaxed > RELAX_LIMIT);
907
908/** How square-on the face is: 1 flat on its back, 0 edge-on, negative face down.
909 * The renderer squashes the tile by this along its tumbling axis. */
910export const faceOn = (b: Body) => Math.cos(b.flip);
911
912/**
913 * A tile's own bounding box, upright. Not what it collides with — that is the
914 * rotated rectangle — but what the felt's straight edges are worked out from,
915 * so the overlay draws both and the difference is visible.
916 */
917export function aabbOf(b: Body): Rect {
918 const half = aabbHalf(b);
919 return { x: b.x - half.x, y: b.y - half.y, w: half.x * 2, h: half.y * 2 };
920}
921
922/**
923 * Where this tile's *centre* is allowed to be, which is the edge less its own
924 * half. This is the line a bounce actually happens at, and it sits half a tile
925 * inside the one you can see — which is why a tile looks like it turned around
926 * early. For the overlay; the real work is `limitsOf`.
927 */
928export function centreLimits(r: Rect, b: Body): Rect {
929 const l = limitsOf(r, b);
930 return { x: l.minX, y: l.minY, w: l.maxX - l.minX, h: l.maxY - l.minY };
931}
932
933/** How far outside the pool a tile is sitting. The tests' invariant. */
934export function outside(b: Body, pool: Rect): number {
935 const half = aabbHalf(b);
936 return Math.max(
937 0,
938 pool.x + half.x - b.x,
939 b.x - (pool.x + pool.w - half.x),
940 pool.y + half.y - b.y,
941 b.y - (pool.y + pool.h - half.y),
942 );
943}
944
945/**
946 * How high a tile is held while it is being dragged. Above `WALL_HEIGHT` so it
947 * clears the wall, and above `ON_FELT` so it is out of the way of every tile it
948 * is carried over — the pile does not part in front of a finger, the tile goes
949 * over the top of it, which is what picking one up is.
950 */
951export const CARRY_Z = 46;
952
953/** The topmost tile under a point, or null. What a finger has taken hold of.
954 * Last first: later tiles were thrown later and lie on top. */
955export function tileAt(world: World, x: number, y: number): Body | null {
956 for (let i = world.bodies.length - 1; i >= 0; i--) {
957 const b = world.bodies[i];
958 const c = Math.cos(-b.angle);
959 const s = Math.sin(-b.angle);
960 const dx = x - b.x;
961 const dy = y - b.y;
962 // Into the tile's own frame, where the test is a rectangle again.
963 if (Math.abs(dx * c - dy * s) <= b.w / 2 && Math.abs(dx * s + dy * c) <= b.h / 2) return b;
964 }
965 return null;
966}
967
968/** Taken out of the pile and held above it. */
969export function lift(b: Body) {
970 b.carried = true;
971 b.resting = false;
972 b.z = CARRY_Z;
973 b.vx = 0;
974 b.vy = 0;
975 b.vz = 0;
976 b.spin = 0;
977 b.flipSpin = 0;
978 // Whatever it comes down on, it comes down face up, as a tile does.
979 b.flip = Math.round(b.flip / TAU) * TAU;
980}
981
982/** Let go of it: dropped where it is, or sent off at whatever it was flicked. */
983export function drop(b: Body, vx: number, vy: number, spin: number) {
984 b.carried = false;
985 b.vx = vx;
986 b.vy = vy;
987 b.spin = spin;
988 // It was being held up; from here it simply falls.
989 b.vz = 0;
990 b.still = 0;
991 b.awake = 0;
992 b.resting = false;
993 // Thrown from inside the pile rather than from a hand, so it is already past
994 // every seat's tiles and they are solid to it straight away.
995 b.leftSeat = true;
996 b.entered = true;
997}
998
999/** Whether two tiles are sharing ground, which they must never do at rest. */
1000export function overlapping(a: Body, b: Body): number {
1001 const hit = overlapOf(a, b);
1002 return hit ? hit.depth : 0;
1003}
1004
1005/** Scale a tile is drawn at, given how high it is. Sells the arc on a flat
1006 * canvas; the renderer offsets the shadow by the same height. */
1007export const zScale = (z: number) => 1 + z * 0.0016;
1008
1009/**
1010 * The upward kick that puts a tile back on the felt after `seconds` in the air.
1011 * How a throw is aimed: pick how long it should take, and the horizontal speed
1012 * follows from the distance.
1013 */
1014export const liftFor = (seconds: number) => (GRAVITY * seconds) / 2;
1015
1016/** How high that kick gets — worth checking against WALL_HEIGHT. */
1017export const peakOf = (vz: number) => (vz * vz) / (2 * GRAVITY);