xonecas.ioDon't click! Sean Caetano Martin Sign in
space-browser / client / src / main.ts 72 lines2.7 kB Raw
1// Space Browser, the game. The client draws what the server sends and asks for
2// nothing else: this file is only the wiring, and the one loop that eases and draws.
3import { install } from './dev';
4import { bind, pointer, step } from './input';
5import { toWorld } from './sim';
6import { at, cam, canvas, cellOf, wpc } from './stage';
7import { PIECE_R, TONE, View } from './view';
8import { apply, bodies, follow, loose, ore, own, shots, ships, state } from './world';
9
10const view = new View(canvas);
11addEventListener('resize', () => view.resize());
12if (import.meta.env.DEV) install();
13bind();
14
15// What the pointer is over, in world units: a piece of a hull is round, a body is
16// as round as it is drawn. Nothing here decides anything, it only names the cell.
17const over = (x: number, y: number, p: { x: number; y: number }, r: number) =>
18  (x - p.x) ** 2 + (y - p.y) ** 2 <= r * r;
19// On the map every mark is exactly one cell wide, so it is hit as one cell.
20const tile = (x: number, y: number) => {
21  const r = wpc();
22  for (const s of ships.values()) if (s.id !== state?.you && !s.ai && over(x, y, s, r)) return TONE.hull;
23  for (const s of state?.systems ?? []) if (over(x, y, s, r)) return TONE.body;
24  return TONE.space;
25};
26const spot = (x: number, y: number) => {
27  if (cam.scene === 'galaxy') return tile(x, y);
28  for (const s of ships.values()) {
29    if (s.id === state?.you) continue; // your own hull is not a target
30    if (s.pieces.some((p) => over(x, y, toWorld(s, p), PIECE_R))) return TONE.hull;
31  }
32  for (const b of bodies.values()) if (over(x, y, b, b.r)) return TONE.body;
33  return TONE.space;
34};
35
36let last = performance.now();
37function frame(): void {
38  const now = performance.now();
39  const dt = Math.min(0.05, Math.max(0, now - last) / 1000);
40  last = now;
41
42  step(dt);
43  apply(dt);
44  follow(dt);
45
46  // The pointer is a cell mark like the order marker, so it is placed from the
47  // camera every frame: a pan slides the world under a pointer that never moved.
48  const p = pointer();
49  const c = p && cellOf(p.clientX, p.clientY);
50  const w = p && at(p);
51  view.setPointer(c ? c.cellX : null, c?.cellY, w ? spot(w.x, w.y) : undefined);
52
53  // The marker is the order the server is flying: never a click of our own, and
54  // never one it has already flown.
55  const me = own();
56  if (cam.scene === 'galaxy') {
57    view.drawGalaxy(cam, state?.systems ?? [], [...ships.values()], state?.you ?? 0);
58  } else {
59    view.draw(
60      cam,
61      [...bodies.values()],
62      [...ships.values()],
63      state?.you ?? 0,
64      [...shots.values()],
65      [...loose.values()],
66      [...ore.values()],
67      me && me.order && !state?.held ? { x: me.tx, y: me.ty } : null,
68    );
69  }
70  requestAnimationFrame(frame);
71}
72requestAnimationFrame(frame);