diff --git a/apps/web/src/components/billiards/BilliardsOverlay.tsx b/apps/web/src/components/billiards/BilliardsOverlay.tsx new file mode 100644 index 0000000000..704b6662d3 --- /dev/null +++ b/apps/web/src/components/billiards/BilliardsOverlay.tsx @@ -0,0 +1,444 @@ +import { useNavigate } from "@tanstack/react-router"; +import { useGT } from "gt-react"; +import { GiftIcon, LockIcon, MedalIcon, PaletteIcon, XIcon } from "lucide-react"; +import { useEffect, useRef, useState, type CSSProperties } from "react"; +import { createPortal } from "react-dom"; + +import { cn } from "../../lib/utils"; +import { useThreadShells } from "../../state/entities"; +import { formatClock, type BilliardsLabels } from "./billiardsHud"; +import { medalFor, nextMedal, type Medal } from "./billiardsRecords"; +import { GLOW_BALLS, GOLDEN_SHOTS } from "./billiardsRules"; +import { BilliardsSession, type BilliardsHud } from "./billiardsSession"; +import { SKINS, type Skin, type SkinId } from "./billiardsSkins"; +import { snapshotThreads, threadAlerts, type ThreadAlert } from "./billiardsThreadAlerts"; + +const MAX_ALERTS = 3; +const MEDAL_COLORS: Readonly> = { + gold: "#f0c04a", + silver: "#d3d9e0", + bronze: "#d08a52", +}; + +// The pool hall's materials, kept here so the overlay matches what the canvas draws. +const CHALK = "rgba(236, 233, 222, 0.92)"; +const CHALK_DIM = "rgba(236, 233, 222, 0.55)"; +const CHALK_YELLOW = "#ffe08a"; +const CHALKBOARD: CSSProperties = { + background: "radial-gradient(120% 90% at 50% 40%, #2c3a33 0%, #1d2823 60%, #151c18 100%)", + border: "10px solid #4a2f1b", + boxShadow: + "inset 0 0 0 2px #6b4527, inset 0 0 30px rgba(0,0,0,0.55), 0 24px 60px rgba(0,0,0,0.7)", + color: CHALK, + textShadow: "0 0 1px rgba(236,233,222,0.5)", +}; +const BRASS_KNOB: CSSProperties = { + background: "radial-gradient(circle at 35% 30%, #f6dc93, #c9a24a 55%, #6e5016)", + boxShadow: "0 2px 6px rgba(0,0,0,0.6), inset 0 -1px 2px rgba(0,0,0,0.35)", + color: "#3a2808", +}; +const PAPER: CSSProperties = { + background: "linear-gradient(180deg, #fbf3dc, #efe2bf)", + boxShadow: "0 8px 18px rgba(0,0,0,0.55), 0 1px 0 rgba(255,255,255,0.6) inset", + color: "#2b2114", +}; +const WOOD_DRAWER: CSSProperties = { + background: "linear-gradient(180deg, #3d2416, #2a1810)", + boxShadow: "0 16px 40px rgba(0,0,0,0.7), inset 0 1px 0 rgba(255,255,255,0.08)", + border: "1px solid #5a3a22", +}; +const KEYFRAMES = ` +@keyframes ari-billiards-note-in { + 0% { transform: translateY(-24px) rotate(-9deg); opacity: 0; } + 55% { transform: translateY(3px) rotate(2deg); opacity: 1; } + 78% { transform: translateY(-1px) rotate(-3deg); } + 100% { transform: translateY(0) rotate(-1.5deg); } +} +@keyframes ari-billiards-pin-glow { + 0%, 100% { box-shadow: 0 0 0 0 rgba(255, 90, 70, 0.7); } + 50% { box-shadow: 0 0 0 5px rgba(255, 90, 70, 0); } +} +@keyframes ari-billiards-board-in { + 0% { transform: translateY(14px) scale(0.96); opacity: 0; } + 100% { transform: translateY(0) scale(1); opacity: 1; } +}`; + +function alertId(alert: ThreadAlert): string { + return `${alert.key}:${alert.kind}:${alert.thread.latestRun?.completedAt ?? ""}`; +} + +/** The billiards easter egg: a full-window table, opened by triple-clicking the Ari Code logo. */ +export default function BilliardsOverlay({ onClose }: { onClose: () => void }) { + const gt = useGT(); + const navigate = useNavigate(); + const dialogRef = useRef(null); + const canvasRef = useRef(null); + const sessionRef = useRef(null); + const chimedRef = useRef>(new Set()); + const [hud, setHud] = useState(null); + const threads = useThreadShells(); + const [baseline] = useState(() => snapshotThreads(threads)); + const [dismissed, setDismissed] = useState>(new Set()); + const [pickerOpen, setPickerOpen] = useState(false); + const alerts = threadAlerts(baseline, threads) + .filter((alert) => !dismissed.has(alertId(alert))) + .slice(0, MAX_ALERTS); + const alertKey = alerts.map(alertId).join("|"); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- runs the canvas game session while mounted and reports its HUD + useEffect(() => { + const canvas = canvasRef.current; + if (!canvas) return; + const session = new BilliardsSession(canvas, setHud); + sessionRef.current = session; + dialogRef.current?.focus(); + return () => { + session.dispose(); + sessionRef.current = null; + }; + }, []); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hands the canvas game its words in the reader's language + useEffect(() => { + const labels: BilliardsLabels = { + scratch: gt("Scratch"), + miss: gt("No ball hit"), + freeMiss: gt("Free this once"), + early8: gt("8 too early"), + wrong8: gt("Wrong pocket"), + scratch8: gt("Scratch on the 8"), + wand: gt("Wand"), + golden: gt("Golden cue"), + glow: gt("Glow cue"), + wandHint: gt("The first ball you hit drops"), + goldenHint: gt("Full sight for {count} shots", { count: GOLDEN_SHOTS }), + glowHint: gt("Bursts through {count} balls", { count: GLOW_BALLS }), + callPocket: gt("Click a pocket to call the 8"), + callFirst: gt("Call a pocket first"), + breakHint: gt("Hold to charge, release to shoot"), + controlsHint: gt("Shift for fine aim, Esc to close"), + penalty: (seconds) => gt("+{seconds} s", { seconds }), + }; + sessionRef.current?.setLabels(labels); + }, [gt]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rings a bell (Web Audio) when a new thread note is pinned + useEffect(() => { + const ids = alertKey === "" ? [] : alertKey.split("|"); + if (ids.some((id) => !chimedRef.current.has(id))) sessionRef.current?.chime(); + chimedRef.current = new Set([...chimedRef.current, ...ids]); + }, [alertKey, sessionRef, chimedRef]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a window Escape listener that closes the game while it is open + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== "Escape") return; + event.preventDefault(); + event.stopPropagation(); + if (!sessionRef.current?.cancelCharge()) onClose(); + }; + window.addEventListener("keydown", onKeyDown, true); + return () => window.removeEventListener("keydown", onKeyDown, true); + }, [onClose]); + + const openThread = (alert: ThreadAlert) => { + onClose(); + void navigate({ + to: "/$environmentId/$threadId", + params: { environmentId: alert.thread.environmentId, threadId: alert.thread.id }, + }); + }; + + const skinName = (id: SkinId) => { + switch (id) { + case "classic": + return gt("Classic", { $context: "billiards cue skin" }); + case "ari": + // oxlint-disable-next-line t3code/no-untranslated-copy -- product name + return "Ari"; + case "copper": + return gt("Copper", { $context: "billiards cue skin" }); + case "chrome": + return gt("Chrome", { $context: "billiards cue skin" }); + case "ember": + return gt("Ember", { $context: "billiards cue skin" }); + } + }; + const unlockHint = (skin: Skin) => { + switch (skin.unlock) { + case null: + return ""; + case "clear": + return gt("Clear a table"); + case "bronze": + return gt("Win a bronze medal"); + case "silver": + return gt("Win a silver medal"); + case "gold": + return gt("Win a gold medal"); + } + }; + const medalLabel = (medal: Medal) => + medal === "gold" + ? gt("Gold medal") + : medal === "silver" + ? gt("Silver medal") + : gt("Bronze medal"); + const nextMedalText = (totalMs: number) => { + const next = nextMedal(totalMs); + if (!next) return null; + const time = formatClock(next[1]); + return next[0] === "gold" + ? gt("Next: gold under {time}", { time }) + : next[0] === "silver" + ? gt("Next: silver under {time}", { time }) + : gt("Next: bronze under {time}", { time }); + }; + + const result = hud?.phase === "cleared" ? hud.result : null; + + return createPortal( +
+ +
+ + +
+ + +
+ + {pickerOpen && hud ? ( +
+

+ {gt("Stick")} +

+ {SKINS.map((skin) => { + const unlocked = hud.unlockedSkins.has(skin.id); + const selected = hud.skin === skin.id; + return ( + + ); + })} +
+ ) : null} + + {alerts.length > 0 ? ( +
+ {alerts.map((alert) => ( +
+ +

+ {alert.kind === "done" + ? gt("Done", { $context: "a thread finished" }) + : gt("Needs you")} +

+

{alert.thread.title}

+
+ + +
+
+ ))} +
+ ) : null} + + {hud?.phase === "cleared" ? ( +
+
+

+ {gt("Table cleared")} +

+

+ {formatClock(result?.run.totalMs ?? hud.totalMs, true)} +

+

+ {gt("{clock} played, +{seconds} s penalties, {shots} shots", { + clock: formatClock( + (result?.run.totalMs ?? hud.totalMs) - hud.penaltySeconds * 1000, + true, + ), + seconds: hud.penaltySeconds, + shots: hud.shots, + })} +

+ {result?.medal ? ( +

+ + {medalLabel(result.medal)} +

+ ) : null} + {result?.rankToday === 1 ? ( +

+ {gt("New best today!")} +

+ ) : null} + {result?.newSkins.map((id) => ( +

+ + {gt("New stick unlocked: {name}", { name: skinName(id) })} +

+ ))} + {result && result.medal !== "gold" ? ( +

+ {nextMedalText(result.run.totalMs)} +

+ ) : null} + {hud.todayRuns.length > 1 ? ( +
+

+ {gt("Today on this computer")} +

+
    + {hud.todayRuns.slice(0, 5).map((run, index) => { + const medal = medalFor(run.totalMs); + const current = run === result?.run; + return ( +
  1. + + {index + 1} + + {formatClock(run.totalMs, true)} + {run.penaltySeconds > 0 ? ( + + {gt("+{seconds} s", { seconds: run.penaltySeconds })} + + ) : null} + {medal ? ( + + ) : ( + + )} +
  2. + ); + })} +
+
+ ) : null} +
+ + +
+
+
+ ) : null} +
+
, + document.body, + ); +} diff --git a/apps/web/src/components/billiards/billiardsAim.test.ts b/apps/web/src/components/billiards/billiardsAim.test.ts new file mode 100644 index 0000000000..5750c77ef8 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsAim.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { castTrajectory } from "./billiardsAim.ts"; +import { makeBall, shotSpeed, type PhysicsEvent } from "./billiardsPhysics.ts"; +import { BilliardsGame } from "./billiardsRules.ts"; +import { BALL_RADIUS } from "./billiardsTable.ts"; + +const R = BALL_RADIUS; + +describe("castTrajectory", () => { + it("stops where the cue ball touches the first ball", () => { + const cue = makeBall(0, 0.5, 1.5); + const path = castTrajectory([cue, makeBall(3, 0.5, 1)], cue, -Math.PI / 2); + expect(path.ball?.id).toBe(3); + expect(path.points.at(-1)?.y).toBeCloseTo(1 + 2 * R); + }); + + it("follows the cue ball off a cushion to a ball behind it", () => { + const cue = makeBall(0, 0.5, 1.8); + // 45 degrees up and right: off the right rail, then on to a ball up on the left. + const bounceY = 1.8 - (1 - R - 0.5); + // The rail keeps 72% of the speed into it and 94% along it, like the physics. + const out = Math.hypot(0.72, 0.94); + const target = makeBall(5, 1 - R - (0.4 * 0.72) / out, bounceY - (0.4 * 0.94) / out); + const path = castTrajectory([cue, target], cue, -Math.PI / 4); + expect(path.points).toHaveLength(3); + expect(path.points[1]?.x).toBeCloseTo(1 - R); + expect(path.ball?.id).toBe(5); + }); + + it("ends in the pocket when the cue ball heads straight into one", () => { + const cue = makeBall(0, 0.3, 0.3); + const path = castTrajectory([cue], cue, (-3 * Math.PI) / 4); + expect(path.pocket).toBe(0); + expect(path.ball).toBeNull(); + }); + + it("predicts where a real shot comes off two cushions and stops", () => { + const cue = makeBall(0, 0.3, 1.6); + const angle = -1.1; + const speed = shotSpeed(0.45); + const path = castTrajectory([cue], cue, angle, speed, 6); + const game = new BilliardsGame({ skipBreak: true, balls: [makeBall(0, 0.3, 1.6)] }); + game.shoot(angle, speed); + const events: PhysicsEvent[] = []; + while (game.phase === "rolling") game.advance(1 / 60, events); + const end = path.points.at(-1)!; + const ball = game.ball(0)!; + expect(path.points.length).toBeGreaterThanOrEqual(3); + expect(path.stops).toBe(true); + expect(Math.hypot(end.x - ball.x, end.y - ball.y)).toBeLessThan(0.03); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsAim.ts b/apps/web/src/components/billiards/billiardsAim.ts new file mode 100644 index 0000000000..8e95fca357 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsAim.ts @@ -0,0 +1,133 @@ +import { + CUSHION_GRIP, + CUSHION_RESTITUTION, + DRAG, + ROLL_DECEL, + type Ball, +} from "./billiardsPhysics.ts"; +import { BALL_RADIUS, TABLE_LENGTH, TABLE_WIDTH, type Point } from "./billiardsTable.ts"; + +const R = BALL_RADIUS; +/** How many cushions the guide follows the cue ball off. */ +const AIM_BOUNCES = 2; +const MAX_LENGTH = 3; +/** The golden cue's full sight. */ +export const GOLDEN_SIGHT = { bounces: 5, length: 7 } as const; + +export interface Trajectory { + /** The cue ball's path: its centre at the start, at each cushion, and where it ends. */ + readonly points: ReadonlyArray; + /** The ball it hits first, with the cue ball touching it at the path's last point. */ + readonly ball: Ball | null; + /** The path ends in this pocket: a scratch, unless a ball comes first. */ + readonly pocket: number | null; + /** The cue ball runs out of speed at the path's end. */ + readonly stops: boolean; + /** Direction of the last segment, for the cue ball's deflection off `ball`. */ + readonly dx: number; + readonly dy: number; +} + +// Where the rails open into a pocket, measured along the rail the path reaches. +const CORNER_OPENING = 0.07; +const SIDE_OPENING = 0.045; + +/** The pocket whose mouth the path reaches at a rail, if any. */ +function pocketAt(x: number, y: number, onSideRail: boolean): number | null { + const right = x > TABLE_WIDTH / 2; + const top = y < TABLE_LENGTH / 2; + if (onSideRail && Math.abs(y - TABLE_LENGTH / 2) < SIDE_OPENING) return right ? 3 : 2; + const along = onSideRail ? Math.min(y, TABLE_LENGTH - y) : Math.min(x, TABLE_WIDTH - x); + if (along < CORNER_OPENING) return top ? (right ? 1 : 0) : right ? 5 : 4; + return null; +} + +/** How far a ball rolling at `speed` travels before friction stops it (same law as the physics). */ +function stoppingDistance(speed: number): number { + return speed / DRAG - (ROLL_DECEL / (DRAG * DRAG)) * Math.log(1 + (DRAG * speed) / ROLL_DECEL); +} + +/** The speed left after rolling `distance` from `speed`. */ +function speedAfter(speed: number, distance: number): number { + const target = stoppingDistance(speed) - distance; + if (target <= 0) return 0; + let low = 0; + let high = speed; + for (let i = 0; i < 30; i++) { + const mid = (low + high) / 2; + if (stoppingDistance(mid) < target) low = mid; + else high = mid; + } + return (low + high) / 2; +} + +/** + * Where the cue ball goes along `angle` if nothing slows it: off up to `bounces` cushions, + * until it touches a ball, runs into a pocket, or (given a `speed`) stops. Cushions bounce it the + * way the physics does: they keep less of the speed into the rail than along it. + */ +export function castTrajectory( + balls: ReadonlyArray, + cue: Ball, + angle: number, + speed: number | null = null, + bounces: number = AIM_BOUNCES, + maxLength: number = MAX_LENGTH, +): Trajectory { + let v = speed ?? Infinity; + let x = cue.x; + let y = cue.y; + let dx = Math.cos(angle); + let dy = Math.sin(angle); + let travelled = 0; + const points: Point[] = [{ x, y }]; + for (let bounce = 0; ; bounce++) { + let best = Infinity; + let hit: Ball | null = null; + for (const ball of balls) { + if (!ball.onTable || ball === cue) continue; + const fx = x - ball.x; + const fy = y - ball.y; + const b = fx * dx + fy * dy; + const c = fx * fx + fy * fy - 4 * R * R; + const disc = b * b - c; + if (disc < 0) continue; + const t = -b - Math.sqrt(disc); + if (t > 1e-6 && t < best) { + best = t; + hit = ball; + } + } + const wallX = dx > 0 ? (TABLE_WIDTH - R - x) / dx : dx < 0 ? (R - x) / dx : Infinity; + const wallY = dy > 0 ? (TABLE_LENGTH - R - y) / dy : dy < 0 ? (R - y) / dy : Infinity; + const wall = Math.max(0, Math.min(wallX, wallY)); + const rolls = v === Infinity ? Infinity : stoppingDistance(v); + const remaining = Math.min(maxLength - travelled, rolls); + if (hit && best <= wall && best <= remaining) { + points.push({ x: x + dx * best, y: y + dy * best }); + return { points, ball: hit, pocket: null, stops: false, dx, dy }; + } + const step = Math.min(wall, remaining); + x += dx * step; + y += dy * step; + travelled += step; + points.push({ x, y }); + if (step === remaining) { + return { points, ball: null, pocket: null, stops: rolls <= wall, dx, dy }; + } + const pocket = pocketAt(x, y, wall === wallX); + if (pocket !== null || bounce >= bounces) { + return { points, ball: null, pocket, stops: false, dx, dy }; + } + // Same bounce as the physics: the speed into the rail drops more than the speed along it. + const normalX = wall === wallX; + const along = normalX ? dy : dx; + const into = normalX ? dx : dy; + const outAlong = along * CUSHION_GRIP; + const outInto = -into * CUSHION_RESTITUTION; + const factor = Math.hypot(outAlong, outInto); + dx = normalX ? outInto / factor : outAlong / factor; + dy = normalX ? outAlong / factor : outInto / factor; + if (v !== Infinity) v = speedAfter(v, step) * factor; + } +} diff --git a/apps/web/src/components/billiards/billiardsAudio.ts b/apps/web/src/components/billiards/billiardsAudio.ts new file mode 100644 index 0000000000..4c9bf625c0 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsAudio.ts @@ -0,0 +1,133 @@ +// Every sound is synthesised, so the game ships no audio files. + +const clamp01 = (value: number) => Math.max(0, Math.min(1, value)); + +export class BilliardsAudio { + private context: AudioContext | null = null; + private master: GainNode | null = null; + private noise: AudioBuffer | null = null; + + /** Starts audio; call from a user gesture. */ + unlock(): void { + if (!this.context) { + const context = new AudioContext(); + const master = context.createGain(); + master.gain.value = 0.55; + master.connect(context.destination); + const noise = context.createBuffer( + 1, + Math.floor(context.sampleRate * 0.4), + context.sampleRate, + ); + const data = noise.getChannelData(0); + for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1; + this.context = context; + this.master = master; + this.noise = noise; + } + if (this.context.state === "suspended") void this.context.resume(); + } + + dispose(): void { + void this.context?.close(); + this.context = null; + } + + /** Ball on ball: a bright click whose pitch and level follow the impact. */ + click(speed: number): void { + const v = clamp01(speed / 5); + if (v < 0.01) return; + this.tone("sine", 2300 + Math.random() * 900 + v * 600, 1900, v * 0.45, 0.05); + this.hiss("bandpass", 3600, 1.4, v * 0.55, 0.02); + } + + /** Ball on cushion: a low, soft thud. */ + cushion(speed: number): void { + const v = clamp01(speed / 4); + if (v < 0.02) return; + this.tone("sine", 150, 70, v * 0.6, 0.12); + this.hiss("lowpass", 700, 0.7, v * 0.35, 0.07); + } + + /** Ball into a pocket: a hollow drop, then a rattle in the pocket. */ + pocket(): void { + this.tone("triangle", 240, 85, 0.35, 0.28); + this.hiss("bandpass", 950, 2, 0.22, 0.05, 0.09); + this.hiss("bandpass", 780, 2, 0.14, 0.05, 0.17); + } + + /** Cue tip on the cue ball. */ + cue(power: number): void { + const p = clamp01(power); + this.hiss("bandpass", 1500 + p * 900, 0.9, 0.25 + p * 0.5, 0.03); + this.tone("sine", 700 + p * 300, 500, 0.15 + p * 0.2, 0.04); + } + + /** A power-up: a quick rising chime. */ + powerUp(): void { + for (const [i, note] of [784, 1047, 1319, 1568].entries()) { + this.tone("sine", note, note * 1.01, 0.22, 0.28, i * 0.055); + this.tone("triangle", note * 2, note * 2, 0.05, 0.18, i * 0.055); + } + } + + /** A soft two-note bell: a thread wants attention. */ + chime(): void { + this.tone("sine", 1318, 1318, 0.2, 0.6); + this.tone("sine", 1760, 1760, 0.16, 0.8, 0.12); + } + + /** A ball taken by a power-up: a soft magic swish. */ + guide(): void { + this.tone("sine", 520, 1400, 0.16, 0.35); + this.hiss("highpass", 5000, 0.7, 0.08, 0.3); + } + + private tone( + type: OscillatorType, + from: number, + to: number, + gain: number, + decay: number, + delay = 0, + ): void { + const { context, master } = this; + if (!context || !master) return; + const at = context.currentTime + delay; + const oscillator = context.createOscillator(); + const envelope = context.createGain(); + oscillator.type = type; + oscillator.frequency.setValueAtTime(from, at); + oscillator.frequency.exponentialRampToValueAtTime(to, at + decay); + envelope.gain.setValueAtTime(gain, at); + envelope.gain.exponentialRampToValueAtTime(0.0001, at + decay); + oscillator.connect(envelope).connect(master); + oscillator.start(at); + oscillator.stop(at + decay + 0.02); + } + + private hiss( + type: BiquadFilterType, + frequency: number, + q: number, + gain: number, + decay: number, + delay = 0, + ): void { + const { context, master, noise } = this; + if (!context || !master || !noise) return; + const at = context.currentTime + delay; + const source = context.createBufferSource(); + const filter = context.createBiquadFilter(); + const envelope = context.createGain(); + source.buffer = noise; + filter.type = type; + filter.frequency.value = frequency; + filter.Q.value = q; + envelope.gain.setValueAtTime(gain, at); + envelope.gain.exponentialRampToValueAtTime(0.0001, at + decay); + source.connect(filter).connect(envelope).connect(master); + source.start(at, Math.random() * 0.3); + source.stop(at + decay + 0.02); + } +} diff --git a/apps/web/src/components/billiards/billiardsBalls.ts b/apps/web/src/components/billiards/billiardsBalls.ts new file mode 100644 index 0000000000..620171a2a0 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsBalls.ts @@ -0,0 +1,215 @@ +import { EIGHT } from "./billiardsRules.ts"; +import { BALL_RADIUS } from "./billiardsTable.ts"; + +// Balls are shaded per pixel from a 3D orientation, so stripes and numbers visibly roll. +// Each ball keeps a small sprite that is redrawn only when the ball turned. + +const COLORS: ReadonlyArray = [ + [244, 241, 232], + [242, 194, 48], + [33, 96, 212], + [216, 50, 43], + [108, 63, 163], + [240, 122, 31], + [29, 138, 74], + [140, 34, 51], + [21, 21, 21], +]; +const WHITE: readonly [number, number, number] = [246, 243, 234]; +const CUE_DOT: readonly [number, number, number] = [200, 40, 40]; +// Light from the top left, a little above. +const LIGHT = normalize([-0.38, -0.48, 0.79]); +const HALF = normalize([LIGHT[0], LIGHT[1], LIGHT[2] + 1]); +/** Cosine of the number disc's angular radius. */ +const NUMBER_DISC = Math.cos(0.5); +/** Stripe balls are white where the pole axis is steeper than this. */ +const STRIPE_CAP = 0.58; + +type Vec3 = [number, number, number]; + +function cross(a: Vec3, b: Vec3): Vec3 { + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; +} + +function normalize(v: Vec3): Vec3 { + const length = Math.hypot(v[0], v[1], v[2]); + return [v[0] / length, v[1] / length, v[2] / length]; +} + +/** Body axes in world space: e1, e2 (stripe pole) and e3 (number). z points at the viewer. */ +interface Orientation { + e1: Vec3; + e2: Vec3; + e3: Vec3; +} + +interface Sprite { + readonly canvas: HTMLCanvasElement; + readonly image: ImageData; + dirty: boolean; +} + +function rollVector(v: Vec3, ux: number, uy: number, cos: number, sin: number): void { + // Turns v in the plane of the travel direction u and z, carrying z towards u. + const a = v[0] * ux + v[1] * uy; + const c = v[2]; + const a2 = a * cos + c * sin; + const c2 = c * cos - a * sin; + v[0] += (a2 - a) * ux; + v[1] += (a2 - a) * uy; + v[2] = c2; +} + +export class BallSprites { + private readonly orientations = new Map(); + private readonly sprites = new Map(); + private size = 0; + + /** Sets the sprite size from the pixels per table unit; redraws everything when it changes. */ + resize(scale: number): void { + const size = Math.max(8, Math.min(72, Math.ceil(BALL_RADIUS * 2 * scale))); + if (size === this.size) return; + this.size = size; + this.sprites.clear(); + } + + reset(): void { + this.orientations.clear(); + for (const sprite of this.sprites.values()) sprite.dirty = true; + } + + /** Rolls a ball by the distance it travelled. */ + roll(id: number, dx: number, dy: number): void { + const distance = Math.hypot(dx, dy); + if (distance < 1e-6) return; + const orientation = this.orientation(id); + const angle = distance / BALL_RADIUS; + const ux = dx / distance; + const uy = dy / distance; + const cos = Math.cos(angle); + const sin = Math.sin(angle); + rollVector(orientation.e1, ux, uy, cos, sin); + rollVector(orientation.e2, ux, uy, cos, sin); + orientation.e1 = normalize(orientation.e1); + orientation.e2 = normalize(orientation.e2); + // Rebuild e3 from the other two, so rounding never skews the frame. + const [a, b] = [orientation.e1, orientation.e2]; + orientation.e3 = cross(a, b); + const c = orientation.e3; + orientation.e3 = normalize(c); + orientation.e2 = cross(orientation.e3, a); + const sprite = this.sprites.get(id); + if (sprite) sprite.dirty = true; + } + + /** Draws ball `id` centred on (x, y) in table units; `size` scales it, as when it sinks. */ + draw(ctx: CanvasRenderingContext2D, id: number, x: number, y: number, size = 1): void { + const sprite = this.sprite(id); + const r = BALL_RADIUS * size; + ctx.drawImage(sprite.canvas, x - r, y - r, r * 2, r * 2); + if (id === 0) return; + const { e3 } = this.orientation(id); + this.drawNumber(ctx, id, x, y, r, e3); + if (id > EIGHT) this.drawNumber(ctx, id, x, y, r, [-e3[0], -e3[1], -e3[2]]); + } + + private drawNumber( + ctx: CanvasRenderingContext2D, + id: number, + x: number, + y: number, + r: number, + axis: Vec3, + ): void { + if (axis[2] < 0.35) return; + const angle = Math.atan2(axis[1], axis[0]); + // Drawn at real pixel size: tiny fonts scaled up by the table transform render soft. + const matrix = ctx.getTransform(); + const at = matrix.transformPoint({ x: x + axis[0] * r * 0.98, y: y + axis[1] * r * 0.98 }); + const pixels = r * matrix.a; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, at.x, at.y); + ctx.rotate(angle); + ctx.scale(axis[2], 1); + ctx.rotate(-angle); + ctx.globalAlpha *= Math.min(1, (axis[2] - 0.35) * 4); + ctx.fillStyle = "#151515"; + ctx.font = `700 ${pixels * 0.62}px ui-sans-serif, system-ui, sans-serif`; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(String(id), 0, pixels * 0.04); + ctx.restore(); + } + + private orientation(id: number): Orientation { + let orientation = this.orientations.get(id); + if (!orientation) { + orientation = { e1: [1, 0, 0], e2: [0, 1, 0], e3: [0, 0, 1] }; + this.orientations.set(id, orientation); + } + return orientation; + } + + private sprite(id: number): Sprite { + let sprite = this.sprites.get(id); + if (!sprite) { + const canvas = document.createElement("canvas"); + canvas.width = this.size; + canvas.height = this.size; + const context = canvas.getContext("2d"); + const image = context + ? context.createImageData(this.size, this.size) + : new ImageData(this.size, this.size); + sprite = { canvas, image, dirty: true }; + this.sprites.set(id, sprite); + } + if (sprite.dirty) { + this.paint(id, sprite); + sprite.dirty = false; + } + return sprite; + } + + private paint(id: number, sprite: Sprite): void { + const { e2, e3 } = this.orientation(id); + const base = COLORS[id > EIGHT ? id - EIGHT : id] ?? WHITE; + const stripe = id > EIGHT; + const size = this.size; + const half = size / 2; + const data = sprite.image.data; + for (let py = 0; py < size; py++) { + for (let px = 0; px < size; px++) { + const i = (py * size + px) * 4; + const x = (px + 0.5 - half) / half; + const y = (py + 0.5 - half) / half; + const rr = x * x + y * y; + if (rr >= 1) { + data[i + 3] = 0; + continue; + } + const z = Math.sqrt(1 - rr); + const b2 = x * e2[0] + y * e2[1] + z * e2[2]; + const b3 = x * e3[0] + y * e3[1] + z * e3[2]; + let color = base; + if (id === 0) { + color = Math.abs(b3) > 0.965 ? CUE_DOT : WHITE; + } else if (Math.abs(b3) > NUMBER_DISC && (b3 > 0 || stripe)) { + color = WHITE; + } else if (stripe && Math.abs(b2) > STRIPE_CAP) { + color = WHITE; + } + const diffuse = Math.max(0, x * LIGHT[0] + y * LIGHT[1] + z * LIGHT[2]); + const specular = Math.max(0, x * HALF[0] + y * HALF[1] + z * HALF[2]) ** 48; + const light = 0.42 + 0.68 * diffuse; + // A soft rim darkens the edge, like the cloth under it bouncing less light back. + const rim = 0.78 + 0.22 * z; + const edge = Math.min(1, (1 - Math.sqrt(rr)) * half * 1.5); + data[i] = Math.min(255, color[0] * light * rim + specular * 235); + data[i + 1] = Math.min(255, color[1] * light * rim + specular * 235); + data[i + 2] = Math.min(255, color[2] * light * rim + specular * 235); + data[i + 3] = edge * 255; + } + } + sprite.canvas.getContext("2d")?.putImageData(sprite.image, 0, 0); + } +} diff --git a/apps/web/src/components/billiards/billiardsCues.ts b/apps/web/src/components/billiards/billiardsCues.ts new file mode 100644 index 0000000000..e9e90c9a78 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsCues.ts @@ -0,0 +1,298 @@ +import type { Ball } from "./billiardsPhysics.ts"; +import { RING_RADIUS, type PowerKind, type PowerRing } from "./billiardsRules.ts"; +import type { SkinId } from "./billiardsSkins.ts"; +import { BALL_RADIUS } from "./billiardsTable.ts"; + +// The stick's looks and the power-up rings. A power-up changes the stick while it's armed; +// the same looks become unlockable skins later. + +export type CueStyle = SkinId | PowerKind; + +const R = BALL_RADIUS; +const CUE_LENGTH = 1.15; +const WAND_LENGTH = 0.62; + +/** Each power-up's colour, as "r, g, b". */ +export const POWER_COLORS: Readonly> = { + wand: "190, 140, 255", + golden: "255, 200, 80", + glow: "90, 235, 255", +}; + +/** Where the stick's tip sits, for effects that come off it. */ +export function cueTip(cue: Ball, angle: number, power: number): { x: number; y: number } { + const back = R + 0.012 + power * 0.14; + return { x: cue.x - Math.cos(angle) * back, y: cue.y - Math.sin(angle) * back }; +} + +export function drawCue( + ctx: CanvasRenderingContext2D, + cue: Ball, + angle: number, + power: number, + style: CueStyle, + now: number, +): void { + const dx = Math.cos(angle); + const dy = Math.sin(angle); + const tip = cueTip(cue, angle, power); + const length = style === "wand" ? WAND_LENGTH : CUE_LENGTH; + // At full power the stick trembles a little. + const tremble = power > 0.97 ? Math.sin(now * 90) * 0.0012 : 0; + const tipX = tip.x - dy * tremble; + const tipY = tip.y + dx * tremble; + const buttX = tipX - dx * length; + const buttY = tipY - dy * length; + const px = -dy; + const py = dx; + const tipHalf = style === "wand" ? 0.004 : 0.0065; + const buttHalf = style === "wand" ? 0.009 : 0.013; + const outline = (offset: number) => { + ctx.beginPath(); + ctx.moveTo(tipX + px * tipHalf + offset, tipY + py * tipHalf + offset * 1.4); + ctx.lineTo(buttX + px * buttHalf + offset, buttY + py * buttHalf + offset * 1.4); + ctx.lineTo(buttX - px * buttHalf + offset, buttY - py * buttHalf + offset * 1.4); + ctx.lineTo(tipX - px * tipHalf + offset, tipY - py * tipHalf + offset * 1.4); + ctx.closePath(); + }; + outline(0.012); + ctx.fillStyle = "rgba(0, 0, 0, 0.3)"; + ctx.fill(); + + const body = ctx.createLinearGradient(tipX, tipY, buttX, buttY); + for (const [stop, color] of cueStops(style, now)) body.addColorStop(stop, color); + ctx.save(); + if (style === "glow" || style === "wand") { + const scale = ctx.getTransform().a; + ctx.shadowColor = `rgba(${POWER_COLORS[style]}, 0.9)`; + ctx.shadowBlur = (0.018 + Math.sin(now * 6) * 0.006) * scale; + } else if (style === "ember") { + const scale = ctx.getTransform().a; + ctx.shadowColor = "rgba(255, 110, 30, 0.6)"; + ctx.shadowBlur = (0.01 + Math.sin(now * 2.2) * 0.004) * scale; + } + outline(0); + ctx.fillStyle = body; + ctx.fill(); + ctx.restore(); + + if (style === "wand") drawWandStar(ctx, tipX + dx * 0.006, tipY + dy * 0.006, now); +} + +function cueStops(style: CueStyle, now: number): ReadonlyArray { + switch (style) { + case "classic": + return [ + [0, "#7fb2e0"], + [0.01, "#7fb2e0"], + [0.0101, "#f3efe4"], + [0.025, "#f3efe4"], + [0.026, "#e0c69c"], + [0.62, "#b8875a"], + [0.621, "#d4af37"], + [0.63, "#d4af37"], + [0.631, "#2a1810"], + [1, "#120a06"], + ]; + case "ari": + return [ + [0, "#fff3c4"], + [0.012, "#fff3c4"], + [0.0121, "#ffc83d"], + [0.03, "#ffc83d"], + [0.031, "#8a4fc0"], + [0.4, "#5b2a86"], + [0.401, "#ffc83d"], + [0.415, "#ffc83d"], + [0.416, "#4a1f70"], + [0.6, "#3a1858"], + [0.601, "#ffc83d"], + [0.61, "#ffc83d"], + [0.611, "#2a0f42"], + [1, "#1a0829"], + ]; + case "copper": { + // Engraved rings along a warm metal shaft. + const stops: Array = [ + [0, "#7fb2e0"], + [0.01, "#7fb2e0"], + [0.0101, "#f3c6a0"], + [0.03, "#e8a476"], + ]; + for (let i = 0; i < 8; i++) { + const at = 0.08 + i * 0.11; + stops.push([at, i % 2 === 0 ? "#b87333" : "#d48a4f"], [at + 0.004, "#6b3a1c"]); + } + stops.push([1, "#5a2e14"]); + return stops; + } + case "chrome": { + // A slow reflection slides along polished steel. + const band = 0.1 + ((now * 0.25) % 1) * 0.8; + return [ + [0, "#7fb2e0"], + [0.01, "#7fb2e0"], + [0.0101, "#f4f7fa"], + [0.03, "#cfd6de"], + [Math.max(0.035, band - 0.1), "#8d97a3"], + [band, "#ffffff"], + [Math.min(0.97, band + 0.1), "#8d97a3"], + [1, "#3c434c"], + ]; + } + case "ember": { + // Charred wood with embers that breathe along it. + const stops: Array = [ + [0, "#ffd9a0"], + [0.015, "#ffd9a0"], + [0.016, "#2a0f06"], + ]; + for (let i = 1; i < 9; i++) { + const heat = 0.5 + 0.5 * Math.sin(now * 2.6 + i * 1.7); + stops.push([i / 9, `hsl(${18 + heat * 14}, 100%, ${10 + heat * 42}%)`]); + } + stops.push([1, "#120604"]); + return stops; + } + case "golden": { + // A shine runs down the stick, over and over. + const band = 0.08 + ((now * 0.45) % 1) * 0.84; + return [ + [0, "#fff6d0"], + [0.025, "#fff6d0"], + [0.026, "#c99520"], + [Math.max(0.03, band - 0.07), "#e3b23c"], + [band, "#fffbe6"], + [Math.min(0.97, band + 0.07), "#e3b23c"], + [1, "#7a5208"], + ]; + } + case "wand": + return [ + [0, "#f4ecff"], + [0.03, "#f4ecff"], + [0.031, "#3a2654"], + [0.5, "#24173a"], + [0.51, "#c9b6e8"], + [0.53, "#c9b6e8"], + [0.531, "#1a1029"], + [1, "#0c0714"], + ]; + case "glow": { + // Colour flows along the stick. + const stops: Array = []; + for (let i = 0; i <= 6; i++) { + const hue = (now * 140 + i * 50) % 360; + stops.push([i / 6, `hsl(${hue}, 95%, ${i === 0 ? 88 : 62}%)`]); + } + return stops; + } + } +} + +function drawWandStar(ctx: CanvasRenderingContext2D, x: number, y: number, now: number): void { + const spin = now * 2.4; + const size = 0.016 * (1 + Math.sin(now * 7) * 0.12); + ctx.save(); + const glow = ctx.createRadialGradient(x, y, 0, x, y, size * 2.4); + glow.addColorStop(0, `rgba(${POWER_COLORS.wand}, 0.75)`); + glow.addColorStop(1, `rgba(${POWER_COLORS.wand}, 0)`); + ctx.fillStyle = glow; + ctx.beginPath(); + ctx.arc(x, y, size * 2.4, 0, Math.PI * 2); + ctx.fill(); + ctx.fillStyle = "#fbf6ff"; + starPath(ctx, x, y, size, size * 0.38, spin); + ctx.fill(); + ctx.restore(); +} + +function starPath( + ctx: CanvasRenderingContext2D, + x: number, + y: number, + outer: number, + inner: number, + rotation: number, +): void { + ctx.beginPath(); + for (let i = 0; i < 8; i++) { + const radius = i % 2 === 0 ? outer : inner; + const angle = rotation + (i * Math.PI) / 4; + const px = x + Math.cos(angle) * radius; + const py = y + Math.sin(angle) * radius; + if (i === 0) ctx.moveTo(px, py); + else ctx.lineTo(px, py); + } + ctx.closePath(); +} + +/** The rings still waiting on the cloth, with a glyph for what each one gives. */ +export function drawRings( + ctx: CanvasRenderingContext2D, + rings: ReadonlyArray, + now: number, +): void { + for (const ring of rings) { + if (ring.collected) continue; + const color = POWER_COLORS[ring.kind]; + const pulse = 1 + Math.sin(now * 3 + ring.id) * 0.07; + const radius = RING_RADIUS * 1.25 * pulse; + ctx.save(); + const halo = ctx.createRadialGradient(ring.x, ring.y, 0, ring.x, ring.y, radius * 1.6); + halo.addColorStop(0, `rgba(${color}, 0.28)`); + halo.addColorStop(1, `rgba(${color}, 0)`); + ctx.fillStyle = halo; + ctx.beginPath(); + ctx.arc(ring.x, ring.y, radius * 1.6, 0, Math.PI * 2); + ctx.fill(); + ctx.strokeStyle = `rgba(${color}, 0.9)`; + ctx.lineWidth = 0.004; + ctx.setLineDash([0.014, 0.009]); + ctx.lineDashOffset = -now * 0.04; + ctx.beginPath(); + ctx.arc(ring.x, ring.y, radius, 0, Math.PI * 2); + ctx.stroke(); + ctx.setLineDash([]); + ctx.fillStyle = `rgb(${color})`; + ctx.strokeStyle = `rgb(${color})`; + drawGlyph(ctx, ring.kind, ring.x, ring.y, now); + ctx.restore(); + } +} + +function drawGlyph( + ctx: CanvasRenderingContext2D, + kind: PowerKind, + x: number, + y: number, + now: number, +): void { + const s = RING_RADIUS * 0.5; + switch (kind) { + case "wand": + starPath(ctx, x, y, s, s * 0.4, now); + ctx.fill(); + break; + case "golden": + ctx.lineWidth = 0.004; + ctx.beginPath(); + ctx.arc(x, y, s * 0.75, 0, Math.PI * 2); + ctx.stroke(); + ctx.beginPath(); + ctx.arc(x, y, s * 0.3, 0, Math.PI * 2); + ctx.fill(); + break; + case "glow": + ctx.beginPath(); + ctx.moveTo(x + s * 0.25, y - s); + ctx.lineTo(x - s * 0.55, y + s * 0.12); + ctx.lineTo(x - s * 0.02, y + s * 0.12); + ctx.lineTo(x - s * 0.3, y + s); + ctx.lineTo(x + s * 0.55, y - s * 0.15); + ctx.lineTo(x + s * 0.02, y - s * 0.15); + ctx.closePath(); + ctx.fill(); + break; + } +} diff --git a/apps/web/src/components/billiards/billiardsFx.ts b/apps/web/src/components/billiards/billiardsFx.ts new file mode 100644 index 0000000000..33c53f8b38 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsFx.ts @@ -0,0 +1,390 @@ +import type { Ball, PhysicsEvent } from "./billiardsPhysics.ts"; +import { EIGHT } from "./billiardsRules.ts"; +import { BALL_RADIUS, POCKETS, TABLE_LENGTH, TABLE_WIDTH } from "./billiardsTable.ts"; + +// Everything here is looks only: it never feeds back into the simulation. + +const R = BALL_RADIUS; +const MAX_PARTICLES = 240; +const GOLD = "255, 200, 80"; +const WHITE = "255, 255, 255"; +const DUST = "205, 225, 255"; + +/** + * The cloth's memory: a rolling ball brushes the nap into a light trail that stays for the game. + * A ball crossing an older trail brushes it back flat, so crossings return to plain cloth. Each + * shot paints into its own layer, which is XORed onto the settled marks when the shot ends, so + * a ball never erases the trail it is drawing right now. + */ +export class ClothNap { + private readonly settled = document.createElement("canvas"); + private readonly shot = document.createElement("canvas"); + private readonly view = document.createElement("canvas"); + private scale = 1; + private originX = 0; + private originY = 0; + private shotMarked = false; + private viewStale = true; + + resize(width: number, height: number, scale: number, originX: number, originY: number): void { + for (const canvas of [this.settled, this.shot, this.view]) { + canvas.width = width; + canvas.height = height; + } + this.scale = scale; + this.originX = originX; + this.originY = originY; + this.shotMarked = false; + this.viewStale = true; + } + + clear(): void { + for (const canvas of [this.settled, this.shot, this.view]) { + canvas.getContext("2d")?.clearRect(0, 0, canvas.width, canvas.height); + } + this.shotMarked = false; + this.viewStale = true; + } + + /** Brushes the nap along a ball's path this frame. */ + stamp(x0: number, y0: number, x1: number, y1: number): void { + const ctx = this.shot.getContext("2d"); + if (!ctx) return; + ctx.setTransform(this.scale, 0, 0, this.scale, this.originX, this.originY); + ctx.strokeStyle = "#fff"; + ctx.lineWidth = R * 1.6; + ctx.lineCap = "round"; + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(x1, y1); + ctx.stroke(); + this.shotMarked = true; + this.viewStale = true; + } + + /** The shot ended: its trail joins the cloth, flattening the older trails it crossed. */ + commit(): void { + if (!this.shotMarked) return; + const ctx = this.settled.getContext("2d"); + if (ctx) { + ctx.globalCompositeOperation = "xor"; + ctx.drawImage(this.shot, 0, 0); + ctx.globalCompositeOperation = "source-over"; + } + this.shot.getContext("2d")?.clearRect(0, 0, this.shot.width, this.shot.height); + this.shotMarked = false; + this.viewStale = true; + } + + /** Lays the nap over the cloth, never over the pockets or rails. Expects the table transform. */ + draw(ctx: CanvasRenderingContext2D, shiftX: number, shiftY: number): void { + if (this.viewStale) { + const view = this.view.getContext("2d"); + if (view) { + view.clearRect(0, 0, this.view.width, this.view.height); + view.drawImage(this.settled, 0, 0); + if (this.shotMarked) { + view.globalCompositeOperation = "xor"; + view.drawImage(this.shot, 0, 0); + view.globalCompositeOperation = "source-over"; + } + } + this.viewStale = false; + } + ctx.save(); + ctx.beginPath(); + ctx.rect(0, 0, TABLE_WIDTH, TABLE_LENGTH); + for (const pocket of POCKETS) { + ctx.moveTo(pocket.x + pocket.radius, pocket.y); + ctx.arc(pocket.x, pocket.y, pocket.radius, 0, Math.PI * 2); + } + ctx.clip("evenodd"); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalAlpha = 0.13; + ctx.filter = `blur(${Math.max(1, R * 0.2 * this.scale)}px)`; + ctx.drawImage(this.view, shiftX, shiftY); + ctx.restore(); + } +} + +interface Particle { + x: number; + y: number; + vx: number; + vy: number; + age: number; + readonly life: number; + readonly size: number; + readonly color: string; + readonly drag: number; +} + +interface Ring { + readonly x: number; + readonly y: number; + age: number; + readonly life: number; + readonly from: number; + readonly to: number; + readonly width: number; + readonly color: string; + readonly alpha: number; +} + +export class Effects { + private particles: Particle[] = []; + private rings: Ring[] = []; + private shakeTime = 0; + private shakePower = 0; + /** A shot gets one hit-stop at most, on its first hard contact. */ + private impactShown = false; + /** Seconds the whole scene stays frozen, for the weight of a hard hit. */ + hitStop = 0; + + reset(): void { + this.particles = []; + this.rings = []; + this.shakeTime = 0; + this.hitStop = 0; + } + + cueStrike(cue: Ball, angle: number, power: number): void { + this.impactShown = false; + this.ring(cue.x, cue.y, R, R * (2 + power * 2), 0.18, 0.004, WHITE, 0.35 + power * 0.4); + const count = Math.round(3 + power * 6); + for (let i = 0; i < count; i++) { + // Chalk puffs back off the tip. + const spread = angle + Math.PI + (Math.random() - 0.5) * 1.2; + const speed = 0.08 + Math.random() * 0.25 * (0.4 + power); + this.particle( + cue.x - Math.cos(angle) * R, + cue.y - Math.sin(angle) * R, + Math.cos(spread) * speed, + Math.sin(spread) * speed, + 0.35 + Math.random() * 0.25, + 0.003 + Math.random() * 0.003, + "127, 178, 224", + 5, + ); + } + } + + /** Turns this frame's contacts into effects. `breakShot` says whether the rack is breaking. */ + onEvents( + events: ReadonlyArray, + balls: ReadonlyArray, + breakShot: boolean, + ): void { + let hardest = 0; + for (const event of events) { + if (event.kind === "ball") { + hardest = Math.max(hardest, event.speed); + if (event.speed < 0.5) continue; + const a = balls.find((ball) => ball.id === event.a); + const b = balls.find((ball) => ball.id === event.b); + if (!a || !b) continue; + const x = (a.x + b.x) / 2; + const y = (a.y + b.y) / 2; + const v = Math.min(1, event.speed / 5); + this.ring(x, y, R * 0.3, R * (1 + v * 1.6), 0.16, 0.003, WHITE, 0.25 + v * 0.45); + if (event.speed > 2.5) this.burst(x, y, Math.round(2 + v * 6), 0.4 * v, WHITE, 0.25); + } else if (event.kind === "cushion") { + if (event.speed < 0.4) continue; + const v = Math.min(1, event.speed / 4); + this.burst(event.x, event.y, Math.round(3 + v * 7), 0.12 + 0.22 * v, DUST, 0.5); + this.ring( + event.x, + event.y, + R * 0.4, + R * (1.2 + v * 1.5), + 0.25, + 0.0025, + DUST, + 0.15 + v * 0.3, + ); + } else if (event.kind === "pocket") { + const pocket = POCKETS[event.pocket]; + if (!pocket) continue; + const gold = event.ball === EIGHT; + const color = gold ? GOLD : event.ball === 0 ? "255, 110, 90" : WHITE; + this.ring( + pocket.x, + pocket.y, + pocket.radius * 0.8, + pocket.radius * 2.4, + 0.5, + 0.006, + color, + 0.8, + ); + this.ring(pocket.x, pocket.y, pocket.radius, pocket.radius * 1.6, 0.3, 0.003, color, 0.5); + for (let i = 0; i < 14; i++) { + // Sparks drawn into the pocket. + const angle = (i / 14) * Math.PI * 2 + Math.random() * 0.3; + const distance = pocket.radius * (1.6 + Math.random()); + const speed = distance / 0.35; + this.particle( + pocket.x + Math.cos(angle) * distance, + pocket.y + Math.sin(angle) * distance, + -Math.cos(angle) * speed, + -Math.sin(angle) * speed, + 0.32, + 0.0035, + color, + 0, + ); + } + } + } + if (this.impactShown) return; + if (breakShot && hardest > 3) { + this.impactShown = true; + this.hitStop = 0.05; + this.shake(0.006, 0.3); + } else if (hardest > 5.5) { + this.impactShown = true; + this.hitStop = 0.03; + } + } + + /** A power-up collected, or a ball taken by one: a burst in its colour. */ + powerBurst(x: number, y: number, color: string): void { + this.ring(x, y, R, R * 5, 0.55, 0.006, color, 0.9); + this.ring(x, y, R * 0.5, R * 3, 0.35, 0.003, WHITE, 0.6); + this.burst(x, y, 22, 0.55, color, 0.6); + } + + /** One spark left behind something magic as it moves. */ + trail(x: number, y: number, color: string): void { + const angle = Math.random() * Math.PI * 2; + this.particle( + x + Math.cos(angle) * R * 0.6, + y + Math.sin(angle) * R * 0.6, + Math.cos(angle) * 0.03, + Math.sin(angle) * 0.03, + 0.45 + Math.random() * 0.3, + 0.0025 + Math.random() * 0.0025, + color, + 2, + ); + } + + /** The table cleared: a wide gold wave from the called pocket. */ + celebrate(pocketId: number | null): void { + const pocket = POCKETS.find((candidate) => candidate.id === pocketId) ?? POCKETS[0]; + if (!pocket) return; + for (const [delay, width] of [ + [0, 0.012], + [0.12, 0.007], + [0.24, 0.004], + ] as const) { + this.rings.push({ + x: pocket.x, + y: pocket.y, + age: -delay, + life: 1.3, + from: pocket.radius, + to: 2.4, + width, + color: GOLD, + alpha: 0.7, + }); + } + this.shake(0.004, 0.25); + } + + private shake(power: number, time: number): void { + this.shakePower = Math.max(this.shakePower * (this.shakeTime > 0 ? 1 : 0), power); + this.shakeTime = Math.max(this.shakeTime, time); + } + + /** How far the frame is thrown this instant, in table units. */ + shakeOffset(): { readonly x: number; readonly y: number } { + if (this.shakeTime <= 0) return { x: 0, y: 0 }; + const power = this.shakePower * Math.min(1, this.shakeTime / 0.3); + return { x: (Math.random() - 0.5) * 2 * power, y: (Math.random() - 0.5) * 2 * power }; + } + + update(seconds: number): void { + this.shakeTime = Math.max(0, this.shakeTime - seconds); + for (const particle of this.particles) { + particle.age += seconds; + const drag = Math.exp(-particle.drag * seconds); + particle.vx *= drag; + particle.vy *= drag; + particle.x += particle.vx * seconds; + particle.y += particle.vy * seconds; + } + this.particles = this.particles.filter((particle) => particle.age < particle.life); + for (const ring of this.rings) ring.age += seconds; + this.rings = this.rings.filter((ring) => ring.age < ring.life); + } + + /** Draws rings and particles. Expects the table transform. */ + draw(ctx: CanvasRenderingContext2D): void { + ctx.save(); + ctx.globalCompositeOperation = "lighter"; + for (const ring of this.rings) { + if (ring.age < 0) continue; + const t = ring.age / ring.life; + const ease = 1 - (1 - t) * (1 - t); + ctx.strokeStyle = `rgba(${ring.color}, ${ring.alpha * (1 - t)})`; + ctx.lineWidth = ring.width * (1 - t * 0.6); + ctx.beginPath(); + ctx.arc(ring.x, ring.y, ring.from + (ring.to - ring.from) * ease, 0, Math.PI * 2); + ctx.stroke(); + } + for (const particle of this.particles) { + const t = particle.age / particle.life; + ctx.fillStyle = `rgba(${particle.color}, ${0.85 * (1 - t)})`; + ctx.beginPath(); + ctx.arc(particle.x, particle.y, particle.size * (1 - t * 0.5), 0, Math.PI * 2); + ctx.fill(); + } + ctx.restore(); + } + + private burst(x: number, y: number, count: number, speed: number, color: string, life: number) { + for (let i = 0; i < count; i++) { + const angle = Math.random() * Math.PI * 2; + const v = speed * (0.4 + Math.random() * 0.6); + this.particle( + x, + y, + Math.cos(angle) * v, + Math.sin(angle) * v, + life * (0.6 + Math.random() * 0.4), + 0.0025 + Math.random() * 0.003, + color, + 4, + ); + } + } + + private particle( + x: number, + y: number, + vx: number, + vy: number, + life: number, + size: number, + color: string, + drag: number, + ): void { + if (this.particles.length >= MAX_PARTICLES) this.particles.shift(); + this.particles.push({ x, y, vx, vy, age: 0, life, size, color, drag }); + } + + private ring( + x: number, + y: number, + from: number, + to: number, + life: number, + width: number, + color: string, + alpha: number, + ): void { + this.rings.push({ x, y, age: 0, life, from, to, width, color, alpha }); + } +} diff --git a/apps/web/src/components/billiards/billiardsHud.ts b/apps/web/src/components/billiards/billiardsHud.ts new file mode 100644 index 0000000000..40103aaebf --- /dev/null +++ b/apps/web/src/components/billiards/billiardsHud.ts @@ -0,0 +1,323 @@ +import { RAIL_WIDTH, TABLE_LENGTH, TABLE_WIDTH } from "./billiardsTable.ts"; + +// The scoreboard lives in the scene: a brass plate on the top rail for the clock, chalk tallies +// for shots, and callouts that pop up where something happened. Words come in translated. + +export interface BilliardsLabels { + readonly scratch: string; + readonly miss: string; + readonly freeMiss: string; + readonly early8: string; + readonly wrong8: string; + readonly scratch8: string; + readonly wand: string; + readonly golden: string; + readonly glow: string; + readonly wandHint: string; + readonly goldenHint: string; + readonly glowHint: string; + readonly callPocket: string; + readonly callFirst: string; + readonly breakHint: string; + readonly controlsHint: string; + readonly penalty: (seconds: number) => string; +} + +export interface ScoreView { + readonly totalMs: number; + readonly penaltySeconds: number; + readonly shots: number; + readonly bestMs: number | null; + readonly goldenShots: number; + readonly isBreak: boolean; + /** Only the 8 is left and no pocket is called yet. */ + readonly callNeeded: boolean; +} + +const BRASS = "#c9a24a"; +const PLATE_WIDTH = 0.44; +const PLATE_HEIGHT = 0.14; +const PLATE_Y = -RAIL_WIDTH - 0.02 - PLATE_HEIGHT; +const CHALK = "236, 233, 222"; +const ROUNDED = `ui-rounded, "SF Pro Rounded", ui-sans-serif, system-ui, sans-serif`; +const MONO = "ui-monospace, SFMono-Regular, Menlo, monospace"; + +export function formatClock(ms: number, tenths = false): string { + const seconds = Math.floor(Math.max(0, ms) / 1000); + const clock = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; + return tenths ? `${clock}.${Math.floor((Math.max(0, ms) % 1000) / 100)}` : clock; +} + +interface TextStyle { + readonly weight?: number; + readonly family?: string; + readonly fill: string; + readonly stroke?: string; + /** Outline width, in table units. */ + readonly strokeWidth?: number; + readonly align?: CanvasTextAlign; + /** In table units. */ + readonly maxWidth?: number; +} + +/** + * Text at (x, y) in table units, `size` tall, drawn at real pixel size: canvas fonts smaller than a + * pixel, scaled up by the table transform, come out soft and blocky. + */ +function drawText( + ctx: CanvasRenderingContext2D, + text: string, + x: number, + y: number, + size: number, + style: TextStyle, +): void { + const matrix = ctx.getTransform(); + const at = matrix.transformPoint({ x, y }); + const scale = matrix.a; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.font = `${style.weight ?? 700} ${size * scale}px ${style.family ?? ROUNDED}`; + ctx.textAlign = style.align ?? "center"; + ctx.textBaseline = "middle"; + const maxWidth = style.maxWidth === undefined ? undefined : style.maxWidth * scale; + if (style.stroke) { + ctx.lineJoin = "round"; + ctx.lineWidth = (style.strokeWidth ?? 0.008) * scale; + ctx.strokeStyle = style.stroke; + ctx.strokeText(text, at.x, at.y, maxWidth); + } + ctx.fillStyle = style.fill; + ctx.fillText(text, at.x, at.y, maxWidth); + ctx.restore(); +} + +function brassPlate(ctx: CanvasRenderingContext2D, x: number, width: number): void { + const plate = ctx.createLinearGradient(0, PLATE_Y, 0, PLATE_Y + PLATE_HEIGHT); + plate.addColorStop(0, "#f4dc95"); + plate.addColorStop(0.45, BRASS); + plate.addColorStop(1, "#76561a"); + const scale = ctx.getTransform().a; + ctx.save(); + ctx.shadowColor = "rgba(0, 0, 0, 0.6)"; + ctx.shadowBlur = 0.03 * scale; + ctx.shadowOffsetY = 0.01 * scale; + ctx.fillStyle = plate; + ctx.beginPath(); + ctx.roundRect(x, PLATE_Y, width, PLATE_HEIGHT, 0.018); + ctx.fill(); + ctx.restore(); + // Bevel and two screws. + ctx.strokeStyle = "rgba(255, 244, 205, 0.6)"; + ctx.lineWidth = 0.003; + ctx.beginPath(); + ctx.roundRect(x + 0.006, PLATE_Y + 0.006, width - 0.012, PLATE_HEIGHT - 0.012, 0.013); + ctx.stroke(); + for (const sx of [x + 0.024, x + width - 0.024]) { + const sy = PLATE_Y + PLATE_HEIGHT / 2; + ctx.fillStyle = "#6b4d17"; + ctx.beginPath(); + ctx.arc(sx, sy, 0.008, 0, Math.PI * 2); + ctx.fill(); + ctx.strokeStyle = "rgba(255, 240, 200, 0.65)"; + ctx.lineWidth = 0.002; + ctx.beginPath(); + ctx.moveTo(sx - 0.0055, sy - 0.002); + ctx.lineTo(sx + 0.0055, sy + 0.002); + ctx.stroke(); + } +} + +/** Text cut into brass: dark letters over a light edge. */ +function engrave( + ctx: CanvasRenderingContext2D, + text: string, + x: number, + y: number, + size: number, + color = "#3a2808", +): void { + drawText(ctx, text, x, y + size * 0.05, size, { family: MONO, fill: "rgba(255, 246, 214, 0.6)" }); + drawText(ctx, text, x, y, size, { family: MONO, fill: color }); +} + +/** A chalk stroke: soft, a little rough. */ +function chalkLine( + ctx: CanvasRenderingContext2D, + x0: number, + y0: number, + x1: number, + y1: number, +): void { + ctx.strokeStyle = `rgba(${CHALK}, 0.3)`; + ctx.lineWidth = 0.011; + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(x1, y1); + ctx.stroke(); + ctx.strokeStyle = `rgba(${CHALK}, 0.9)`; + ctx.lineWidth = 0.0055; + ctx.stroke(); +} + +const MAX_TALLIES = 20; + +/** Shots as chalk tallies, in fives, in the dark left of the scoreboard. */ +function drawTallies(ctx: CanvasRenderingContext2D, shots: number): void { + ctx.save(); + ctx.lineCap = "round"; + const height = 0.075; + const top = PLATE_Y + (PLATE_HEIGHT - height) / 2; + const left = -0.15; + const groupWidth = 0.1; + for (let i = 0; i < Math.min(shots, MAX_TALLIES); i++) { + const group = Math.floor(i / 5); + const within = i % 5; + const gx = left + group * groupWidth; + // A fixed wobble per mark, so the tally doesn't jitter. + const wobble = Math.sin(i * 12.9898) * 0.005; + if (within < 4) { + const x = gx + within * 0.018; + chalkLine(ctx, x + wobble, top, x - wobble, top + height); + } else { + chalkLine(ctx, gx - 0.008, top + height * 0.82, gx + 0.064, top + height * 0.18); + } + } + ctx.restore(); + if (shots > MAX_TALLIES) { + drawText(ctx, `+${shots - MAX_TALLIES}`, left, top + height + 0.03, 0.032, { + fill: `rgba(${CHALK}, 0.85)`, + align: "left", + }); + } +} + +function drawTrophy(ctx: CanvasRenderingContext2D, x: number, y: number, size: number): void { + ctx.beginPath(); + ctx.moveTo(x - size, y - size); + ctx.lineTo(x + size, y - size); + ctx.quadraticCurveTo(x + size, y + size * 0.3, x, y + size * 0.4); + ctx.quadraticCurveTo(x - size, y + size * 0.3, x - size, y - size); + ctx.fill(); + ctx.fillRect(x - size * 0.15, y + size * 0.35, size * 0.3, size * 0.5); + ctx.fillRect(x - size * 0.55, y + size * 0.8, size * 1.1, size * 0.25); +} + +/** The brass scoreboard (clock, penalties, today's best) and the shot tallies. Table transform. */ +export function drawScoreboard(ctx: CanvasRenderingContext2D, view: ScoreView): void { + const x = (TABLE_WIDTH - PLATE_WIDTH) / 2; + brassPlate(ctx, x, PLATE_WIDTH); + const penalty = view.penaltySeconds > 0; + const clockY = PLATE_Y + PLATE_HEIGHT * (view.bestMs === null ? 0.52 : 0.4); + engrave(ctx, formatClock(view.totalMs), penalty ? 0.47 : 0.5, clockY, 0.085); + if (penalty) engrave(ctx, `+${view.penaltySeconds}`, 0.655, clockY + 0.004, 0.036, "#8a1c10"); + if (view.bestMs !== null) { + const bestY = PLATE_Y + PLATE_HEIGHT * 0.79; + ctx.fillStyle = "#4a340c"; + drawTrophy(ctx, 0.425, bestY - 0.003, 0.0105); + engrave(ctx, formatClock(view.bestMs, true), 0.52, bestY, 0.032, "#4a340c"); + } + drawTallies(ctx, view.shots); + + // The golden cue's shots left, as gold pips under the plate. + for (let i = 0; i < view.goldenShots; i++) { + ctx.fillStyle = "#ffd36a"; + ctx.beginPath(); + ctx.arc( + 0.5 + (i - (view.goldenShots - 1) / 2) * 0.035, + PLATE_Y + PLATE_HEIGHT + 0.012, + 0.008, + 0, + Math.PI * 2, + ); + ctx.fill(); + } +} + +/** Instructions written in chalk on the cloth: how to shoot, or that the 8 needs a pocket. */ +export function drawChalkHints( + ctx: CanvasRenderingContext2D, + view: ScoreView, + labels: BilliardsLabels, + now: number, +): void { + const lines = view.isBreak + ? [labels.breakHint, labels.controlsHint] + : view.callNeeded + ? [labels.callPocket] + : []; + const pulse = view.callNeeded ? 0.65 + 0.35 * Math.sin(now * 3) : 0.8; + for (const [i, line] of lines.entries()) { + const size = i === 0 ? 0.046 : 0.032; + const y = (view.isBreak ? 1.7 : TABLE_LENGTH / 2) + i * 0.065; + drawText(ctx, line, 0.5, y, size, { + weight: 600, + fill: `rgba(${CHALK}, ${(i === 0 ? 0.8 : 0.55) * pulse})`, + stroke: "rgba(0, 0, 0, 0.25)", + strokeWidth: 0.006, + maxWidth: 0.92, + }); + } +} + +interface Callout { + readonly text: string; + readonly detail: string | null; + readonly x: number; + readonly y: number; + readonly color: string; + age: number; + readonly life: number; +} + +/** Words that pop up where something happened, rise a little and fade. */ +export class Callouts { + private items: Callout[] = []; + + add(text: string, x: number, y: number, color: string, detail: string | null = null): void { + // Keep it on the table, clear of the rails. + const cx = Math.max(0.22, Math.min(TABLE_WIDTH - 0.22, x)); + const cy = Math.max(0.1, Math.min(TABLE_LENGTH - 0.16, y)); + this.items.push({ text, detail, x: cx, y: cy, color, age: 0, life: detail ? 2.6 : 1.8 }); + } + + reset(): void { + this.items = []; + } + + update(seconds: number): void { + for (const item of this.items) item.age += seconds; + this.items = this.items.filter((item) => item.age < item.life); + } + + draw(ctx: CanvasRenderingContext2D): void { + for (const item of this.items) { + const t = item.age / item.life; + const pop = + item.age < 0.18 + ? 0.6 + (item.age / 0.18) * 0.55 + : Math.max(1, 1.15 - (item.age - 0.18) * 1.5); + const alpha = t > 0.75 ? (1 - t) / 0.25 : 1; + const y = item.y - 0.07 * Math.min(1, item.age / 0.6); + ctx.save(); + ctx.globalAlpha = alpha; + drawText(ctx, item.text, item.x, y, 0.062 * pop, { + weight: 800, + fill: item.color, + stroke: "rgba(8, 10, 14, 0.88)", + strokeWidth: 0.012 * pop, + maxWidth: 0.95, + }); + if (item.detail) { + drawText(ctx, item.detail, item.x, y + 0.06, 0.034, { + weight: 650, + fill: "rgba(255, 255, 255, 0.95)", + stroke: "rgba(8, 10, 14, 0.85)", + strokeWidth: 0.008, + maxWidth: 0.95, + }); + } + ctx.restore(); + } + } +} diff --git a/apps/web/src/components/billiards/billiardsPhysics.ts b/apps/web/src/components/billiards/billiardsPhysics.ts new file mode 100644 index 0000000000..b0ac4921b8 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsPhysics.ts @@ -0,0 +1,215 @@ +import { + BALL_RADIUS, + CUSHION_SEGMENTS, + POCKETS, + TABLE_LENGTH, + TABLE_WIDTH, + type Pocket, +} from "./billiardsTable.ts"; + +export interface Ball { + /** 0 is the cue ball, 1 to 15 the object balls. */ + readonly id: number; + x: number; + y: number; + vx: number; + vy: number; + onTable: boolean; + /** A power-up steers this ball into this pocket, through everything in the way. */ + guidedTo: number | null; +} + +export type PhysicsEvent = + | { readonly kind: "ball"; readonly a: number; readonly b: number; readonly speed: number } + | { + readonly kind: "cushion"; + readonly ball: number; + readonly speed: number; + readonly x: number; + readonly y: number; + } + /** The cue ball passed through this ball, with the glow cue. */ + | { readonly kind: "touch"; readonly ball: number } + /** The cue ball rolled over a power-up ring. Raised by the game, not the physics. */ + | { readonly kind: "powerUp"; readonly ring: number } + /** A power-up took hold of this ball and steers it into a pocket. Raised by the game. */ + | { readonly kind: "guide"; readonly ball: number } + | { + readonly kind: "pocket"; + readonly ball: number; + readonly pocket: number; + readonly x: number; + readonly y: number; + }; + +/** One fixed simulation step. Small enough that a break-speed ball can't pass through another. */ +export const STEP_SECONDS = 1 / 480; +/** The fastest shot, in table widths per second. */ +const MAX_SHOT_SPEED = 8; +const MIN_SHOT_SPEED = 0.3; + +/** Cue ball speed for a shot charged to `power` (0 to 1); low power gets the finer control. */ +export function shotSpeed(power: number): number { + return MIN_SHOT_SPEED + (MAX_SHOT_SPEED - MIN_SHOT_SPEED) * power * power; +} + +export const ROLL_DECEL = 0.5; +export const DRAG = 0.12; +const SLEEP_SPEED = 0.012; +const BALL_RESTITUTION = 0.94; +export const CUSHION_RESTITUTION = 0.72; +export const CUSHION_GRIP = 0.94; +const DIAMETER = BALL_RADIUS * 2; +const OUT_MARGIN = BALL_RADIUS * 1.2; +/** A guided ball never rolls slower than this on its way to the pocket. */ +const GUIDED_SPEED = 1.6; + +export interface StepOptions { + /** The cue ball passes through other balls instead of hitting them. */ + readonly cueGhost?: boolean; +} + +export function makeBall(id: number, x: number, y: number): Ball { + return { id, x, y, vx: 0, vy: 0, onTable: true, guidedTo: null }; +} + +export function anyMoving(balls: ReadonlyArray): boolean { + return balls.some((ball) => ball.onTable && (ball.vx !== 0 || ball.vy !== 0)); +} + +function nearestPocket(x: number, y: number): Pocket { + let best = POCKETS[0] as Pocket; + let bestDistance = Infinity; + for (const pocket of POCKETS) { + const distance = Math.hypot(pocket.x - x, pocket.y - y); + if (distance < bestDistance) { + best = pocket; + bestDistance = distance; + } + } + return best; +} + +/** Advances every ball by one fixed step, appending what happened to `events`. Deterministic. */ +export function stepPhysics( + balls: Ball[], + events: PhysicsEvent[], + options: StepOptions = {}, +): void { + const dt = STEP_SECONDS; + + for (const ball of balls) { + if (!ball.onTable) continue; + if (ball.guidedTo !== null) { + const pocket = POCKETS[ball.guidedTo]; + if (pocket) { + const dx = pocket.x - ball.x; + const dy = pocket.y - ball.y; + const distance = Math.hypot(dx, dy) || 1; + const speed = Math.max(GUIDED_SPEED, Math.hypot(ball.vx, ball.vy)); + // Turn smoothly towards the pocket rather than snapping. + const turn = Math.min(1, dt * 14); + ball.vx += ((dx / distance) * speed - ball.vx) * turn; + ball.vy += ((dy / distance) * speed - ball.vy) * turn; + ball.x += ball.vx * dt; + ball.y += ball.vy * dt; + continue; + } + } + if (ball.vx === 0 && ball.vy === 0) continue; + const speed = Math.hypot(ball.vx, ball.vy); + const loss = (ROLL_DECEL + DRAG * speed) * dt; + if (speed - loss < SLEEP_SPEED) { + ball.vx = 0; + ball.vy = 0; + continue; + } + const scale = (speed - loss) / speed; + ball.vx *= scale; + ball.vy *= scale; + ball.x += ball.vx * dt; + ball.y += ball.vy * dt; + } + + for (let i = 0; i < balls.length; i++) { + const a = balls[i]; + if (!a?.onTable) continue; + for (let j = i + 1; j < balls.length; j++) { + const b = balls[j]; + if (!b?.onTable) continue; + if (a.guidedTo !== null || b.guidedTo !== null) continue; + const dx = b.x - a.x; + const dy = b.y - a.y; + const distanceSquared = dx * dx + dy * dy; + if (distanceSquared >= DIAMETER * DIAMETER || distanceSquared === 0) continue; + if (options.cueGhost && (a.id === 0 || b.id === 0)) { + events.push({ kind: "touch", ball: a.id === 0 ? b.id : a.id }); + continue; + } + const distance = Math.sqrt(distanceSquared); + const nx = dx / distance; + const ny = dy / distance; + const push = (DIAMETER - distance) / 2; + a.x -= nx * push; + a.y -= ny * push; + b.x += nx * push; + b.y += ny * push; + const approach = (a.vx - b.vx) * nx + (a.vy - b.vy) * ny; + if (approach <= 0) continue; + const impulse = ((1 + BALL_RESTITUTION) / 2) * approach; + a.vx -= impulse * nx; + a.vy -= impulse * ny; + b.vx += impulse * nx; + b.vy += impulse * ny; + events.push({ kind: "ball", a: a.id, b: b.id, speed: approach }); + } + } + + for (const ball of balls) { + if (!ball.onTable || ball.guidedTo !== null) continue; + for (const { a, b } of CUSHION_SEGMENTS) { + const sx = b.x - a.x; + const sy = b.y - a.y; + const t = Math.max( + 0, + Math.min(1, ((ball.x - a.x) * sx + (ball.y - a.y) * sy) / (sx * sx + sy * sy)), + ); + const cx = a.x + sx * t; + const cy = a.y + sy * t; + const dx = ball.x - cx; + const dy = ball.y - cy; + const distanceSquared = dx * dx + dy * dy; + if (distanceSquared >= BALL_RADIUS * BALL_RADIUS || distanceSquared === 0) continue; + const distance = Math.sqrt(distanceSquared); + const nx = dx / distance; + const ny = dy / distance; + ball.x += nx * (BALL_RADIUS - distance); + ball.y += ny * (BALL_RADIUS - distance); + const normalSpeed = ball.vx * nx + ball.vy * ny; + if (normalSpeed >= 0) continue; + const tx = ball.vx - normalSpeed * nx; + const ty = ball.vy - normalSpeed * ny; + ball.vx = tx * CUSHION_GRIP - normalSpeed * CUSHION_RESTITUTION * nx; + ball.vy = ty * CUSHION_GRIP - normalSpeed * CUSHION_RESTITUTION * ny; + events.push({ kind: "cushion", ball: ball.id, speed: -normalSpeed, x: cx, y: cy }); + } + } + + for (const ball of balls) { + if (!ball.onTable) continue; + const pocket = nearestPocket(ball.x, ball.y); + const inPocket = Math.hypot(pocket.x - ball.x, pocket.y - ball.y) < pocket.radius; + // Cushions close every gap but the pocket mouths, so a ball off the cloth went into one. + const offCloth = + ball.x < -OUT_MARGIN || + ball.x > TABLE_WIDTH + OUT_MARGIN || + ball.y < -OUT_MARGIN || + ball.y > TABLE_LENGTH + OUT_MARGIN; + if (!inPocket && !offCloth) continue; + events.push({ kind: "pocket", ball: ball.id, pocket: pocket.id, x: ball.x, y: ball.y }); + ball.onTable = false; + ball.vx = 0; + ball.vy = 0; + ball.guidedTo = null; + } +} diff --git a/apps/web/src/components/billiards/billiardsPowerUps.test.ts b/apps/web/src/components/billiards/billiardsPowerUps.test.ts new file mode 100644 index 0000000000..fcafb87e41 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsPowerUps.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { makeBall, type Ball, type PhysicsEvent } from "./billiardsPhysics.ts"; +import { + BilliardsGame, + EIGHT, + GOLDEN_SHOTS, + placeRings, + seededRandom, + type PowerKind, + type PowerRing, +} from "./billiardsRules.ts"; + +function settle(game: BilliardsGame): PhysicsEvent[] { + const events: PhysicsEvent[] = []; + for (let frame = 0; frame < 60 * 60 && game.phase === "rolling"; frame++) { + game.advance(1 / 60, events); + } + return events; +} + +const ring = (kind: PowerKind, x: number, y: number): PowerRing => ({ + id: 0, + kind, + x, + y, + collected: false, +}); + +function gameWith(balls: Ball[], rings: PowerRing[] = []): BilliardsGame { + return new BilliardsGame({ skipBreak: true, balls, rings }); +} + +const UP = -Math.PI / 2; + +describe("power-up rings", () => { + it("places the same rings for the same seed", () => { + expect(placeRings(seededRandom(9))).toEqual(placeRings(seededRandom(9))); + }); + + it("arms the next shot when the cue ball rolls over a ring", () => { + const game = gameWith([makeBall(0, 0.5, 1.6), makeBall(3, 0.9, 0.2)], [ring("wand", 0.5, 1.3)]); + game.shoot(UP, 1.2); + const events = settle(game); + expect(events.some((event) => event.kind === "powerUp")).toBe(true); + expect(game.armed).toBe("wand"); + expect(game.rings[0]?.collected).toBe(true); + }); + + it("gives the golden cue a few shots of full sight", () => { + const game = gameWith( + [makeBall(0, 0.5, 1.6), makeBall(3, 0.9, 0.2)], + [ring("golden", 0.5, 1.3)], + ); + game.shoot(UP, 1.2); + settle(game); + expect(game.goldenShots).toBe(GOLDEN_SHOTS); + game.shoot(Math.PI / 2, 0.3); + expect(game.goldenShots).toBe(GOLDEN_SHOTS - 1); + }); +}); + +describe("power-up shots", () => { + it("wand: the first ball hit drops even on a thin, slow hit", () => { + const game = gameWith([ + makeBall(0, 0.5, 1.4), + makeBall(3, 0.52, 1.0), + makeBall(EIGHT, 0.2, 1.8), + ]); + game.armed = "wand"; + game.shoot(UP, 0.9); + settle(game); + expect(game.lastShot?.potted).toEqual([3]); + expect(game.ball(0)?.onTable).toBe(true); + }); + + it("wand: won't drop the 8 while other balls are left", () => { + const game = gameWith([ + makeBall(0, 0.5, 1.4), + makeBall(EIGHT, 0.5, 1.0), + makeBall(3, 0.9, 0.2), + ]); + game.armed = "wand"; + game.shoot(UP, 0.9); + settle(game); + expect(game.ball(EIGHT)?.onTable).toBe(true); + }); + + it("glow: the cue ball bursts through up to three balls and drops them", () => { + const game = gameWith([ + makeBall(0, 0.5, 1.7), + makeBall(3, 0.5, 1.4), + makeBall(4, 0.5, 1.2), + makeBall(5, 0.5, 1.0), + makeBall(6, 0.5, 0.8), + makeBall(EIGHT, 0.1, 1.9), + ]); + game.armed = "glow"; + game.shoot(UP, 2.5); + settle(game); + expect([...(game.lastShot?.potted ?? [])].sort()).toEqual([3, 4, 5]); + expect(game.ball(6)?.onTable).toBe(true); + expect(game.lastShot?.foul).toBeNull(); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsRecords.test.ts b/apps/web/src/components/billiards/billiardsRecords.test.ts new file mode 100644 index 0000000000..f8448c797d --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRecords.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + medalFor, + nextMedal, + rackDay, + rackSeed, + runsOn, + type BilliardsRun, +} from "./billiardsRecords.ts"; + +const run = (day: string, totalMs: number): BilliardsRun => ({ + day, + totalMs, + penaltySeconds: 0, + shots: 20, + finishedAt: `${day}T12:00:00.000Z`, +}); + +describe("daily rack", () => { + it("switches racks at midnight in Zürich, not UTC", () => { + expect(rackDay(new Date("2026-11-26T22:30:00Z"))).toBe("2026-11-26"); + expect(rackDay(new Date("2026-11-26T23:30:00Z"))).toBe("2026-11-27"); + }); + + it("gives each day its own stable seed", () => { + expect(rackSeed("2026-11-26")).toBe(rackSeed("2026-11-26")); + expect(rackSeed("2026-11-26")).not.toBe(rackSeed("2026-11-27")); + }); +}); + +describe("medals", () => { + it("awards the best medal a time is under", () => { + expect(medalFor(140_000)).toBe("gold"); + expect(medalFor(200_000)).toBe("silver"); + expect(medalFor(299_000)).toBe("bronze"); + expect(medalFor(301_000)).toBeNull(); + }); + + it("names the next medal to chase", () => { + expect(nextMedal(400_000)?.[0]).toBe("bronze"); + expect(nextMedal(250_000)?.[0]).toBe("silver"); + expect(nextMedal(140_000)).toBeNull(); + }); +}); + +describe("runsOn", () => { + it("lists one day's runs, fastest first", () => { + const runs = [ + run("2026-11-26", 200_000), + run("2026-11-25", 100_000), + run("2026-11-26", 150_000), + ]; + expect(runsOn(runs, "2026-11-26").map((r) => r.totalMs)).toEqual([150_000, 200_000]); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsRecords.ts b/apps/web/src/components/billiards/billiardsRecords.ts new file mode 100644 index 0000000000..8615e84cc5 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRecords.ts @@ -0,0 +1,90 @@ +// The daily rack and this machine's best runs. Everyone racks the same balls on the same day, +// so times compare fairly; a team-wide leaderboard can later post these same runs. + +const STORAGE_KEY = "ari-billiards-runs"; +const MAX_RUNS = 100; + +export type Medal = "gold" | "silver" | "bronze"; + +/** A run under these times earns the medal. Tune once the team has played a few racks. */ +const MEDAL_TIMES_MS: ReadonlyArray = [ + ["gold", 150_000], + ["silver", 210_000], + ["bronze", 300_000], +]; + +export interface BilliardsRun { + /** The rack's day, `YYYY-MM-DD` in Zürich. */ + readonly day: string; + /** Clock plus penalties: what ranks. */ + readonly totalMs: number; + readonly penaltySeconds: number; + readonly shots: number; + readonly finishedAt: string; +} + +/** Today's date in Zürich, so the whole team switches racks at the same midnight. */ +export function rackDay(now: Date = new Date()): string { + return new Intl.DateTimeFormat("en-CA", { + timeZone: "Europe/Zurich", + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(now); +} + +/** A stable seed for a day's rack. */ +export function rackSeed(day: string): number { + let hash = 2166136261; + for (let i = 0; i < day.length; i++) { + hash ^= day.charCodeAt(i); + hash = Math.imul(hash, 16777619); + } + return hash >>> 0; +} + +export function medalFor(totalMs: number): Medal | null { + return MEDAL_TIMES_MS.find(([, limit]) => totalMs < limit)?.[0] ?? null; +} + +/** The next medal a time could earn, and the time it takes. */ +export function nextMedal(totalMs: number | null): readonly [Medal, number] | null { + const better = MEDAL_TIMES_MS.filter(([, limit]) => totalMs === null || totalMs >= limit); + return better.at(-1) ?? null; +} + +function isRun(value: unknown): value is BilliardsRun { + if (typeof value !== "object" || value === null) return false; + const run = value as Record; + return ( + typeof run.day === "string" && + typeof run.totalMs === "number" && + typeof run.penaltySeconds === "number" && + typeof run.shots === "number" && + typeof run.finishedAt === "string" + ); +} + +export function loadRuns(): BilliardsRun[] { + try { + const parsed: unknown = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "[]"); + return Array.isArray(parsed) ? parsed.filter(isRun) : []; + } catch { + return []; + } +} + +/** Keeps the best runs; saving can fail in a locked-down browser, and the game plays on. */ +export function saveRun(runs: ReadonlyArray, run: BilliardsRun): BilliardsRun[] { + const next = [...runs, run].sort((a, b) => a.totalMs - b.totalMs).slice(0, MAX_RUNS); + try { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); + } catch { + // Not saved; the run still shows for this session. + } + return next; +} + +export function runsOn(runs: ReadonlyArray, day: string): BilliardsRun[] { + return runs.filter((run) => run.day === day).sort((a, b) => a.totalMs - b.totalMs); +} diff --git a/apps/web/src/components/billiards/billiardsRender.ts b/apps/web/src/components/billiards/billiardsRender.ts new file mode 100644 index 0000000000..bfbbdfeffb --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRender.ts @@ -0,0 +1,444 @@ +import { castTrajectory, GOLDEN_SIGHT } from "./billiardsAim.ts"; +import { drawCue, drawRings, POWER_COLORS, type CueStyle } from "./billiardsCues.ts"; +import type { BallSprites } from "./billiardsBalls.ts"; +import type { ClothNap, Effects } from "./billiardsFx.ts"; +import { shotSpeed, type Ball } from "./billiardsPhysics.ts"; +import { EIGHT, type BilliardsGame } from "./billiardsRules.ts"; +import { + BALL_RADIUS, + CUSHIONS, + FOOT_SPOT, + HEAD_SPOT, + POCKETS, + RAIL_WIDTH, + TABLE_LENGTH, + TABLE_WIDTH, + type Pocket, +} from "./billiardsTable.ts"; + +// The canvas is a 9:16 frame around the table, in table units. +export const FRAME_WIDTH = 1.4; +const FRAME_HEIGHT = (FRAME_WIDTH * 16) / 9; +// The table sits a little low in the frame, leaving the top for the brass scoreboard. +export const TABLE_ORIGIN = { + x: (FRAME_WIDTH - TABLE_WIDTH) / 2, + y: 0.3, +}; + +const R = BALL_RADIUS; +const CLOTH_CENTER = "#1d6896"; +const CLOTH_EDGE = "#0f3b5c"; +const CUSHION = "#164f78"; +const SINK_SECONDS = 0.22; +const CALL = "255, 200, 80"; + +export interface Sinking { + readonly ball: number; + readonly x: number; + readonly y: number; + readonly pocket: Pocket; + readonly start: number; +} + +export interface SceneView { + readonly game: BilliardsGame; + readonly aimAngle: number; + /** 0 to 1 while charging a shot, null otherwise. */ + readonly power: number | null; + readonly hoverPocket: number | null; + readonly sinking: ReadonlyArray; + /** Seconds, for pulses and animations. */ + readonly now: number; + readonly sprites: BallSprites; + readonly nap: ClothNap; + readonly fx: Effects; + /** Screen shake, in table units. */ + readonly shake: { readonly x: number; readonly y: number }; + /** 0 to 1: darkens the edges while the final 8 rolls in slow motion. */ + readonly vignette: number; + readonly cueStyle: CueStyle; +} + +export { SINK_SECONDS }; + +/** Sets the table transform: table units, origin at the cloth's top left corner. */ +export function tableTransform(ctx: CanvasRenderingContext2D, scale: number): void { + frameTransform(ctx, scale); +} + +function frameTransform( + ctx: CanvasRenderingContext2D, + scale: number, + shiftX = 0, + shiftY = 0, +): void { + ctx.setTransform( + scale, + 0, + 0, + scale, + (TABLE_ORIGIN.x + shiftX) * scale, + (TABLE_ORIGIN.y + shiftY) * scale, + ); +} + +/** Everything that never moves, drawn once per resize. */ +export function drawStaticLayer(layer: HTMLCanvasElement, scale: number): void { + const ctx = layer.getContext("2d"); + if (!ctx) return; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, layer.width, layer.height); + frameTransform(ctx, scale); + + // A dark pool hall: warm near the table, black at the edges. + const backdrop = ctx.createRadialGradient(0.5, 1, 0.2, 0.5, 1, 1.6); + backdrop.addColorStop(0, "#21170f"); + backdrop.addColorStop(0.6, "#0d0906"); + backdrop.addColorStop(1, "#030202"); + ctx.fillStyle = backdrop; + ctx.fillRect(-TABLE_ORIGIN.x, -TABLE_ORIGIN.y, FRAME_WIDTH, FRAME_HEIGHT); + + // Rail wood, with a soft drop shadow under the whole table. + ctx.save(); + ctx.shadowColor = "rgba(0, 0, 0, 0.6)"; + ctx.shadowBlur = 0.06 * scale; + ctx.shadowOffsetY = 0.02 * scale; + const wood = ctx.createLinearGradient(-RAIL_WIDTH, 0, 1 + RAIL_WIDTH, 0); + wood.addColorStop(0, "#2a1810"); + wood.addColorStop(0.5, "#3d2416"); + wood.addColorStop(1, "#2a1810"); + ctx.fillStyle = wood; + ctx.beginPath(); + ctx.roundRect(-RAIL_WIDTH, -RAIL_WIDTH, 1 + RAIL_WIDTH * 2, 2 + RAIL_WIDTH * 2, 0.045); + ctx.fill(); + ctx.restore(); + ctx.strokeStyle = "rgba(255, 255, 255, 0.07)"; + ctx.lineWidth = 0.003; + ctx.stroke(); + + // Cloth, under the cushions too. + const cloth = ctx.createRadialGradient(0.5, 1, 0.1, 0.5, 1, 1.2); + cloth.addColorStop(0, CLOTH_CENTER); + cloth.addColorStop(1, CLOTH_EDGE); + ctx.fillStyle = cloth; + ctx.fillRect(-0.045, -0.045, 1.09, 2.09); + ctx.save(); + ctx.globalAlpha = 0.07; + ctx.fillStyle = noisePattern(ctx, scale); + ctx.fillRect(-0.045, -0.045, 1.09, 2.09); + ctx.restore(); + + for (const cushion of CUSHIONS) { + ctx.beginPath(); + for (const [i, point] of cushion.entries()) { + if (i === 0) ctx.moveTo(point.x, point.y); + else ctx.lineTo(point.x, point.y); + } + ctx.closePath(); + ctx.fillStyle = CUSHION; + ctx.fill(); + const [, noseStart, noseEnd] = cushion; + if (noseStart && noseEnd) { + ctx.beginPath(); + ctx.moveTo(noseStart.x, noseStart.y); + ctx.lineTo(noseEnd.x, noseEnd.y); + ctx.strokeStyle = "rgba(255, 255, 255, 0.1)"; + ctx.lineWidth = 0.003; + ctx.stroke(); + } + } + + for (const pocket of POCKETS) { + const hole = ctx.createRadialGradient(pocket.x, pocket.y, 0, pocket.x, pocket.y, pocket.radius); + hole.addColorStop(0, "#000"); + hole.addColorStop(0.75, "#050505"); + hole.addColorStop(1, "#1b1b1b"); + ctx.fillStyle = hole; + ctx.beginPath(); + ctx.arc(pocket.x, pocket.y, pocket.radius, 0, Math.PI * 2); + ctx.fill(); + } + + // Diamonds on the rails, spots and the head string on the cloth. + ctx.fillStyle = "rgba(236, 224, 196, 0.75)"; + const railMid = RAIL_WIDTH * 0.6; + for (const t of [0.25, 0.5, 0.75]) { + for (const [x, y] of [ + [t, -railMid], + [t, TABLE_LENGTH + railMid], + [-railMid, t], + [-railMid, 1 + t], + [1 + railMid, t], + [1 + railMid, 1 + t], + ] as const) { + ctx.beginPath(); + ctx.arc(x, y, 0.006, 0, Math.PI * 2); + ctx.fill(); + } + } + ctx.strokeStyle = "rgba(255, 255, 255, 0.06)"; + ctx.lineWidth = 0.003; + ctx.beginPath(); + ctx.moveTo(0, HEAD_SPOT.y); + ctx.lineTo(1, HEAD_SPOT.y); + ctx.stroke(); + ctx.fillStyle = "rgba(255, 255, 255, 0.18)"; + for (const spot of [HEAD_SPOT, FOOT_SPOT]) { + ctx.beginPath(); + ctx.arc(spot.x, spot.y, 0.005, 0, Math.PI * 2); + ctx.fill(); + } + + // One lamp over the middle of the table: a warm pool of light, edges falling off into the dark. + const lamp = ctx.createRadialGradient(0.5, 0.95, 0.05, 0.5, 1, 1.35); + lamp.addColorStop(0, "rgba(255, 214, 160, 0.09)"); + lamp.addColorStop(0.45, "rgba(255, 200, 140, 0.02)"); + lamp.addColorStop(0.75, "rgba(0, 0, 0, 0.18)"); + lamp.addColorStop(1, "rgba(0, 0, 0, 0.5)"); + ctx.fillStyle = lamp; + ctx.fillRect(-TABLE_ORIGIN.x, -TABLE_ORIGIN.y, FRAME_WIDTH, FRAME_HEIGHT); + + // The tray the potted balls line up in. + ctx.fillStyle = "rgba(255, 255, 255, 0.04)"; + ctx.beginPath(); + ctx.roundRect(-0.01, TRAY_Y - 0.032, 1.02, 0.064, 0.032); + ctx.fill(); +} + +const TRAY_Y = TABLE_LENGTH + RAIL_WIDTH + 0.045; + +function noisePattern(ctx: CanvasRenderingContext2D, scale: number): CanvasPattern | string { + const size = 128; + const tile = document.createElement("canvas"); + tile.width = size; + tile.height = size; + const tileContext = tile.getContext("2d"); + if (!tileContext) return "transparent"; + const image = tileContext.createImageData(size, size); + for (let i = 0; i < image.data.length; i += 4) { + const value = Math.random() * 255; + image.data[i] = value; + image.data[i + 1] = value; + image.data[i + 2] = value; + image.data[i + 3] = 255; + } + tileContext.putImageData(image, 0, 0); + const pattern = ctx.createPattern(tile, "repeat"); + if (!pattern) return "transparent"; + pattern.setTransform(new DOMMatrix().scale(1 / scale)); + return pattern; +} + +export function drawScene( + ctx: CanvasRenderingContext2D, + staticLayer: HTMLCanvasElement, + scale: number, + view: SceneView, +): void { + const { game, sprites } = view; + const shiftX = view.shake.x * scale; + const shiftY = view.shake.y * scale; + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (shiftX !== 0 || shiftY !== 0) { + ctx.fillStyle = "#06080c"; + ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); + } + ctx.drawImage(staticLayer, shiftX, shiftY); + frameTransform(ctx, scale, view.shake.x, view.shake.y); + view.nap.draw(ctx, shiftX, shiftY); + if (!game.isBreak) drawRings(ctx, game.rings, view.now); + + const cue = game.ball(0); + const aiming = game.phase === "aiming" && cue?.onTable; + if (game.needsCall()) drawPocketCalls(ctx, view); + if (aiming && cue) { + drawAimGuide(ctx, game, cue, view.aimAngle, view.power, game.goldenShots > 0); + } + + for (const ball of game.balls) if (ball.onTable) drawShadow(ctx, ball.x, ball.y, 1); + for (const ball of game.balls) if (ball.onTable) sprites.draw(ctx, ball.id, ball.x, ball.y); + for (const sinking of view.sinking) drawSinking(ctx, sprites, sinking, view.now); + view.fx.draw(ctx); + + if (aiming && cue) { + drawCue(ctx, cue, view.aimAngle, view.power ?? 0, view.cueStyle, view.now); + } + if (view.power !== null) drawPowerMeter(ctx, view.power); + + for (const [i, id] of game.pottedOrder.entries()) { + sprites.draw(ctx, id, 0.035 + i * 0.066, TRAY_Y); + } + if (view.vignette > 0) drawVignette(ctx, view.vignette); +} + +function drawVignette(ctx: CanvasRenderingContext2D, amount: number): void { + const shade = ctx.createRadialGradient(0.5, 1, 0.45, 0.5, 1, 1.45); + shade.addColorStop(0, "rgba(0, 0, 0, 0)"); + shade.addColorStop(1, `rgba(0, 0, 0, ${0.6 * amount})`); + ctx.fillStyle = shade; + ctx.fillRect( + -TABLE_ORIGIN.x - 0.05, + -TABLE_ORIGIN.y - 0.05, + FRAME_WIDTH + 0.1, + FRAME_HEIGHT + 0.1, + ); +} + +function drawShadow(ctx: CanvasRenderingContext2D, x: number, y: number, size: number): void { + const shadow = ctx.createRadialGradient( + x + R * 0.3, + y + R * 0.45, + 0, + x + R * 0.3, + y + R * 0.45, + R * 1.25 * size, + ); + shadow.addColorStop(0, "rgba(0, 0, 0, 0.45)"); + shadow.addColorStop(0.6, "rgba(0, 0, 0, 0.25)"); + shadow.addColorStop(1, "rgba(0, 0, 0, 0)"); + ctx.fillStyle = shadow; + ctx.beginPath(); + ctx.arc(x + R * 0.3, y + R * 0.45, R * 1.25 * size, 0, Math.PI * 2); + ctx.fill(); +} + +function drawSinking( + ctx: CanvasRenderingContext2D, + sprites: BallSprites, + sinking: Sinking, + now: number, +): void { + const t = Math.min(1, (now - sinking.start) / SINK_SECONDS); + const ease = t * t; + const x = sinking.x + (sinking.pocket.x - sinking.x) * ease; + const y = sinking.y + (sinking.pocket.y - sinking.y) * ease; + const size = 1 - 0.45 * ease; + ctx.save(); + ctx.globalAlpha = 1 - ease * 0.85; + sprites.draw(ctx, sinking.ball, x, y, size); + ctx.restore(); +} + +function drawAimGuide( + ctx: CanvasRenderingContext2D, + game: BilliardsGame, + cue: Ball, + angle: number, + power: number | null, + golden: boolean, +): void { + // While charging, the line only reaches as far as this power rolls the cue ball. + const speed = power === null ? null : shotSpeed(power); + const path = golden + ? castTrajectory(game.balls, cue, angle, speed, GOLDEN_SIGHT.bounces, GOLDEN_SIGHT.length) + : castTrajectory(game.balls, cue, angle, speed); + const dots = golden ? POWER_COLORS.golden : "255, 255, 255"; + ctx.save(); + ctx.lineCap = "round"; + // Zero-length dashes with round caps draw dots; each cushion leg fades a little more. + ctx.setLineDash([0, 0.017]); + ctx.lineWidth = 0.0065; + for (let i = 1; i < path.points.length; i++) { + const from = path.points[i - 1]; + const to = path.points[i]; + if (!from || !to) continue; + ctx.strokeStyle = `rgba(${dots}, ${Math.max(0.2, 0.8 - (i - 1) * (golden ? 0.1 : 0.25))})`; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } + ctx.setLineDash([]); + const end = path.points[path.points.length - 1] ?? cue; + if (path.ball) { + const { ball } = path; + ctx.strokeStyle = "rgba(255, 255, 255, 0.75)"; + ctx.lineWidth = 0.004; + ctx.beginPath(); + ctx.arc(end.x, end.y, R, 0, Math.PI * 2); + ctx.stroke(); + const nx = (ball.x - end.x) / (2 * R); + const ny = (ball.y - end.y) / (2 * R); + if (golden) { + // Full sight: where the object ball goes, off its cushions too. + const others = game.balls.filter((other) => other !== cue); + const objectPath = castTrajectory(others, ball, Math.atan2(ny, nx), null, 3, 2.5); + ctx.setLineDash([0, 0.017]); + ctx.lineWidth = 0.0065; + ctx.strokeStyle = `rgba(${POWER_COLORS.golden}, 0.85)`; + ctx.beginPath(); + for (const [i, point] of objectPath.points.entries()) { + if (i === 0) ctx.moveTo(point.x, point.y); + else ctx.lineTo(point.x, point.y); + } + ctx.stroke(); + ctx.setLineDash([]); + } else { + ctx.strokeStyle = "rgba(255, 255, 255, 0.7)"; + ctx.lineWidth = 0.0045; + ctx.beginPath(); + ctx.moveTo(ball.x + nx * R, ball.y + ny * R); + ctx.lineTo(ball.x + nx * 0.3, ball.y + ny * 0.3); + ctx.stroke(); + } + // The cue ball leaves at right angles to the object ball. + const along = path.dx * nx + path.dy * ny; + const tx = path.dx - along * nx; + const ty = path.dy - along * ny; + const length = Math.hypot(tx, ty); + if (length > 0.05) { + ctx.strokeStyle = "rgba(255, 255, 255, 0.25)"; + ctx.lineWidth = 0.003; + ctx.beginPath(); + ctx.moveTo(end.x, end.y); + ctx.lineTo(end.x + (tx / length) * 0.12, end.y + (ty / length) * 0.12); + ctx.stroke(); + } + } else if (path.stops) { + ctx.strokeStyle = "rgba(255, 255, 255, 0.35)"; + ctx.lineWidth = 0.003; + ctx.beginPath(); + ctx.arc(end.x, end.y, R, 0, Math.PI * 2); + ctx.stroke(); + } else if (path.pocket !== null) { + // Straight into a pocket: a scratch. + ctx.strokeStyle = "rgba(255, 110, 90, 0.85)"; + ctx.lineWidth = 0.004; + ctx.beginPath(); + ctx.arc(end.x, end.y, R, 0, Math.PI * 2); + ctx.stroke(); + } + ctx.restore(); +} + +function drawPowerMeter(ctx: CanvasRenderingContext2D, power: number): void { + const x = 1 + RAIL_WIDTH + 0.04; + const top = 0.6; + const height = 0.8; + ctx.fillStyle = "rgba(255, 255, 255, 0.08)"; + ctx.beginPath(); + ctx.roundRect(x, top, 0.018, height, 0.009); + ctx.fill(); + const fill = ctx.createLinearGradient(0, top + height, 0, top); + fill.addColorStop(0, "#5ad19a"); + fill.addColorStop(0.6, "#ffc850"); + fill.addColorStop(1, "#ff5a4f"); + ctx.fillStyle = fill; + ctx.beginPath(); + ctx.roundRect(x, top + height * (1 - power), 0.018, height * power, 0.009); + ctx.fill(); +} + +function drawPocketCalls(ctx: CanvasRenderingContext2D, view: SceneView): void { + const pulse = 0.35 + 0.25 * Math.sin(view.now * 4); + for (const pocket of POCKETS) { + const called = view.game.calledPocket === pocket.id; + const hovered = view.hoverPocket === pocket.id; + ctx.strokeStyle = `rgba(${CALL}, ${called || hovered ? 0.95 : pulse})`; + ctx.lineWidth = called ? 0.008 : 0.005; + ctx.beginPath(); + ctx.arc(pocket.x, pocket.y, pocket.radius * 1.3, 0, Math.PI * 2); + ctx.stroke(); + if (called) view.sprites.draw(ctx, EIGHT, pocket.x, pocket.y, 0.6); + } +} diff --git a/apps/web/src/components/billiards/billiardsRules.test.ts b/apps/web/src/components/billiards/billiardsRules.test.ts new file mode 100644 index 0000000000..b84167ee09 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRules.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { makeBall, shotSpeed, type Ball, type PhysicsEvent } from "./billiardsPhysics.ts"; +import { BilliardsGame, EIGHT, rackBalls, seededRandom } from "./billiardsRules.ts"; +import { BALL_RADIUS, FOOT_SPOT, HEAD_SPOT, POCKETS } from "./billiardsTable.ts"; + +function settle(game: BilliardsGame): PhysicsEvent[] { + const events: PhysicsEvent[] = []; + for (let frame = 0; frame < 60 * 60 && game.phase === "rolling"; frame++) { + game.advance(1 / 60, events); + } + return events; +} + +function angleTo(from: Ball, x: number, y: number): number { + return Math.atan2(y - from.y, x - from.x); +} + +function overlaps(balls: ReadonlyArray): number { + let count = 0; + const onTable = balls.filter((ball) => ball.onTable); + for (let i = 0; i < onTable.length; i++) { + for (let j = i + 1; j < onTable.length; j++) { + const a = onTable[i] as Ball; + const b = onTable[j] as Ball; + if (Math.hypot(a.x - b.x, a.y - b.y) < BALL_RADIUS * 2 - 1e-6) count++; + } + } + return count; +} + +const topLeft = POCKETS[0]!; +const topRight = POCKETS[1]!; + +describe("rackBalls", () => { + it("racks 15 balls without overlap and the 8 in the middle", () => { + const balls = rackBalls(seededRandom(7)); + expect(balls).toHaveLength(16); + expect(new Set(balls.map((ball) => ball.id)).size).toBe(16); + expect(overlaps(balls)).toBe(0); + const eight = balls.find((ball) => ball.id === EIGHT)!; + expect(eight.x).toBeCloseTo(FOOT_SPOT.x); + }); + + it("racks the same way for the same seed", () => { + expect(rackBalls(seededRandom(42))).toEqual(rackBalls(seededRandom(42))); + }); +}); + +describe("the break", () => { + it("spreads the rack at full power and comes to rest on the table", () => { + const game = new BilliardsGame({ random: seededRandom(3) }); + const cue = game.ball(0)!; + expect(game.shoot(angleTo(cue, FOOT_SPOT.x, FOOT_SPOT.y) + 0.004, shotSpeed(1))).toBe(true); + settle(game); + expect(game.phase).toBe("aiming"); + expect(game.shots).toBe(0); + expect(game.penaltySeconds).toBe(0); + expect(overlaps(game.balls)).toBe(0); + for (const ball of game.balls.filter((b) => b.onTable)) { + expect(ball.x).toBeGreaterThan(0); + expect(ball.x).toBeLessThan(1); + expect(ball.y).toBeGreaterThan(0); + expect(ball.y).toBeLessThan(2); + } + const moved = game.balls.filter((b) => b.id !== 0 && Math.abs(b.y - FOOT_SPOT.y) > 0.2); + expect(moved.length).toBeGreaterThan(5); + }); + + it("is the same every time for the same rack and shot", () => { + const run = () => { + const game = new BilliardsGame({ random: seededRandom(11) }); + game.shoot(-Math.PI / 2 + 0.01, shotSpeed(1)); + settle(game); + return game.balls.map((ball) => [ball.id, ball.x, ball.y, ball.onTable]); + }; + expect(run()).toEqual(run()); + }); +}); + +describe("rules", () => { + // Cue and 8 on the diagonal to the top-left corner, so a straight shot pots the 8 there. + const eightShot = (extra: Ball[] = []) => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.4, 0.4), makeBall(EIGHT, 0.2, 0.2), ...extra], + }); + return { game, angle: angleTo(game.ball(0)!, topLeft.x, topLeft.y) }; + }; + + it("needs a called pocket before shooting the 8", () => { + const { game, angle } = eightShot(); + expect(game.needsCall()).toBe(true); + expect(game.shoot(angle, 2)).toBe(false); + }); + + it("clears the table when the 8 drops in the called pocket", () => { + const { game, angle } = eightShot(); + game.callPocket(topLeft.id); + expect(game.shoot(angle, 2)).toBe(true); + settle(game); + expect(game.phase).toBe("cleared"); + expect(game.shots).toBe(1); + expect(game.penaltySeconds).toBe(0); + }); + + it("respots the 8 with a penalty when it drops in another pocket", () => { + const { game, angle } = eightShot(); + game.callPocket(topRight.id); + game.shoot(angle, 2); + settle(game); + expect(game.phase).toBe("aiming"); + expect(game.lastShot?.foul).toBe("wrong8"); + expect(game.penaltySeconds).toBe(15); + expect(game.ball(EIGHT)).toMatchObject({ onTable: true, x: FOOT_SPOT.x }); + }); + + it("respots the 8 with a penalty when it drops before the other balls", () => { + const { game, angle } = eightShot([makeBall(3, 0.8, 1.6)]); + expect(game.needsCall()).toBe(false); + game.shoot(angle, 2); + settle(game); + expect(game.lastShot?.foul).toBe("early8"); + expect(game.penaltySeconds).toBe(15); + expect(game.ball(EIGHT)?.onTable).toBe(true); + }); + + it("puts a scratched cue ball back on the head spot with a penalty", () => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.3, 0.3), makeBall(3, 0.8, 1.6)], + }); + game.shoot(angleTo(game.ball(0)!, topLeft.x, topLeft.y), 2); + settle(game); + expect(game.lastShot?.foul).toBe("scratch"); + expect(game.penaltySeconds).toBe(10); + expect(game.ball(0)).toMatchObject({ onTable: true, x: HEAD_SPOT.x, y: HEAD_SPOT.y }); + }); + + it("forgives the first miss of a game, then adds seconds for each miss", () => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.5, 1.5), makeBall(3, 0.8, 0.3)], + }); + game.shoot(Math.PI / 2, 0.6); + settle(game); + expect(game.lastShot).toMatchObject({ foul: "noContact", forgiven: true }); + expect(game.penaltySeconds).toBe(0); + game.shoot(-Math.PI / 2, 0.6); + settle(game); + expect(game.lastShot).toMatchObject({ foul: "noContact", forgiven: false }); + expect(game.penaltySeconds).toBe(5); + }); + + it("counts a clean pot as one shot", () => { + const game = new BilliardsGame({ + skipBreak: true, + balls: [makeBall(0, 0.4, 0.4), makeBall(3, 0.2, 0.2), makeBall(EIGHT, 0.5, 1.2)], + }); + game.shoot(angleTo(game.ball(0)!, topLeft.x, topLeft.y), 2); + settle(game); + expect(game.lastShot).toEqual({ foul: null, forgiven: false, potted: [3] }); + expect(game.penaltySeconds).toBe(0); + expect(game.needsCall()).toBe(true); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsRules.ts b/apps/web/src/components/billiards/billiardsRules.ts new file mode 100644 index 0000000000..55635de992 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsRules.ts @@ -0,0 +1,343 @@ +import { + anyMoving, + makeBall, + stepPhysics, + STEP_SECONDS, + type Ball, + type PhysicsEvent, +} from "./billiardsPhysics.ts"; +import { + BALL_RADIUS, + FOOT_SPOT, + HEAD_SPOT, + POCKETS, + TABLE_LENGTH, + type Point, +} from "./billiardsTable.ts"; + +// Solo 8-ball: pot the other 14 in any order, then the 8 into a pocket you call. +// It's a race: the clock starts once the break settles, and fouls add seconds to it. + +export type Foul = "scratch" | "noContact" | "early8" | "wrong8" | "scratch8"; + +/** Seconds each foul adds to the clock. */ +export const FOUL_PENALTY_SECONDS: Readonly> = { + scratch: 10, + noContact: 5, + early8: 15, + wrong8: 15, + scratch8: 15, +}; +export const EIGHT = 8; + +export type Phase = "aiming" | "rolling" | "cleared"; + +// Power-ups: rings on the cloth, placed by the daily seed so everyone gets the same ones. +// Rolling the cue ball over a ring arms it for the next shot. +export type PowerKind = "wand" | "golden" | "glow"; + +export interface PowerRing { + readonly id: number; + readonly kind: PowerKind; + readonly x: number; + readonly y: number; + collected: boolean; +} + +/** The cue ball's centre has to pass this close to a ring's centre. */ +export const RING_RADIUS = 0.04; +/** How many shots the golden cue's full sight lasts. */ +export const GOLDEN_SHOTS = 3; +/** How many balls one glow shot can burst into pockets. */ +export const GLOW_BALLS = 3; + +/** Two rings a rack: one in each half, the glow cue rarer than the other two. */ +export function placeRings(random: () => number): PowerRing[] { + const first: PowerKind = random() < 0.5 ? "wand" : "golden"; + const second: PowerKind = random() < 0.35 ? "glow" : first === "wand" ? "golden" : "wand"; + const spot = (top: number, bottom: number) => ({ + x: 0.14 + random() * 0.72, + y: top + random() * (bottom - top), + }); + return [ + { id: 0, kind: first, ...spot(1.05, 1.38), collected: false }, + { id: 1, kind: second, ...spot(0.18, 0.85), collected: false }, + ]; +} + +/** A shot that runs longer than this is stopped where it is. */ +const MAX_ROLL_SECONDS = 40; + +/** Same seed, same sequence: the daily rack depends on it. */ +export function seededRandom(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** The cue ball on the head spot and 15 balls racked on the foot spot, the 8 in the middle. */ +export function rackBalls(random: () => number): Ball[] { + const others = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15]; + for (let i = others.length - 1; i > 0; i--) { + const j = Math.floor(random() * (i + 1)); + [others[i], others[j]] = [others[j] as number, others[i] as number]; + } + const spacing = BALL_RADIUS * 2 + 0.0004; + const rowStep = spacing * (Math.sqrt(3) / 2); + const balls: Ball[] = [makeBall(0, HEAD_SPOT.x, HEAD_SPOT.y)]; + let next = 0; + for (let row = 0; row < 5; row++) { + for (let i = 0; i <= row; i++) { + const id = row === 2 && i === 1 ? EIGHT : (others[next++] as number); + balls.push(makeBall(id, FOOT_SPOT.x + (i - row / 2) * spacing, FOOT_SPOT.y - row * rowStep)); + } + } + return balls; +} + +function nearestPocketId(x: number, y: number): number { + let best = 0; + let bestDistance = Infinity; + for (const pocket of POCKETS) { + const distance = Math.hypot(pocket.x - x, pocket.y - y); + if (distance < bestDistance) { + best = pocket.id; + bestDistance = distance; + } + } + return best; +} + +export interface ShotResult { + readonly foul: Foul | null; + /** The game's first miss is free: likely a slip, so it only warns. */ + readonly forgiven: boolean; + readonly potted: ReadonlyArray; +} + +export interface BilliardsGameOptions { + readonly random?: () => number; + /** A custom layout, for tests. */ + readonly balls?: Ball[]; + /** Power-up rings; none without them. */ + readonly rings?: PowerRing[]; + readonly skipBreak?: boolean; +} + +export class BilliardsGame { + readonly balls: Ball[]; + phase: Phase = "aiming"; + isBreak: boolean; + shots = 0; + penaltySeconds = 0; + calledPocket: number | null = null; + lastShot: ShotResult | null = null; + /** Ball ids in the order they dropped. */ + readonly pottedOrder: number[] = []; + readonly rings: PowerRing[]; + /** Waiting for the next shot. */ + armed: "wand" | "glow" | null = null; + /** Shots left with the golden cue's full sight. */ + goldenShots = 0; + + private accumulator = 0; + private rollSeconds = 0; + private firstContact: number | null = null; + private pottedThisShot: Array<{ ball: number; pocket: number }> = []; + private objectBallsAtShotStart = 0; + private missForgiven = false; + /** The power-up working on the shot that's rolling. */ + private active: "wand" | "glow" | null = null; + private guidedThisShot = 0; + + constructor(options: BilliardsGameOptions = {}) { + this.balls = options.balls ?? rackBalls(options.random ?? Math.random); + this.isBreak = !options.skipBreak; + this.rings = options.rings ?? []; + } + + /** The power-up working on the shot that's rolling. */ + get activePower(): "wand" | "glow" | null { + return this.active; + } + + ball(id: number): Ball | undefined { + return this.balls.find((ball) => ball.id === id); + } + + /** Object balls still on the table, not counting the 8. */ + objectBallsLeft(): number { + return this.balls.filter((ball) => ball.onTable && ball.id !== 0 && ball.id !== EIGHT).length; + } + + /** Only the 8 is left, so a pocket has to be called before shooting. */ + needsCall(): boolean { + return this.phase === "aiming" && this.objectBallsLeft() === 0 && !!this.ball(EIGHT)?.onTable; + } + + callPocket(pocket: number): void { + if (this.needsCall()) this.calledPocket = pocket; + } + + /** Strikes the cue ball. False when it isn't time to shoot, or the 8 needs a called pocket. */ + shoot(angle: number, speed: number): boolean { + const cue = this.ball(0); + if (this.phase !== "aiming" || !cue?.onTable) return false; + if (this.needsCall() && this.calledPocket === null) return false; + cue.vx = Math.cos(angle) * speed; + cue.vy = Math.sin(angle) * speed; + this.firstContact = null; + this.pottedThisShot = []; + this.objectBallsAtShotStart = this.objectBallsLeft(); + this.active = this.armed; + this.armed = null; + this.guidedThisShot = 0; + if (this.goldenShots > 0) this.goldenShots -= 1; + this.rollSeconds = 0; + this.accumulator = 0; + this.phase = "rolling"; + return true; + } + + /** Runs the simulation for `seconds` in fixed steps; settles the shot once every ball stops. */ + advance(seconds: number, events: PhysicsEvent[]): void { + if (this.phase !== "rolling") return; + this.accumulator += seconds; + while (this.accumulator >= STEP_SECONDS) { + this.accumulator -= STEP_SECONDS; + this.rollSeconds += STEP_SECONDS; + const from = events.length; + stepPhysics(this.balls, events, { cueGhost: this.active === "glow" }); + const stepEnd = events.length; + for (let i = from; i < stepEnd; i++) { + const event = events[i]; + if (event?.kind === "ball" && (event.a === 0 || event.b === 0)) { + const other = event.a === 0 ? event.b : event.a; + if (this.firstContact === null) { + this.firstContact = other; + if (this.active === "wand") this.guide(other, events); + } + } else if (event?.kind === "touch") { + this.firstContact ??= event.ball; + if (this.active === "glow" && this.guidedThisShot < GLOW_BALLS) { + this.guide(event.ball, events); + } + } else if (event?.kind === "pocket") { + this.pottedThisShot.push({ ball: event.ball, pocket: event.pocket }); + if (event.ball !== 0) this.pottedOrder.push(event.ball); + } + } + this.collectRings(events); + if (this.rollSeconds > MAX_ROLL_SECONDS) { + for (const ball of this.balls) { + ball.vx = 0; + ball.vy = 0; + ball.guidedTo = null; + } + } + if (!anyMoving(this.balls)) { + this.settle(); + return; + } + } + } + + /** Steers a ball into a pocket: the nearest, or for the last 8 the called one. */ + private guide(id: number, events: PhysicsEvent[]): void { + const ball = this.ball(id); + if (!ball?.onTable || ball.guidedTo !== null || id === 0) return; + let pocket: number | null; + if (id === EIGHT) { + // The 8 only drops by power-up when it's the last ball and its pocket is called. + if (this.objectBallsLeft() > 0) return; + pocket = this.calledPocket; + } else { + pocket = nearestPocketId(ball.x, ball.y); + } + if (pocket === null) return; + ball.guidedTo = pocket; + this.guidedThisShot += 1; + events.push({ kind: "guide", ball: id }); + } + + private collectRings(events: PhysicsEvent[]): void { + const cue = this.ball(0); + if (this.isBreak || !cue?.onTable) return; + for (const ring of this.rings) { + if (ring.collected || Math.hypot(ring.x - cue.x, ring.y - cue.y) > RING_RADIUS) continue; + ring.collected = true; + if (ring.kind === "golden") this.goldenShots = GOLDEN_SHOTS; + else this.armed = ring.kind; + events.push({ kind: "powerUp", ring: ring.id }); + } + } + + private settle(): void { + this.active = null; + const scratched = this.pottedThisShot.some((pot) => pot.ball === 0); + const eight = this.pottedThisShot.find((pot) => pot.ball === EIGHT); + let foul: Foul | null = null; + let forgiven = false; + let cleared = false; + + if (this.isBreak) { + this.isBreak = false; + } else { + this.shots += 1; + if (eight) { + if (this.objectBallsAtShotStart > 0) foul = "early8"; + else if (scratched) foul = "scratch8"; + else if (eight.pocket !== this.calledPocket) foul = "wrong8"; + else cleared = true; + } else if (scratched) { + foul = "scratch"; + } else if (this.firstContact === null) { + foul = "noContact"; + } + if (foul === "noContact" && !this.missForgiven) { + this.missForgiven = true; + forgiven = true; + } else if (foul) { + this.penaltySeconds += FOUL_PENALTY_SECONDS[foul]; + } + } + + if (eight && !cleared) this.respot(EIGHT, FOOT_SPOT, -1); + if (scratched) this.respot(0, HEAD_SPOT, 1); + this.lastShot = { + foul, + forgiven, + potted: this.pottedThisShot.map((pot) => pot.ball).filter((id) => id !== 0), + }; + this.phase = cleared ? "cleared" : "aiming"; + } + + /** Puts a ball back on `spot`, sliding along the table (`direction` first) until it's clear. */ + private respot(id: number, spot: Point, direction: 1 | -1): void { + const ball = this.ball(id); + if (!ball) return; + const potted = this.pottedOrder.lastIndexOf(id); + if (potted !== -1) this.pottedOrder.splice(potted, 1); + const step = BALL_RADIUS * 0.5; + for (let i = 0; i < 400; i++) { + const offset = (i % 2 === 1 ? 1 : -1) * Math.ceil(i / 2) * step * direction; + const y = spot.y + offset; + if (y < BALL_RADIUS || y > TABLE_LENGTH - BALL_RADIUS) continue; + const free = this.balls.every( + (other) => + other === ball || + !other.onTable || + Math.hypot(other.x - spot.x, other.y - y) >= BALL_RADIUS * 2 + 0.001, + ); + if (free) { + Object.assign(ball, { x: spot.x, y, vx: 0, vy: 0, onTable: true, guidedTo: null }); + return; + } + } + } +} diff --git a/apps/web/src/components/billiards/billiardsSession.ts b/apps/web/src/components/billiards/billiardsSession.ts new file mode 100644 index 0000000000..2e5c7175c7 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsSession.ts @@ -0,0 +1,611 @@ +import { observeResize } from "~/lib/observeResize"; + +import { BilliardsAudio } from "./billiardsAudio.ts"; +import { BallSprites } from "./billiardsBalls.ts"; +import { ClothNap, Effects } from "./billiardsFx.ts"; +import { + Callouts, + drawChalkHints, + drawScoreboard, + type BilliardsLabels, + type ScoreView, +} from "./billiardsHud.ts"; +import { shotSpeed, type PhysicsEvent } from "./billiardsPhysics.ts"; +import { + drawScene, + drawStaticLayer, + FRAME_WIDTH, + SINK_SECONDS, + tableTransform, + TABLE_ORIGIN, + type Sinking, +} from "./billiardsRender.ts"; +import { + loadRuns, + medalFor, + rackDay, + rackSeed, + runsOn, + saveRun, + type BilliardsRun, + type Medal, +} from "./billiardsRecords.ts"; +import { cueTip, POWER_COLORS, type CueStyle } from "./billiardsCues.ts"; +import { loadSkin, saveSkin, unlockedSkins, type SkinId } from "./billiardsSkins.ts"; +import { + BilliardsGame, + EIGHT, + FOUL_PENALTY_SECONDS, + placeRings, + seededRandom, + type Foul, + type Phase, +} from "./billiardsRules.ts"; +import { POCKETS, type Point } from "./billiardsTable.ts"; + +/** What the overlay shows around the canvas. */ +export interface BilliardsHud { + readonly phase: Phase; + readonly isBreak: boolean; + readonly shots: number; + readonly penaltySeconds: number; + /** Clock plus penalties: the race time. */ + readonly totalMs: number; + readonly needsCall: boolean; + readonly calledPocket: number | null; + readonly foul: Foul | null; + /** The foul was the game's free first miss. */ + readonly forgiven: boolean; + /** The player tried to shoot the 8 without calling a pocket. */ + readonly blocked: boolean; + /** Today's rack, `YYYY-MM-DD`. */ + readonly day: string; + /** This machine's runs on today's rack, best first. */ + readonly todayRuns: ReadonlyArray; + /** How the run that just cleared the table placed. */ + readonly result: RunResult | null; + /** A power-up waiting for the next shot. */ + readonly armed: "wand" | "glow" | null; + readonly goldenShots: number; + readonly skin: SkinId; + readonly unlockedSkins: ReadonlySet; +} + +export interface RunResult { + readonly run: BilliardsRun; + /** 1 is the best run today. */ + readonly rankToday: number; + readonly medal: Medal | null; + /** Skins this run unlocked. */ + readonly newSkins: ReadonlyArray; +} + +function dailyGame(day: string): BilliardsGame { + const seed = rackSeed(day); + return new BilliardsGame({ + random: seededRandom(seed), + rings: placeRings(seededRandom(seed ^ 0x5bd1e995)), + }); +} + +const CHARGE_MS = 1100; +const FINE_AIM = 0.12; +const POCKET_PICK_RADIUS = 0.1; +const HUD_INTERVAL_MS = 250; +const FOUL_COLOR = "#ff8a70"; +const CALL_COLOR = "#ffd36a"; +/** How slow the final 8 rolls as it nears the called pocket. */ +const SLOW_MOTION = 0.3; + +function wrapAngle(angle: number): number { + return Math.atan2(Math.sin(angle), Math.cos(angle)); +} + +/** Runs one game on a canvas: input, simulation, sound and drawing. */ +export class BilliardsSession { + private readonly canvas: HTMLCanvasElement; + private readonly context: CanvasRenderingContext2D; + private readonly staticLayer = document.createElement("canvas"); + private readonly onHud: (hud: BilliardsHud) => void; + private readonly audio = new BilliardsAudio(); + private readonly sprites = new BallSprites(); + private readonly nap = new ClothNap(); + private readonly fx = new Effects(); + private readonly callouts = new Callouts(); + private labels: BilliardsLabels | null = null; + /** Where the cue ball dropped this shot, for the scratch callout. */ + private scratchPocket: number | null = null; + private readonly stopObservingResize: () => void; + private day = rackDay(); + private game = dailyGame(this.day); + private runs = loadRuns(); + private todayRuns = runsOn(this.runs, this.day); + private result: RunResult | null = null; + private unlocked = unlockedSkins(this.runs); + private skin: SkinId = this.unlocked.has(loadSkin()) ? loadSkin() : "classic"; + private scale = 1; + private frame = 0; + private lastFrame = 0; + private aimAngle = -Math.PI / 2; + private lastPointerAngle: number | null = null; + private pointer: Point | null = null; + private chargeStart: number | null = null; + private sinking: Sinking[] = []; + private clockStart: number | null = null; + private clockEnd: number | null = null; + private blockedUntil = 0; + /** Hit-stops and slow motion don't count against the player's clock. */ + private frozenMs = 0; + private timeScale = 1; + private finalShot = false; + private lastHud: BilliardsHud | null = null; + private lastHudAt = 0; + + constructor(canvas: HTMLCanvasElement, onHud: (hud: BilliardsHud) => void) { + const context = canvas.getContext("2d"); + if (!context) throw new Error("Canvas 2D is not available"); + this.canvas = canvas; + this.context = context; + this.onHud = onHud; + this.stopObservingResize = observeResize(canvas, () => this.resize()); + canvas.addEventListener("pointerdown", this.handlePointerDown); + canvas.addEventListener("pointermove", this.handlePointerMove); + canvas.addEventListener("pointerup", this.handlePointerUp); + canvas.addEventListener("pointercancel", this.handlePointerCancel); + canvas.addEventListener("contextmenu", this.handleContextMenu); + this.resize(); + this.frame = requestAnimationFrame(this.tick); + } + + dispose(): void { + cancelAnimationFrame(this.frame); + this.stopObservingResize(); + this.canvas.removeEventListener("pointerdown", this.handlePointerDown); + this.canvas.removeEventListener("pointermove", this.handlePointerMove); + this.canvas.removeEventListener("pointerup", this.handlePointerUp); + this.canvas.removeEventListener("pointercancel", this.handlePointerCancel); + this.canvas.removeEventListener("contextmenu", this.handleContextMenu); + this.audio.dispose(); + } + + restart(): void { + this.day = rackDay(); + this.game = dailyGame(this.day); + this.todayRuns = runsOn(this.runs, this.day); + this.result = null; + this.aimAngle = -Math.PI / 2; + this.chargeStart = null; + this.sinking = []; + this.clockStart = null; + this.clockEnd = null; + this.blockedUntil = 0; + this.frozenMs = 0; + this.timeScale = 1; + this.finalShot = false; + this.sprites.reset(); + this.nap.clear(); + this.fx.reset(); + this.callouts.reset(); + this.emitHud(performance.now(), true); + } + + /** The words the scene draws, in the reader's language. */ + setLabels(labels: BilliardsLabels): void { + this.labels = labels; + } + + /** A soft bell, for a thread that wants attention while playing. */ + chime(): void { + this.audio.chime(); + } + + /** Drops a shot being charged. False when there was none. */ + cancelCharge(): boolean { + if (this.chargeStart === null) return false; + this.chargeStart = null; + return true; + } + + private resize(): void { + const rect = this.canvas.getBoundingClientRect(); + if (rect.width === 0 || rect.height === 0) return; + const ratio = window.devicePixelRatio || 1; + this.canvas.width = Math.round(rect.width * ratio); + this.canvas.height = Math.round(rect.height * ratio); + this.staticLayer.width = this.canvas.width; + this.staticLayer.height = this.canvas.height; + this.scale = this.canvas.width / FRAME_WIDTH; + drawStaticLayer(this.staticLayer, this.scale); + this.sprites.resize(this.scale); + this.nap.resize( + this.canvas.width, + this.canvas.height, + this.scale, + TABLE_ORIGIN.x * this.scale, + TABLE_ORIGIN.y * this.scale, + ); + } + + private toTable(event: PointerEvent): Point { + const rect = this.canvas.getBoundingClientRect(); + return { + x: ((event.clientX - rect.left) / rect.width) * FRAME_WIDTH - TABLE_ORIGIN.x, + y: ((event.clientY - rect.top) / rect.width) * FRAME_WIDTH - TABLE_ORIGIN.y, + }; + } + + private pocketAt(point: Point | null): number | null { + if (!point || !this.game.needsCall()) return null; + for (const pocket of POCKETS) { + if (Math.hypot(pocket.x - point.x, pocket.y - point.y) < POCKET_PICK_RADIUS) return pocket.id; + } + return null; + } + + private power(now: number): number { + return this.chargeStart === null ? 0 : Math.min(1, (now - this.chargeStart) / CHARGE_MS); + } + + private readonly handlePointerMove = (event: PointerEvent) => { + this.pointer = this.toTable(event); + this.canvas.style.cursor = this.pocketAt(this.pointer) === null ? "crosshair" : "pointer"; + const cue = this.game.ball(0); + if (!cue?.onTable) return; + const target = Math.atan2(this.pointer.y - cue.y, this.pointer.x - cue.x); + // The aim holds still while a shot charges, so pressing a trackpad can't nudge it. + if (this.chargeStart === null) { + this.aimAngle = + event.shiftKey && this.lastPointerAngle !== null + ? this.aimAngle + wrapAngle(target - this.lastPointerAngle) * FINE_AIM + : target; + } + this.lastPointerAngle = target; + }; + + private readonly handlePointerDown = (event: PointerEvent) => { + if (event.button !== 0) return; + this.audio.unlock(); + const now = performance.now(); + if (this.game.phase !== "aiming") return; + const pocket = this.pocketAt(this.toTable(event)); + if (pocket !== null) { + this.game.callPocket(pocket); + this.emitHud(now, true); + return; + } + if (this.game.needsCall() && this.game.calledPocket === null) { + this.blockedUntil = now + 2500; + const cue = this.game.ball(0); + if (cue && this.labels) + this.callouts.add(this.labels.callFirst, cue.x, cue.y - 0.06, CALL_COLOR); + this.emitHud(now, true); + return; + } + this.chargeStart = now; + this.canvas.setPointerCapture(event.pointerId); + }; + + private readonly handlePointerUp = (event: PointerEvent) => { + if (this.chargeStart === null) return; + const now = performance.now(); + const power = this.power(now); + this.chargeStart = null; + if (this.canvas.hasPointerCapture(event.pointerId)) { + this.canvas.releasePointerCapture(event.pointerId); + } + const speed = shotSpeed(power); + const finalShot = this.game.objectBallsLeft() === 0; + if (!this.game.shoot(this.aimAngle, speed)) return; + this.finalShot = finalShot; + this.audio.cue(power); + const cue = this.game.ball(0); + if (cue) this.fx.cueStrike(cue, this.aimAngle, power); + this.emitHud(now, true); + }; + + private readonly handlePointerCancel = () => { + this.chargeStart = null; + }; + + private readonly handleContextMenu = (event: Event) => { + event.preventDefault(); + }; + + private readonly tick = (time: number) => { + this.frame = requestAnimationFrame(this.tick); + const seconds = this.lastFrame === 0 ? 0 : Math.min(0.05, (time - this.lastFrame) / 1000); + this.lastFrame = time; + + // A hit-stop freezes everything for a beat; slow motion stretches the final 8. + let simSeconds = seconds * this.timeScale; + let frozenSeconds = seconds - simSeconds; + if (this.fx.hitStop > 0) { + const stop = Math.min(this.fx.hitStop, seconds); + this.fx.hitStop -= stop; + simSeconds = 0; + frozenSeconds = seconds; + } + if (this.clockStart !== null && this.clockEnd === null) this.frozenMs += frozenSeconds * 1000; + + const phase = this.game.phase; + const breakShot = this.game.isBreak; + const before = new Map(); + for (const ball of this.game.balls) + if (ball.onTable) before.set(ball.id, { x: ball.x, y: ball.y }); + const events: PhysicsEvent[] = []; + this.game.advance(simSeconds, events); + this.trackRolling(before, simSeconds); + this.playEvents(events, time / 1000); + this.fx.onEvents(events, this.game.balls, breakShot); + if (this.game.phase !== phase) { + this.nap.commit(); + if (phase === "rolling") this.calloutShot(); + if (this.game.phase === "cleared") { + this.clockEnd = time; + this.fx.celebrate(this.game.calledPocket); + this.recordRun(time); + } + // The clock starts once the break settles. + if (!this.game.isBreak && this.clockStart === null) this.clockStart = time; + this.emitHud(time, true); + } + if (simSeconds > 0 || this.game.phase === "aiming") this.trailMagic(time); + this.updateSlowMotion(seconds); + this.fx.update(simSeconds === 0 ? 0 : Math.max(simSeconds, seconds * 0.5)); + this.sinking = this.sinking.filter((sinking) => time / 1000 - sinking.start < SINK_SECONDS); + this.callouts.update(seconds); + + drawScene(this.context, this.staticLayer, this.scale, { + game: this.game, + aimAngle: this.aimAngle, + power: this.chargeStart === null ? null : this.power(time), + hoverPocket: this.pocketAt(this.pointer), + sinking: this.sinking, + now: time / 1000, + sprites: this.sprites, + nap: this.nap, + fx: this.fx, + shake: this.fx.shakeOffset(), + vignette: Math.min(1, (1 - this.timeScale) / (1 - SLOW_MOTION)), + cueStyle: this.cueStyle(), + }); + tableTransform(this.context, this.scale); + const score = this.scoreView(time); + if (this.labels && this.game.phase === "aiming") { + drawChalkHints(this.context, score, this.labels, time / 1000); + } + drawScoreboard(this.context, score); + this.callouts.draw(this.context); + if (time - this.lastHudAt > HUD_INTERVAL_MS) this.emitHud(time, false); + }; + + /** Rolls each moving ball's sprite and brushes the cloth along its path. */ + private trackRolling(before: ReadonlyMap, seconds: number): void { + if (seconds === 0) return; + for (const ball of this.game.balls) { + const start = before.get(ball.id); + if (!start || !ball.onTable) continue; + const dx = ball.x - start.x; + const dy = ball.y - start.y; + const distance = Math.hypot(dx, dy); + // A respot jumps the ball; it didn't roll there. + if (distance < 1e-5 || distance > 0.2) continue; + this.sprites.roll(ball.id, dx, dy); + this.nap.stamp(start.x, start.y, ball.x, ball.y); + } + } + + /** Says what a shot's foul cost, where it happened. */ + private calloutShot(): void { + const shot = this.game.lastShot; + const labels = this.labels; + const scratchPocket = this.scratchPocket; + this.scratchPocket = null; + if (!shot?.foul || !labels) return; + const seconds = shot.forgiven ? 0 : FOUL_PENALTY_SECONDS[shot.foul]; + const detail = shot.forgiven ? labels.freeMiss : labels.penalty(seconds); + const color = shot.forgiven ? CALL_COLOR : FOUL_COLOR; + const pocket = POCKETS.find((candidate) => candidate.id === scratchPocket); + const cue = this.game.ball(0); + const eight = this.game.ball(EIGHT); + switch (shot.foul) { + case "scratch": + if (pocket) this.callouts.add(labels.scratch, pocket.x, pocket.y, color, detail); + break; + case "noContact": + if (cue) this.callouts.add(labels.miss, cue.x, cue.y - 0.06, color, detail); + break; + case "early8": + case "wrong8": + case "scratch8": { + const text = + shot.foul === "early8" + ? labels.early8 + : shot.foul === "wrong8" + ? labels.wrong8 + : labels.scratch8; + if (eight) this.callouts.add(text, eight.x, eight.y - 0.06, color, detail); + break; + } + } + } + + private scoreView(now: number): ScoreView { + return { + totalMs: this.totalMs(now), + penaltySeconds: this.game.penaltySeconds, + shots: this.game.shots, + bestMs: this.todayRuns[0]?.totalMs ?? null, + goldenShots: this.game.goldenShots, + isBreak: this.game.isBreak, + callNeeded: this.game.needsCall() && this.game.calledPocket === null, + }; + } + + private recordRun(now: number): void { + const run: BilliardsRun = { + day: this.day, + totalMs: Math.round(this.totalMs(now)), + penaltySeconds: this.game.penaltySeconds, + shots: this.game.shots, + finishedAt: new Date().toISOString(), + }; + this.runs = saveRun(this.runs, run); + const before = this.unlocked; + this.unlocked = unlockedSkins(this.runs); + const newSkins = [...this.unlocked].filter((id) => !before.has(id)); + this.todayRuns = runsOn(this.runs, this.day); + this.result = { + run, + rankToday: this.todayRuns.indexOf(run) + 1, + medal: medalFor(run.totalMs), + newSkins, + }; + } + + private totalMs(now: number): number { + const clock = + this.clockStart === null ? 0 : (this.clockEnd ?? now) - this.clockStart - this.frozenMs; + return clock + this.game.penaltySeconds * 1000; + } + + private updateSlowMotion(seconds: number): void { + let target = 1; + const eight = this.game.ball(EIGHT); + const pocket = POCKETS.find((candidate) => candidate.id === this.game.calledPocket); + if (this.finalShot && this.game.phase === "rolling" && eight?.onTable && pocket) { + const dx = pocket.x - eight.x; + const dy = pocket.y - eight.y; + const distance = Math.hypot(dx, dy); + const speed = Math.hypot(eight.vx, eight.vy); + const heading = speed > 0 ? (dx * eight.vx + dy * eight.vy) / (distance * speed) : 0; + if (speed > 0.05 && distance < 0.35 && heading > 0.85) target = SLOW_MOTION; + } + this.timeScale += (target - this.timeScale) * Math.min(1, seconds * 8); + if (Math.abs(this.timeScale - target) < 0.01) this.timeScale = target; + } + + private playEvents(events: ReadonlyArray, now: number): void { + const clicks: number[] = []; + const thuds: number[] = []; + for (const event of events) { + switch (event.kind) { + case "ball": + clicks.push(event.speed); + break; + case "cushion": + thuds.push(event.speed); + break; + case "touch": + break; + case "pocket": { + if (event.ball === 0) this.scratchPocket = event.pocket; + this.audio.pocket(); + const pocket = POCKETS[event.pocket]; + if (pocket) { + this.sinking.push({ ball: event.ball, x: event.x, y: event.y, pocket, start: now }); + } + break; + } + case "powerUp": { + const ring = this.game.rings.find((candidate) => candidate.id === event.ring); + if (!ring) break; + this.audio.powerUp(); + this.fx.powerBurst(ring.x, ring.y, POWER_COLORS[ring.kind]); + if (this.labels) { + const { labels } = this; + const [name, hint] = + ring.kind === "wand" + ? [labels.wand, labels.wandHint] + : ring.kind === "golden" + ? [labels.golden, labels.goldenHint] + : [labels.glow, labels.glowHint]; + this.callouts.add(name, ring.x, ring.y - 0.05, `rgb(${POWER_COLORS[ring.kind]})`, hint); + } + this.emitHud(now * 1000, true); + break; + } + case "guide": { + const ball = this.game.ball(event.ball); + const power = this.game.activePower; + if (!ball || !power) break; + this.audio.guide(); + this.fx.powerBurst(ball.x, ball.y, POWER_COLORS[power]); + break; + } + } + } + // A break makes dozens of contacts in one frame; the loudest few carry it. + for (const speed of clicks.sort((a, b) => b - a).slice(0, 3)) this.audio.click(speed); + for (const speed of thuds.sort((a, b) => b - a).slice(0, 2)) this.audio.cushion(speed); + } + + /** Sparks behind balls a power-up is steering, and off a magic stick while aiming. */ + private trailMagic(now: number): void { + const power = this.game.activePower; + for (const ball of this.game.balls) { + if (ball.onTable && ball.guidedTo !== null && power) { + this.fx.trail(ball.x, ball.y, POWER_COLORS[power]); + } + } + const cue = this.game.ball(0); + if (power === "glow" && cue?.onTable && this.game.phase === "rolling") { + this.fx.trail(cue.x, cue.y, POWER_COLORS.glow); + } + const style = this.cueStyle(); + const sparks = + style === "wand" || style === "golden" || style === "glow" ? POWER_COLORS[style] : null; + if (sparks && this.game.phase === "aiming" && cue?.onTable && Math.random() < 0.35) { + const tip = cueTip(cue, this.aimAngle, this.power(now)); + this.fx.trail(tip.x, tip.y, sparks); + } + } + + private cueStyle(): CueStyle { + if (this.game.armed) return this.game.armed; + return this.game.goldenShots > 0 ? "golden" : this.skin; + } + + /** Picks a stick skin; only unlocked ones take. */ + setSkin(id: SkinId): void { + if (!this.unlocked.has(id)) return; + this.skin = id; + saveSkin(id); + this.emitHud(performance.now(), true); + } + + private emitHud(now: number, force: boolean): void { + const game = this.game; + const hud: BilliardsHud = { + phase: game.phase, + isBreak: game.isBreak, + shots: game.shots, + penaltySeconds: game.penaltySeconds, + totalMs: this.totalMs(now), + needsCall: game.needsCall(), + calledPocket: game.calledPocket, + foul: game.phase === "rolling" ? null : (game.lastShot?.foul ?? null), + forgiven: game.lastShot?.forgiven ?? false, + blocked: now < this.blockedUntil, + day: this.day, + todayRuns: this.todayRuns, + result: this.result, + armed: game.armed, + goldenShots: game.goldenShots, + skin: this.skin, + unlockedSkins: this.unlocked, + }; + this.lastHudAt = now; + const last = this.lastHud; + const changed = + !last || + (Object.keys(hud) as Array).some((key) => + key === "totalMs" + ? Math.floor(hud.totalMs / 1000) !== Math.floor(last.totalMs / 1000) + : hud[key] !== last[key], + ); + if (!force && !changed) return; + this.lastHud = hud; + this.onHud(hud); + } +} diff --git a/apps/web/src/components/billiards/billiardsSkins.test.ts b/apps/web/src/components/billiards/billiardsSkins.test.ts new file mode 100644 index 0000000000..b02af74fbe --- /dev/null +++ b/apps/web/src/components/billiards/billiardsSkins.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vite-plus/test"; + +import type { BilliardsRun } from "./billiardsRecords.ts"; +import { unlockedSkins } from "./billiardsSkins.ts"; + +const run = (totalMs: number): BilliardsRun => ({ + day: "2026-11-26", + totalMs, + penaltySeconds: 0, + shots: 20, + finishedAt: "2026-11-26T12:00:00.000Z", +}); + +describe("unlockedSkins", () => { + it("starts with only the classic stick", () => { + expect([...unlockedSkins([])]).toEqual(["classic"]); + }); + + it("unlocks Ari for any cleared table, and each medal's stick with every lower one", () => { + expect([...unlockedSkins([run(400_000)])]).toEqual(["classic", "ari"]); + expect([...unlockedSkins([run(400_000), run(200_000)])]).toEqual([ + "classic", + "ari", + "copper", + "chrome", + ]); + expect(unlockedSkins([run(100_000)]).has("ember")).toBe(true); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsSkins.ts b/apps/web/src/components/billiards/billiardsSkins.ts new file mode 100644 index 0000000000..7ad9ad9bfc --- /dev/null +++ b/apps/web/src/components/billiards/billiardsSkins.ts @@ -0,0 +1,79 @@ +import { medalFor, type BilliardsRun, type Medal } from "./billiardsRecords.ts"; + +// Stick skins: looks earned with results on this machine. A power-up's look still wins while it's +// armed, so a skin never hides that one is ready. + +const STORAGE_KEY = "ari-billiards-skin"; + +export type SkinId = "classic" | "ari" | "copper" | "chrome" | "ember"; + +export interface Skin { + readonly id: SkinId; + /** What earns it: nothing, any cleared table, or a medal. */ + readonly unlock: null | "clear" | Medal; + /** A CSS gradient for the picker swatch. */ + readonly swatch: string; +} + +export const SKINS: ReadonlyArray = [ + { + id: "classic", + unlock: null, + swatch: "linear-gradient(90deg, #120a06, #2a1810 35%, #d4af37 37%, #b8875a 40%, #e0c69c)", + }, + { + id: "ari", + unlock: "clear", + swatch: "linear-gradient(90deg, #2a0f42, #5b2a86 45%, #ffc83d 47%, #5b2a86 50%, #8a4fc0)", + }, + { + id: "copper", + unlock: "bronze", + swatch: "linear-gradient(90deg, #5a2e14, #b87333 30%, #e8a476 50%, #b87333 70%, #f3c6a0)", + }, + { + id: "chrome", + unlock: "silver", + swatch: "linear-gradient(90deg, #3c434c, #9aa4b0 30%, #f4f7fa 50%, #9aa4b0 70%, #dfe5ec)", + }, + { + id: "ember", + unlock: "gold", + swatch: "linear-gradient(90deg, #120604, #3a1408 30%, #ff7a1a 45%, #3a1408 60%, #ffb347)", + }, +]; + +const MEDAL_RANK: Readonly> = { bronze: 1, silver: 2, gold: 3 }; + +/** The skins these runs have earned. */ +export function unlockedSkins(runs: ReadonlyArray): ReadonlySet { + let best = 0; + for (const run of runs) { + const medal = medalFor(run.totalMs); + if (medal) best = Math.max(best, MEDAL_RANK[medal]); + } + return new Set( + SKINS.filter( + (skin) => + skin.unlock === null || + (skin.unlock === "clear" ? runs.length > 0 : best >= MEDAL_RANK[skin.unlock]), + ).map((skin) => skin.id), + ); +} + +export function loadSkin(): SkinId { + try { + const stored = window.localStorage.getItem(STORAGE_KEY); + return SKINS.find((skin) => skin.id === stored)?.id ?? "classic"; + } catch { + return "classic"; + } +} + +export function saveSkin(id: SkinId): void { + try { + window.localStorage.setItem(STORAGE_KEY, id); + } catch { + // Not saved; the choice still holds for this game. + } +} diff --git a/apps/web/src/components/billiards/billiardsTable.ts b/apps/web/src/components/billiards/billiardsTable.ts new file mode 100644 index 0000000000..6426858f7a --- /dev/null +++ b/apps/web/src/components/billiards/billiardsTable.ts @@ -0,0 +1,82 @@ +// Table geometry in table units: the cloth is 1 wide and 2 long, top-down and portrait. +// The head (where the cue ball starts) is at the bottom, the rack at the top. + +export const TABLE_WIDTH = 1; +export const TABLE_LENGTH = 2; +export const BALL_RADIUS = 0.0225; +/** Cushion plus wood beyond the cloth edge. */ +export const RAIL_WIDTH = 0.075; +const CUSHION_DEPTH = 0.036; + +export interface Point { + readonly x: number; + readonly y: number; +} + +export const HEAD_SPOT: Point = { x: 0.5, y: 1.5 }; +export const FOOT_SPOT: Point = { x: 0.5, y: 0.5 }; + +export interface Pocket { + readonly id: number; + readonly x: number; + readonly y: number; + /** A ball whose centre comes this close drops. */ + readonly radius: number; +} + +export const POCKETS: ReadonlyArray = [ + { id: 0, x: -0.014, y: -0.014, radius: 0.05 }, + { id: 1, x: 1.014, y: -0.014, radius: 0.05 }, + { id: 2, x: -0.034, y: 1, radius: 0.046 }, + { id: 3, x: 1.034, y: 1, radius: 0.046 }, + { id: 4, x: -0.014, y: 2.014, radius: 0.05 }, + { id: 5, x: 1.014, y: 2.014, radius: 0.05 }, +]; + +// Where a cushion nose ends next to a corner, and half the side pocket opening. +const CORNER_MOUTH = 0.075; +const SIDE_MOUTH = 0.05; +const D = CUSHION_DEPTH; + +/** + * Each cushion as [jaw back, nose start, nose end, jaw back]: drawn as one polygon, and its three + * edges facing the cloth are what balls bounce off. + */ +export const CUSHIONS: ReadonlyArray> = (() => { + const top: Point[] = [ + { x: CORNER_MOUTH - 0.027, y: -D }, + { x: CORNER_MOUTH, y: 0 }, + { x: 1 - CORNER_MOUTH, y: 0 }, + { x: 1 - CORNER_MOUTH + 0.027, y: -D }, + ]; + const leftUpper: Point[] = [ + { x: -D, y: CORNER_MOUTH - 0.027 }, + { x: 0, y: CORNER_MOUTH }, + { x: 0, y: 1 - SIDE_MOUTH }, + { x: -0.045, y: 1 - SIDE_MOUTH + 0.012 }, + ]; + const leftLower: Point[] = [ + { x: -0.045, y: 1 + SIDE_MOUTH - 0.012 }, + { x: 0, y: 1 + SIDE_MOUTH }, + { x: 0, y: 2 - CORNER_MOUTH }, + { x: -D, y: 2 - CORNER_MOUTH + 0.027 }, + ]; + const mirrorX = (points: Point[]) => points.map((p) => ({ x: TABLE_WIDTH - p.x, y: p.y })); + const mirrorY = (points: Point[]) => points.map((p) => ({ x: p.x, y: TABLE_LENGTH - p.y })); + return [top, mirrorY(top), leftUpper, leftLower, mirrorX(leftUpper), mirrorX(leftLower)]; +})(); + +export interface Segment { + readonly a: Point; + readonly b: Point; +} + +export const CUSHION_SEGMENTS: ReadonlyArray = CUSHIONS.flatMap((polygon) => { + const segments: Segment[] = []; + for (let i = 0; i < polygon.length - 1; i++) { + const a = polygon[i]; + const b = polygon[i + 1]; + if (a && b) segments.push({ a, b }); + } + return segments; +}); diff --git a/apps/web/src/components/billiards/billiardsThreadAlerts.test.ts b/apps/web/src/components/billiards/billiardsThreadAlerts.test.ts new file mode 100644 index 0000000000..646a17c7c9 --- /dev/null +++ b/apps/web/src/components/billiards/billiardsThreadAlerts.test.ts @@ -0,0 +1,57 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { describe, expect, it } from "vite-plus/test"; + +import { snapshotThreads, threadAlerts } from "./billiardsThreadAlerts.ts"; + +function shell( + id: string, + state: { + running?: boolean; + completedAt?: string | null; + needsInput?: boolean; + subagent?: boolean; + runStatus?: string; + } = {}, +): EnvironmentThreadShell { + return { + environmentId: "env", + id, + title: id, + lineage: { relationshipToParent: state.subagent ? "subagent" : null, sideChat: false }, + runtime: state.running ? { status: "running" } : { status: "completed" }, + latestRun: + state.completedAt === undefined + ? null + : { status: state.runStatus ?? "completed", completedAt: state.completedAt }, + hasPendingApprovals: false, + hasPendingUserInput: state.needsInput ?? false, + pendingSubagentRequest: null, + } as unknown as EnvironmentThreadShell; +} + +describe("threadAlerts", () => { + it("says nothing about threads that were already done when the game opened", () => { + const threads = [shell("a", { completedAt: "2026-11-26T10:00:00Z" })]; + expect(threadAlerts(snapshotThreads(threads), threads)).toEqual([]); + }); + + it("reports a thread that finishes while playing", () => { + const baseline = snapshotThreads([shell("a", { running: true, completedAt: null })]); + const alerts = threadAlerts(baseline, [shell("a", { completedAt: "2026-11-26T10:05:00Z" })]); + expect(alerts.map((alert) => [alert.thread.id, alert.kind])).toEqual([["a", "done"]]); + }); + + it("reports a thread that starts needing you, but not a subagent or a stopped run", () => { + const baseline = snapshotThreads([ + shell("a", { running: true }), + shell("b", { running: true, subagent: true }), + shell("c", { running: true }), + ]); + const alerts = threadAlerts(baseline, [ + shell("a", { running: true, needsInput: true }), + shell("b", { completedAt: "2026-11-26T10:05:00Z", subagent: true }), + shell("c", { completedAt: "2026-11-26T10:05:00Z", runStatus: "interrupted" }), + ]); + expect(alerts.map((alert) => [alert.thread.id, alert.kind])).toEqual([["a", "needsYou"]]); + }); +}); diff --git a/apps/web/src/components/billiards/billiardsThreadAlerts.ts b/apps/web/src/components/billiards/billiardsThreadAlerts.ts new file mode 100644 index 0000000000..296f18c02f --- /dev/null +++ b/apps/web/src/components/billiards/billiardsThreadAlerts.ts @@ -0,0 +1,73 @@ +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/models"; +import { isListedThreadLineage } from "@t3tools/contracts"; + +// While the game is open, it shows a bubble for each thread that finished or started needing +// you since the game opened, so playing never hides an agent that's done. + +export type ThreadAlertKind = "done" | "needsYou"; + +export interface ThreadAlert { + readonly key: string; + readonly thread: EnvironmentThreadShell; + readonly kind: ThreadAlertKind; +} + +interface ThreadMark { + readonly completedAt: string | null; + readonly needsYou: boolean; +} + +export type ThreadBaseline = ReadonlyMap; + +function threadAlertKey(thread: EnvironmentThreadShell): string { + return `${thread.environmentId}:${thread.id}`; +} + +function needsYou(thread: EnvironmentThreadShell): boolean { + return ( + thread.hasPendingApprovals || + thread.hasPendingUserInput || + (thread.pendingSubagentRequest ?? null) !== null + ); +} + +function finishedAt(thread: EnvironmentThreadShell): string | null { + const run = thread.latestRun; + if (!run?.completedAt || run.status === "interrupted" || run.status === "cancelled") return null; + return threadRuntimeIsActive(thread.runtime) ? null : run.completedAt; +} + +/** Where every thread stands when the game opens. */ +export function snapshotThreads(threads: ReadonlyArray): ThreadBaseline { + return new Map( + threads.map((thread) => [ + threadAlertKey(thread), + { completedAt: finishedAt(thread), needsYou: needsYou(thread) }, + ]), + ); +} + +/** Listed threads that finished, or started needing you, since `baseline`. */ +export function threadAlerts( + baseline: ThreadBaseline, + threads: ReadonlyArray, +): ThreadAlert[] { + const alerts: ThreadAlert[] = []; + for (const thread of threads) { + if (!isListedThreadLineage(thread.lineage)) continue; + const key = threadAlertKey(thread); + const before = baseline.get(key); + if (needsYou(thread)) { + if (!before?.needsYou) alerts.push({ key, thread, kind: "needsYou" }); + continue; + } + const completedAt = finishedAt(thread); + if (completedAt !== null && completedAt !== before?.completedAt) { + alerts.push({ key, thread, kind: "done" }); + } + } + return alerts; +} diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index 0ddb535296..3478112260 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -1,7 +1,7 @@ import { ArrowLeftIcon, ArrowRightIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react"; -import type { ReactNode } from "react"; +import type { MouseEvent, ReactNode } from "react"; import { T, useGT } from "gt-react"; -import { memo } from "react"; +import { lazy, memo, Suspense, useState } from "react"; import { Link, useLocation, useNavigate } from "@tanstack/react-router"; import { useAtomValue } from "@effect/atom-react"; @@ -43,6 +43,9 @@ import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUp import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; +// Loaded only when someone triple-clicks the logo. +const BilliardsOverlay = lazy(() => import("../billiards/BilliardsOverlay")); + export const SidebarChromeHeader = memo(function SidebarChromeHeader({ isElectron, }: { @@ -169,17 +172,32 @@ function HistoryNavigationButton({ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) { const gt = useGT(); + const [billiardsOpen, setBilliardsOpen] = useState(false); + // A triple-click opens the billiards easter egg; a single click still goes home. + const openBilliardsOnTripleClick = (event: MouseEvent) => { + if (event.detail < 3) return; + event.preventDefault(); + setBilliardsOpen(true); + }; return ( - - - + <> + + + + {billiardsOpen ? ( + + setBilliardsOpen(false)} /> + + ) : null} + ); } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 9e8e552d4a..ce62571c69 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3111,6 +3111,49 @@ "ff5f1c260e87ecde": "Prüfe, ob das Backend von diesem Browser aus erreichbar ist, CORS für gehostete Clients unterstützt und über HTTPS ausgeliefert wird, wenn du diese Seite über HTTPS öffnest.", "08570ee0982df89d": "Wird gekoppelt...", "3bbae7c96b6cbfc3": "App öffnen", + "0bc152a492a12716": "Weiße versenkt", + "aa2534f03870a3f9": "Keine Kugel getroffen", + "e13bcb690bb9c28f": "Einmal gratis", + "3d83bccbd9e6b227": "8 zu früh", + "163440207bcb77bb": "Falsches Loch", + "24517a21c5ca36f7": "Weiße mit der 8", + "e353b6587c16a231": "Zauberstab", + "c174eedba0edabdc": "Goldqueue", + "e3114242f399e91b": "Leuchtqueue", + "59a3f31ee049d0f5": "Die erste getroffene Kugel fällt", + "b6ab17c9f0d8fece": "Volle Sicht für {count} Stöße", + "597ea9e53fc7cb87": "Bricht durch {count} Kugeln", + "3b3a060f716e1b53": "Klick auf ein Loch, um die 8 anzusagen", + "c655975d03078dd5": "Erst ein Loch ansagen", + "3dfd844f131e4d0a": "Halten zum Aufladen, loslassen zum Stoßen", + "11b40436e8016644": "Shift zielt feiner, Esc schließt", + "c8bf7e23d2bc15ae": "Fertig", + "d25661576338fcf0": "Braucht dich", + "209d36a8ffe3791c": "Klassisch", + "88b909e76e754bef": "Kupfer", + "9ca687520bab7394": "Chrom", + "00f65fd8e47554b2": "Glut", + "637a3c803f6578d7": "Räume einen Tisch ab", + "af4bf1e680b765c6": "Gewinne eine Bronzemedaille", + "52074a21b1859001": "Gewinne eine Silbermedaille", + "ef059864c4430c66": "Gewinne eine Goldmedaille", + "ec925d6946a88b5b": "Queue wählen", + "152ec44c76dca1ec": "Queue", + "4fa58c8eb16781d2": "Neues Queue freigeschaltet: {name}", + "743592404305841f": "Goldmedaille", + "aa1a6773ceaf9223": "Silbermedaille", + "b2c0da632a0a1b98": "Bronzemedaille", + "a8bf31becdf2dc58": "Nächstes Ziel: Gold unter {time}", + "853a57697469a28d": "Nächstes Ziel: Silber unter {time}", + "344ff8f2b12b3d70": "Nächstes Ziel: Bronze unter {time}", + "67f492a1bb0c8673": "Neue Tagesbestzeit!", + "60f19313f8c6f1a2": "Heute auf diesem Computer", + "36d880c1abd2d448": "+{seconds} s", + "412cfbefb305eb90": "Billard", + "b2be70822d55f16a": "Öffnen", + "52499724d03777c6": "Tisch abgeräumt", + "9fab80fe09b3dacf": "{clock} gespielt, +{seconds} s Strafzeit, {shots} Stöße", + "03b3f43d7b61d793": "Nochmal spielen", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} Min. {seconds} s", "f2a955905704b91d": "{hours} Std. {minutes} Min.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 7a86e077d8..80f68e5143 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3110,6 +3110,49 @@ "ff5f1c260e87ecde": "Verify the backend is reachable from this browser, supports CORS for hosted clients, and is served over HTTPS when opening this page from HTTPS.", "08570ee0982df89d": "Pairing...", "3bbae7c96b6cbfc3": "Open app", + "0bc152a492a12716": "Scratch", + "aa2534f03870a3f9": "No ball hit", + "e13bcb690bb9c28f": "Free this once", + "3d83bccbd9e6b227": "8 too early", + "163440207bcb77bb": "Wrong pocket", + "24517a21c5ca36f7": "Scratch on the 8", + "e353b6587c16a231": "Wand", + "c174eedba0edabdc": "Golden cue", + "e3114242f399e91b": "Glow cue", + "59a3f31ee049d0f5": "The first ball you hit drops", + "b6ab17c9f0d8fece": "Full sight for {count} shots", + "597ea9e53fc7cb87": "Bursts through {count} balls", + "3b3a060f716e1b53": "Click a pocket to call the 8", + "c655975d03078dd5": "Call a pocket first", + "3dfd844f131e4d0a": "Hold to charge, release to shoot", + "11b40436e8016644": "Shift for fine aim, Esc to close", + "c8bf7e23d2bc15ae": "Done", + "d25661576338fcf0": "Needs you", + "209d36a8ffe3791c": "Classic", + "88b909e76e754bef": "Copper", + "9ca687520bab7394": "Chrome", + "00f65fd8e47554b2": "Ember", + "637a3c803f6578d7": "Clear a table", + "af4bf1e680b765c6": "Win a bronze medal", + "52074a21b1859001": "Win a silver medal", + "ef059864c4430c66": "Win a gold medal", + "ec925d6946a88b5b": "Choose a stick", + "152ec44c76dca1ec": "Stick", + "4fa58c8eb16781d2": "New stick unlocked: {name}", + "743592404305841f": "Gold medal", + "aa1a6773ceaf9223": "Silver medal", + "b2c0da632a0a1b98": "Bronze medal", + "a8bf31becdf2dc58": "Next: gold under {time}", + "853a57697469a28d": "Next: silver under {time}", + "344ff8f2b12b3d70": "Next: bronze under {time}", + "67f492a1bb0c8673": "New best today!", + "60f19313f8c6f1a2": "Today on this computer", + "36d880c1abd2d448": "+{seconds} s", + "412cfbefb305eb90": "Billiards", + "b2be70822d55f16a": "Open", + "52499724d03777c6": "Table cleared", + "9fab80fe09b3dacf": "{clock} played, +{seconds} s penalties, {shots} shots", + "03b3f43d7b61d793": "Play again", "49cc06e79f21f85a": "{seconds}s", "8603d41c52392f1d": "{minutes}m {seconds}s", "f2a955905704b91d": "{hours}h {minutes}m", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 0cd18d2f03..3e4797102a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3110,6 +3110,49 @@ "ff5f1c260e87ecde": "Comprueba que se puede acceder al backend desde este navegador, que admite CORS para clientes alojados y que se sirve por HTTPS cuando abres esta página desde HTTPS.", "08570ee0982df89d": "Emparejando...", "3bbae7c96b6cbfc3": "Abrir app", + "0bc152a492a12716": "Blanca entronerada", + "aa2534f03870a3f9": "Ninguna bola tocada", + "e13bcb690bb9c28f": "Gratis esta vez", + "3d83bccbd9e6b227": "8 demasiado pronto", + "163440207bcb77bb": "Tronera equivocada", + "24517a21c5ca36f7": "Blanca con la 8", + "e353b6587c16a231": "Varita", + "c174eedba0edabdc": "Taco dorado", + "e3114242f399e91b": "Taco brillante", + "59a3f31ee049d0f5": "La primera bola que toques cae", + "b6ab17c9f0d8fece": "Visión completa durante {count} tiros", + "597ea9e53fc7cb87": "Atraviesa {count} bolas", + "3b3a060f716e1b53": "Haz clic en una tronera para cantar la 8", + "c655975d03078dd5": "Primero canta una tronera", + "3dfd844f131e4d0a": "Mantén para cargar, suelta para tirar", + "11b40436e8016644": "Mayús apunta más fino, Esc cierra", + "c8bf7e23d2bc15ae": "Listo", + "d25661576338fcf0": "Te necesita", + "209d36a8ffe3791c": "Clásico", + "88b909e76e754bef": "Cobre", + "9ca687520bab7394": "Cromo", + "00f65fd8e47554b2": "Brasa", + "637a3c803f6578d7": "Limpia una mesa", + "af4bf1e680b765c6": "Gana una medalla de bronce", + "52074a21b1859001": "Gana una medalla de plata", + "ef059864c4430c66": "Gana una medalla de oro", + "ec925d6946a88b5b": "Elegir un taco", + "152ec44c76dca1ec": "Taco", + "4fa58c8eb16781d2": "Nuevo taco desbloqueado: {name}", + "743592404305841f": "Medalla de oro", + "aa1a6773ceaf9223": "Medalla de plata", + "b2c0da632a0a1b98": "Medalla de bronce", + "a8bf31becdf2dc58": "Siguiente: oro en menos de {time}", + "853a57697469a28d": "Siguiente: plata en menos de {time}", + "344ff8f2b12b3d70": "Siguiente: bronce en menos de {time}", + "67f492a1bb0c8673": "¡Nuevo récord del día!", + "60f19313f8c6f1a2": "Hoy en este ordenador", + "36d880c1abd2d448": "+{seconds} s", + "412cfbefb305eb90": "Billar", + "b2be70822d55f16a": "Abrir", + "52499724d03777c6": "Mesa limpia", + "9fab80fe09b3dacf": "{clock} de juego, +{seconds} s de penalización, {shots} tiros", + "03b3f43d7b61d793": "Jugar otra vez", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} min {seconds} s", "f2a955905704b91d": "{hours} h {minutes} min", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f31ae29b98..26a7ef60a0 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3110,6 +3110,49 @@ "ff5f1c260e87ecde": "Vérifiez que le backend est joignable depuis ce navigateur, qu’il prend en charge CORS pour les clients hébergés et qu’il est servi en HTTPS si cette page est ouverte en HTTPS.", "08570ee0982df89d": "Appairage...", "3bbae7c96b6cbfc3": "Ouvrir l’app", + "0bc152a492a12716": "Blanche empochée", + "aa2534f03870a3f9": "Aucune bille touchée", + "e13bcb690bb9c28f": "Gratuit cette fois", + "3d83bccbd9e6b227": "8 trop tôt", + "163440207bcb77bb": "Mauvaise poche", + "24517a21c5ca36f7": "Blanche avec la 8", + "e353b6587c16a231": "Baguette", + "c174eedba0edabdc": "Queue dorée", + "e3114242f399e91b": "Queue lumineuse", + "59a3f31ee049d0f5": "La première bille touchée tombe", + "b6ab17c9f0d8fece": "Vision complète pour {count} coups", + "597ea9e53fc7cb87": "Traverse {count} billes", + "3b3a060f716e1b53": "Cliquez sur une poche pour annoncer la 8", + "c655975d03078dd5": "Annoncez d’abord une poche", + "3dfd844f131e4d0a": "Maintenez pour charger, relâchez pour tirer", + "11b40436e8016644": "Maj vise plus finement, Échap ferme", + "c8bf7e23d2bc15ae": "Terminé", + "d25661576338fcf0": "Vous attend", + "209d36a8ffe3791c": "Classique", + "88b909e76e754bef": "Cuivre", + "9ca687520bab7394": "Chrome", + "00f65fd8e47554b2": "Braise", + "637a3c803f6578d7": "Nettoyez une table", + "af4bf1e680b765c6": "Gagnez une médaille de bronze", + "52074a21b1859001": "Gagnez une médaille d’argent", + "ef059864c4430c66": "Gagnez une médaille d’or", + "ec925d6946a88b5b": "Choisir une queue", + "152ec44c76dca1ec": "Queue", + "4fa58c8eb16781d2": "Nouvelle queue débloquée : {name}", + "743592404305841f": "Médaille d’or", + "aa1a6773ceaf9223": "Médaille d’argent", + "b2c0da632a0a1b98": "Médaille de bronze", + "a8bf31becdf2dc58": "Prochain objectif : or sous {time}", + "853a57697469a28d": "Prochain objectif : argent sous {time}", + "344ff8f2b12b3d70": "Prochain objectif : bronze sous {time}", + "67f492a1bb0c8673": "Nouveau record du jour !", + "60f19313f8c6f1a2": "Aujourd’hui sur cet ordinateur", + "36d880c1abd2d448": "+{seconds} s", + "412cfbefb305eb90": "Billard", + "b2be70822d55f16a": "Ouvrir", + "52499724d03777c6": "Table nettoyée", + "9fab80fe09b3dacf": "{clock} de jeu, +{seconds} s de pénalités, {shots} coups", + "03b3f43d7b61d793": "Rejouer", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} min {seconds} s", "f2a955905704b91d": "{hours} h {minutes} min", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 633f52eb81..b4ba418791 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3108,6 +3108,49 @@ "ff5f1c260e87ecde": "バックエンドがこのブラウザーから到達可能で、ホスト型クライアント向けに CORS をサポートしていること、また HTTPS のページから開く場合は HTTPS で提供されていることを確認してください。", "08570ee0982df89d": "ペアリングしています...", "3bbae7c96b6cbfc3": "アプリを開く", + "0bc152a492a12716": "スクラッチ", + "aa2534f03870a3f9": "どのボールにも当たらず", + "e13bcb690bb9c28f": "今回は無料", + "3d83bccbd9e6b227": "8番が早すぎ", + "163440207bcb77bb": "違うポケット", + "24517a21c5ca36f7": "8番と一緒にスクラッチ", + "e353b6587c16a231": "ワンド", + "c174eedba0edabdc": "ゴールドキュー", + "e3114242f399e91b": "光るキュー", + "59a3f31ee049d0f5": "最初に当てたボールが落ちる", + "b6ab17c9f0d8fece": "{count}ショットの間ラインが全部見える", + "597ea9e53fc7cb87": "{count}個のボールを突き抜ける", + "3b3a060f716e1b53": "ポケットをクリックして8番を指定", + "c655975d03078dd5": "先にポケットを指定", + "3dfd844f131e4d0a": "長押しでため、離して打つ", + "11b40436e8016644": "Shiftで細かく狙う、Escで閉じる", + "c8bf7e23d2bc15ae": "完了", + "d25661576338fcf0": "対応待ち", + "209d36a8ffe3791c": "クラシック", + "88b909e76e754bef": "カッパー", + "9ca687520bab7394": "クローム", + "00f65fd8e47554b2": "エンバー", + "637a3c803f6578d7": "テーブルを1回クリア", + "af4bf1e680b765c6": "銅メダルを獲得", + "52074a21b1859001": "銀メダルを獲得", + "ef059864c4430c66": "金メダルを獲得", + "ec925d6946a88b5b": "キューを選ぶ", + "152ec44c76dca1ec": "キュー", + "4fa58c8eb16781d2": "新しいキューを解放:{name}", + "743592404305841f": "金メダル", + "aa1a6773ceaf9223": "銀メダル", + "b2c0da632a0a1b98": "銅メダル", + "a8bf31becdf2dc58": "次は金:{time}未満", + "853a57697469a28d": "次は銀:{time}未満", + "344ff8f2b12b3d70": "次は銅:{time}未満", + "67f492a1bb0c8673": "今日の自己ベスト更新!", + "60f19313f8c6f1a2": "今日のこのコンピューターの記録", + "36d880c1abd2d448": "+{seconds}秒", + "412cfbefb305eb90": "ビリヤード", + "b2be70822d55f16a": "開く", + "52499724d03777c6": "テーブルクリア", + "9fab80fe09b3dacf": "プレイ {clock}、ペナルティ +{seconds}秒、{shots}ショット", + "03b3f43d7b61d793": "もう一度プレイ", "49cc06e79f21f85a": "{seconds}秒", "8603d41c52392f1d": "{minutes}分{seconds}秒", "f2a955905704b91d": "{hours}時間{minutes}分", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 3a56c352d3..410118f913 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3109,6 +3109,49 @@ "ff5f1c260e87ecde": "이 브라우저에서 백엔드에 접근할 수 있는지, 호스팅된 클라이언트용 CORS를 지원하는지, HTTPS 페이지에서 열 때 HTTPS로 제공되는지 확인하세요.", "08570ee0982df89d": "페어링하는 중...", "3bbae7c96b6cbfc3": "앱 열기", + "0bc152a492a12716": "스크래치", + "aa2534f03870a3f9": "맞힌 공 없음", + "e13bcb690bb9c28f": "이번엔 무료", + "3d83bccbd9e6b227": "8번 공이 너무 일찍", + "163440207bcb77bb": "잘못된 포켓", + "24517a21c5ca36f7": "8번 공과 스크래치", + "e353b6587c16a231": "지팡이", + "c174eedba0edabdc": "황금 큐", + "e3114242f399e91b": "빛나는 큐", + "59a3f31ee049d0f5": "처음 맞힌 공이 들어갑니다", + "b6ab17c9f0d8fece": "{count}샷 동안 전체 경로", + "597ea9e53fc7cb87": "공 {count}개를 뚫고 지나감", + "3b3a060f716e1b53": "포켓을 클릭해 8번 공을 지정하세요", + "c655975d03078dd5": "먼저 포켓을 지정하세요", + "3dfd844f131e4d0a": "길게 눌러 모으고, 놓아서 치기", + "11b40436e8016644": "Shift로 세밀하게, Esc로 닫기", + "c8bf7e23d2bc15ae": "완료", + "d25661576338fcf0": "확인 필요", + "209d36a8ffe3791c": "클래식", + "88b909e76e754bef": "구리", + "9ca687520bab7394": "크롬", + "00f65fd8e47554b2": "불씨", + "637a3c803f6578d7": "테이블 한 번 클리어", + "af4bf1e680b765c6": "동메달 획득", + "52074a21b1859001": "은메달 획득", + "ef059864c4430c66": "금메달 획득", + "ec925d6946a88b5b": "큐 고르기", + "152ec44c76dca1ec": "큐", + "4fa58c8eb16781d2": "새 큐 잠금 해제: {name}", + "743592404305841f": "금메달", + "aa1a6773ceaf9223": "은메달", + "b2c0da632a0a1b98": "동메달", + "a8bf31becdf2dc58": "다음 목표: {time} 미만 금메달", + "853a57697469a28d": "다음 목표: {time} 미만 은메달", + "344ff8f2b12b3d70": "다음 목표: {time} 미만 동메달", + "67f492a1bb0c8673": "오늘의 새 최고 기록!", + "60f19313f8c6f1a2": "오늘 이 컴퓨터의 기록", + "36d880c1abd2d448": "+{seconds}초", + "412cfbefb305eb90": "당구", + "b2be70822d55f16a": "열기", + "52499724d03777c6": "테이블 클리어", + "9fab80fe09b3dacf": "플레이 {clock}, 페널티 +{seconds}초, {shots}샷", + "03b3f43d7b61d793": "다시 하기", "49cc06e79f21f85a": "{seconds}초", "8603d41c52392f1d": "{minutes}분 {seconds}초", "f2a955905704b91d": "{hours}시간 {minutes}분", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 3c4bf88004..95fbce4f0b 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3110,6 +3110,49 @@ "ff5f1c260e87ecde": "Verifique se o backend está acessível a partir deste navegador, se permite CORS para clientes hospedados e se é servido por HTTPS quando esta página é aberta via HTTPS.", "08570ee0982df89d": "Pareando...", "3bbae7c96b6cbfc3": "Abrir app", + "0bc152a492a12716": "Branca encaçapada", + "aa2534f03870a3f9": "Nenhuma bola atingida", + "e13bcb690bb9c28f": "Grátis desta vez", + "3d83bccbd9e6b227": "8 cedo demais", + "163440207bcb77bb": "Caçapa errada", + "24517a21c5ca36f7": "Branca com a 8", + "e353b6587c16a231": "Varinha", + "c174eedba0edabdc": "Taco dourado", + "e3114242f399e91b": "Taco brilhante", + "59a3f31ee049d0f5": "A primeira bola atingida cai", + "b6ab17c9f0d8fece": "Visão completa por {count} tacadas", + "597ea9e53fc7cb87": "Atravessa {count} bolas", + "3b3a060f716e1b53": "Clique em uma caçapa para cantar a 8", + "c655975d03078dd5": "Escolha uma caçapa primeiro", + "3dfd844f131e4d0a": "Segure para carregar, solte para tacar", + "11b40436e8016644": "Shift mira mais fino, Esc fecha", + "c8bf7e23d2bc15ae": "Pronto", + "d25661576338fcf0": "Precisa de você", + "209d36a8ffe3791c": "Clássico", + "88b909e76e754bef": "Cobre", + "9ca687520bab7394": "Cromo", + "00f65fd8e47554b2": "Brasa", + "637a3c803f6578d7": "Limpe uma mesa", + "af4bf1e680b765c6": "Ganhe uma medalha de bronze", + "52074a21b1859001": "Ganhe uma medalha de prata", + "ef059864c4430c66": "Ganhe uma medalha de ouro", + "ec925d6946a88b5b": "Escolher um taco", + "152ec44c76dca1ec": "Taco", + "4fa58c8eb16781d2": "Novo taco desbloqueado: {name}", + "743592404305841f": "Medalha de ouro", + "aa1a6773ceaf9223": "Medalha de prata", + "b2c0da632a0a1b98": "Medalha de bronze", + "a8bf31becdf2dc58": "Próxima: ouro abaixo de {time}", + "853a57697469a28d": "Próxima: prata abaixo de {time}", + "344ff8f2b12b3d70": "Próxima: bronze abaixo de {time}", + "67f492a1bb0c8673": "Novo recorde do dia!", + "60f19313f8c6f1a2": "Hoje neste computador", + "36d880c1abd2d448": "+{seconds} s", + "412cfbefb305eb90": "Sinuca", + "b2be70822d55f16a": "Abrir", + "52499724d03777c6": "Mesa limpa", + "9fab80fe09b3dacf": "{clock} de jogo, +{seconds} s de penalidade, {shots} tacadas", + "03b3f43d7b61d793": "Jogar de novo", "49cc06e79f21f85a": "{seconds}s", "8603d41c52392f1d": "{minutes}min {seconds}s", "f2a955905704b91d": "{hours}h {minutes}min", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index c94a7a61e3..1846d723a4 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3110,6 +3110,49 @@ "ff5f1c260e87ecde": "Убедитесь, что бэкенд доступен из этого браузера, поддерживает CORS для размещённых клиентов и работает по HTTPS, если эта страница открыта по HTTPS.", "08570ee0982df89d": "Сопряжение...", "3bbae7c96b6cbfc3": "Открыть приложение", + "0bc152a492a12716": "Биток в лузе", + "aa2534f03870a3f9": "Ни один шар не задет", + "e13bcb690bb9c28f": "В этот раз бесплатно", + "3d83bccbd9e6b227": "Восьмёрка слишком рано", + "163440207bcb77bb": "Не та луза", + "24517a21c5ca36f7": "Биток вместе с восьмёркой", + "e353b6587c16a231": "Палочка", + "c174eedba0edabdc": "Золотой кий", + "e3114242f399e91b": "Светящийся кий", + "59a3f31ee049d0f5": "Первый задетый шар падает", + "b6ab17c9f0d8fece": "Полная траектория на {count} удара", + "597ea9e53fc7cb87": "Пробивает {count} шара", + "3b3a060f716e1b53": "Нажмите на лузу, чтобы заказать восьмёрку", + "c655975d03078dd5": "Сначала закажите лузу", + "3dfd844f131e4d0a": "Удерживайте для силы, отпустите для удара", + "11b40436e8016644": "Shift — точнее, Esc — закрыть", + "c8bf7e23d2bc15ae": "Готово", + "d25661576338fcf0": "Нужен ваш ответ", + "209d36a8ffe3791c": "Классика", + "88b909e76e754bef": "Медь", + "9ca687520bab7394": "Хром", + "00f65fd8e47554b2": "Угли", + "637a3c803f6578d7": "Очистите стол", + "af4bf1e680b765c6": "Получите бронзовую медаль", + "52074a21b1859001": "Получите серебряную медаль", + "ef059864c4430c66": "Получите золотую медаль", + "ec925d6946a88b5b": "Выбрать кий", + "152ec44c76dca1ec": "Кий", + "4fa58c8eb16781d2": "Новый кий открыт: {name}", + "743592404305841f": "Золотая медаль", + "aa1a6773ceaf9223": "Серебряная медаль", + "b2c0da632a0a1b98": "Бронзовая медаль", + "a8bf31becdf2dc58": "Дальше: золото быстрее {time}", + "853a57697469a28d": "Дальше: серебро быстрее {time}", + "344ff8f2b12b3d70": "Дальше: бронза быстрее {time}", + "67f492a1bb0c8673": "Новый рекорд дня!", + "60f19313f8c6f1a2": "Сегодня на этом компьютере", + "36d880c1abd2d448": "+{seconds} с", + "412cfbefb305eb90": "Бильярд", + "b2be70822d55f16a": "Открыть", + "52499724d03777c6": "Стол очищен", + "9fab80fe09b3dacf": "{clock} игры, +{seconds} с штрафа, {shots} ударов", + "03b3f43d7b61d793": "Играть снова", "49cc06e79f21f85a": "{seconds} с", "8603d41c52392f1d": "{minutes} мин {seconds} с", "f2a955905704b91d": "{hours} ч {minutes} мин", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6eff8ad435..e110b06444 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3110,6 +3110,49 @@ "ff5f1c260e87ecde": "Kontrollera att backenden kan nås från den här webbläsaren, stöder CORS för webbaserade klienter och betjänas via HTTPS när den här sidan öppnas via HTTPS.", "08570ee0982df89d": "Parkopplar...", "3bbae7c96b6cbfc3": "Öppna app", + "0bc152a492a12716": "Vit i hål", + "aa2534f03870a3f9": "Ingen boll träffad", + "e13bcb690bb9c28f": "Gratis den här gången", + "3d83bccbd9e6b227": "8:an för tidigt", + "163440207bcb77bb": "Fel hål", + "24517a21c5ca36f7": "Vit i hål med 8:an", + "e353b6587c16a231": "Trollstav", + "c174eedba0edabdc": "Guldkö", + "e3114242f399e91b": "Glödkö", + "59a3f31ee049d0f5": "Första bollen du träffar går i", + "b6ab17c9f0d8fece": "Full sikt i {count} stötar", + "597ea9e53fc7cb87": "Bryter igenom {count} bollar", + "3b3a060f716e1b53": "Klicka på ett hål för att ropa ut 8:an", + "c655975d03078dd5": "Ropa ut ett hål först", + "3dfd844f131e4d0a": "Håll för att ladda, släpp för att stöta", + "11b40436e8016644": "Shift siktar finare, Esc stänger", + "c8bf7e23d2bc15ae": "Klar", + "d25661576338fcf0": "Behöver dig", + "209d36a8ffe3791c": "Klassisk", + "88b909e76e754bef": "Koppar", + "9ca687520bab7394": "Krom", + "00f65fd8e47554b2": "Glöd", + "637a3c803f6578d7": "Rensa ett bord", + "af4bf1e680b765c6": "Vinn en bronsmedalj", + "52074a21b1859001": "Vinn en silvermedalj", + "ef059864c4430c66": "Vinn en guldmedalj", + "ec925d6946a88b5b": "Välj en kö", + "152ec44c76dca1ec": "Kö", + "4fa58c8eb16781d2": "Ny kö upplåst: {name}", + "743592404305841f": "Guldmedalj", + "aa1a6773ceaf9223": "Silvermedalj", + "b2c0da632a0a1b98": "Bronsmedalj", + "a8bf31becdf2dc58": "Nästa: guld under {time}", + "853a57697469a28d": "Nästa: silver under {time}", + "344ff8f2b12b3d70": "Nästa: brons under {time}", + "67f492a1bb0c8673": "Nytt dagsrekord!", + "60f19313f8c6f1a2": "Idag på den här datorn", + "36d880c1abd2d448": "+{seconds} s", + "412cfbefb305eb90": "Biljard", + "b2be70822d55f16a": "Öppna", + "52499724d03777c6": "Bordet rensat", + "9fab80fe09b3dacf": "{clock} spelat, +{seconds} s straff, {shots} stötar", + "03b3f43d7b61d793": "Spela igen", "49cc06e79f21f85a": "{seconds} s", "8603d41c52392f1d": "{minutes} min {seconds} s", "f2a955905704b91d": "{hours} h {minutes} min", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 10e12bcfd2..a2365d9f22 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3114,6 +3114,49 @@ "ff5f1c260e87ecde": "请确认此浏览器能访问该后端、后端为托管客户端启用了 CORS,并且在通过 HTTPS 打开此页面时后端也使用 HTTPS。", "08570ee0982df89d": "正在配对…", "3bbae7c96b6cbfc3": "打开应用", + "0bc152a492a12716": "母球落袋", + "aa2534f03870a3f9": "没有击中球", + "e13bcb690bb9c28f": "这次免罚", + "3d83bccbd9e6b227": "8 号球太早", + "163440207bcb77bb": "袋口不对", + "24517a21c5ca36f7": "母球和 8 号球一起落袋", + "e353b6587c16a231": "魔杖", + "c174eedba0edabdc": "金色球杆", + "e3114242f399e91b": "光之球杆", + "59a3f31ee049d0f5": "击中的第一个球会落袋", + "b6ab17c9f0d8fece": "{count} 杆内看到完整路线", + "597ea9e53fc7cb87": "穿过 {count} 个球", + "3b3a060f716e1b53": "点击袋口指定 8 号球", + "c655975d03078dd5": "先指定袋口", + "3dfd844f131e4d0a": "按住蓄力,松开击球", + "11b40436e8016644": "Shift 精细瞄准,Esc 关闭", + "c8bf7e23d2bc15ae": "已完成", + "d25661576338fcf0": "需要你", + "209d36a8ffe3791c": "经典", + "88b909e76e754bef": "紫铜", + "9ca687520bab7394": "铬银", + "00f65fd8e47554b2": "余烬", + "637a3c803f6578d7": "清台一次", + "af4bf1e680b765c6": "获得铜牌", + "52074a21b1859001": "获得银牌", + "ef059864c4430c66": "获得金牌", + "ec925d6946a88b5b": "选择球杆", + "152ec44c76dca1ec": "球杆", + "4fa58c8eb16781d2": "解锁新球杆:{name}", + "743592404305841f": "金牌", + "aa1a6773ceaf9223": "银牌", + "b2c0da632a0a1b98": "铜牌", + "a8bf31becdf2dc58": "下一个目标:{time} 内拿金牌", + "853a57697469a28d": "下一个目标:{time} 内拿银牌", + "344ff8f2b12b3d70": "下一个目标:{time} 内拿铜牌", + "67f492a1bb0c8673": "今日新纪录!", + "60f19313f8c6f1a2": "今天在这台电脑上", + "36d880c1abd2d448": "+{seconds} 秒", + "412cfbefb305eb90": "台球", + "b2be70822d55f16a": "打开", + "52499724d03777c6": "清台", + "9fab80fe09b3dacf": "用时 {clock},罚时 +{seconds} 秒,{shots} 杆", + "03b3f43d7b61d793": "再玩一次", "49cc06e79f21f85a": "{seconds} 秒", "8603d41c52392f1d": "{minutes} 分 {seconds} 秒", "f2a955905704b91d": "{hours} 小时 {minutes} 分钟",