rook/val Public Public: anyone can read this; nobody can change it.
forked from benjivers/val
workbenchthis machine
Files 54c3aae2ea16956d3123256dfdd05930d31be4c5
| 1 | /** |
| 2 | * val, in a browser. It draws what the server sends and sends what the |
| 3 | * person does — nothing else. There is no position here the server did not |
| 4 | * hand over, and no enemy in a snapshot the server decided you cannot see, |
| 5 | * so a patched client learns nothing a plain one does not. |
| 6 | * |
| 7 | * This file is the wiring: the socket, the keys and the pointer, the HUD. |
| 8 | * The drawing lives beside it — `scene.js` for the first-person view, |
| 9 | * `topdown.js` for the map, `gun.js` for the crosshair, `prompt.js` for the |
| 10 | * line of advice and `raycast.js` for the maths all of it stands on. |
| 11 | */ |
| 12 | "use strict"; |
| 13 | |
| 14 | import { makeBeeper } from "./beep.js"; |
| 15 | import { makeBudget, measure } from "./budget.js"; |
| 16 | import { arrive, bodyAt, delay, feed, makeTimeline, renderTime } from "./interp.js"; |
| 17 | import { BODY_R, moveSpeed } from "../src/glide.ts"; |
| 18 | import { drawGun, gunSnapshot, gunTick, makeGun } from "./gun.js"; |
| 19 | import { advance, anchor, holdBack, insideWall, makeLocal, project, reconcile } from "./predict.js"; |
| 20 | import { forget, ghosts, makePresence, shown, sighted, slide } from "./presence.js"; |
| 21 | import { choosePrompt, REACH } from "./prompt.js"; |
| 22 | import { renderSize, WIDTHS } from "./resolution.js"; |
| 23 | import { roster, rosterKey } from "./roster.js"; |
| 24 | import { AGENT_COLOUR, drawScene, makeScene } from "./scene.js"; |
| 25 | import { moveVector } from "./steer.js"; |
| 26 | import { drawTopdown } from "./topdown.js"; |
| 27 | import { drawWatching, watching, watchLines } from "./watch.js"; |
| 28 | import { aim as aimAt, makeYaw, settle, told, turn } from "./yaw.js"; |
| 29 | |
| 30 | const $ = (id) => document.getElementById(id); |
| 31 | const view = $("view"); |
| 32 | const ctx = view.getContext("2d"); |
| 33 | // The world is drawn here, at a few hundred columns, and blitted onto the |
| 34 | // visible canvas scaled. The HUD, the crosshair and the minimap are drawn on |
| 35 | // `view` itself, at whatever the device pixel ratio really is. |
| 36 | const sceneCanvas = document.createElement("canvas"); |
| 37 | const sceneCtx = sceneCanvas.getContext("2d"); |
| 38 | |
| 39 | const KEY_SLOT = { KeyC: "c", KeyQ: "q", KeyE: "e", KeyX: "x" }; |
| 40 | const COARSE = matchMedia("(pointer: coarse)").matches; |
| 41 | const LOOK = 0.0022; // radians per pixel of mouse travel |
| 42 | const HELP_SEEN = "val.help.seen"; |
| 43 | |
| 44 | let map = null; |
| 45 | let solid = () => true; |
| 46 | let world = null; // what predict.js slides against: the grid, from map.json |
| 47 | let snap = null; |
| 48 | let socket = null; |
| 49 | let agents = null; |
| 50 | // Everybody else, kept as the last few things the server said about them and |
| 51 | // drawn between those — see interp.js. `drawAt` is the moment this frame is |
| 52 | // drawing, a snapshot interval behind the present. |
| 53 | const timeline = makeTimeline(); |
| 54 | let drawAt = 0; |
| 55 | // Who is in sight and who just left it — see presence.js. A body the server |
| 56 | // has only now started sending has no history at all, and drawing it solid |
| 57 | // at its exact position is what makes enemies appear to teleport into a room. |
| 58 | const presence = makePresence(); |
| 59 | const slid = { x: 0, y: 0, angle: 0 }; |
| 60 | let marks = []; |
| 61 | let nowSec = performance.now() / 1000; |
| 62 | const keys = new Set(); |
| 63 | // Where this person is looking: the browser's between snapshots, and the |
| 64 | // server's word taken only when it is saying something we did not. See |
| 65 | // yaw.js — a snapshot that stomps this is what made looking around choppy. |
| 66 | const head = makeYaw(); |
| 67 | let locked = false; |
| 68 | let firing = false; |
| 69 | let mode = COARSE ? "top" : "fp"; // a raycaster with touch look is miserable |
| 70 | let mapOpen = false; |
| 71 | let pointer = null; // aim target in canvas pixels, top-down only |
| 72 | let stick = null; // { id, ox, oy, mx, my } |
| 73 | let aimTouch = null; |
| 74 | let helpShown = false; |
| 75 | let last = performance.now(); |
| 76 | let snapAt = last; // when the last snapshot landed: how stale the answer is |
| 77 | // How many columns the world is drawn at, and what the frame is costing. |
| 78 | // See resolution.js for the ladder and budget.js for the rung it settles on: |
| 79 | // the visible canvas is device pixels, this is not. |
| 80 | const budget = makeBudget(0, WIDTHS.length - 1); |
| 81 | let render = { width: 960, height: 600 }; |
| 82 | let perfOn = false; |
| 83 | let perfAt = 0; |
| 84 | |
| 85 | const walk = { x: 0, y: 0 }; |
| 86 | // What this person is doing right now, read once a frame for the drawing and |
| 87 | // once every 50ms for the server. The same object either way: no allocation |
| 88 | // in a loop that runs sixty times a second. |
| 89 | const intent = { mx: 0, my: 0, angle: 0, fire: false, use: false, reload: false }; |
| 90 | // Your own body, run forward from your own keys between snapshots, and the |
| 91 | // object the drawing is handed for it. |
| 92 | const local = makeLocal(); |
| 93 | const drawnMe = { id: "", x: 0, y: 0, angle: 0 }; |
| 94 | const scene = makeScene(); |
| 95 | const gun = makeGun(); |
| 96 | const beeper = makeBeeper(); |
| 97 | |
| 98 | // ------------------------------------------------------------------ socket |
| 99 | |
| 100 | function connect() { |
| 101 | const url = (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws"; |
| 102 | socket = new WebSocket(url); |
| 103 | socket.onopen = () => ($("conn").textContent = "live"); |
| 104 | socket.onclose = () => { |
| 105 | $("conn").textContent = "reconnecting…"; |
| 106 | setTimeout(connect, 1500); |
| 107 | }; |
| 108 | socket.onmessage = (event) => { |
| 109 | const data = JSON.parse(event.data); |
| 110 | if (data.t !== "s") return; |
| 111 | snap = data; |
| 112 | snapAt = performance.now(); |
| 113 | // No seat, no `me`, no players. Everything below reads a body out of the |
| 114 | // snapshot, so a watching connection takes the other path entirely. |
| 115 | if (watching(data)) return void paintWatch(data); |
| 116 | // Timed samples for every body in it, ours included: the drawing walks |
| 117 | // between them rather than chasing the newest one. |
| 118 | arrive(timeline, snapAt / 1000); |
| 119 | // Between rounds everybody is teleported to a spawn, so no sighting |
| 120 | // before that says anything about where anybody is now. |
| 121 | if (data.phase !== "live") forget(presence); |
| 122 | else sighted(presence, data.players, snapAt / 1000); |
| 123 | feed(timeline, data.me.id, data.me, snapAt / 1000); |
| 124 | for (const player of data.players) feed(timeline, player.id, player, snapAt / 1000); |
| 125 | // The server's angle is taken only when it is a correction, never as the |
| 126 | // routine echo of the angle we sent it a moment ago. |
| 127 | settle(head, data.me, snapAt / 1000); |
| 128 | gunSnapshot(gun, data); |
| 129 | paintHud(data); |
| 130 | maybeHelp(data); |
| 131 | }; |
| 132 | } |
| 133 | |
| 134 | const send = (message) => { |
| 135 | if (socket && socket.readyState === 1) socket.send(JSON.stringify(message)); |
| 136 | }; |
| 137 | |
| 138 | // ------------------------------------------------------------------- input |
| 139 | |
| 140 | /** |
| 141 | * Swap the view. The two share one facing — whichever you leave, you keep |
| 142 | * looking the way you were looking — so nothing here touches the angle. |
| 143 | */ |
| 144 | function setMode(next) { |
| 145 | mode = next; |
| 146 | $("stage").dataset.mode = next; |
| 147 | if (next !== "fp" && document.pointerLockElement === view) document.exitPointerLock(); |
| 148 | } |
| 149 | |
| 150 | addEventListener("keydown", (event) => { |
| 151 | if (event.target instanceof HTMLInputElement) return; |
| 152 | if (event.code === "Tab") { |
| 153 | mapOpen = true; |
| 154 | event.preventDefault(); |
| 155 | return; |
| 156 | } |
| 157 | if (event.code === "KeyH" || event.key === "?") { |
| 158 | toggleHelp(); |
| 159 | event.preventDefault(); |
| 160 | return; |
| 161 | } |
| 162 | if (event.code === "KeyV") { |
| 163 | setMode(mode === "fp" ? "top" : "fp"); |
| 164 | event.preventDefault(); |
| 165 | return; |
| 166 | } |
| 167 | if (event.code === "KeyB") { |
| 168 | toggleBuy(); |
| 169 | event.preventDefault(); |
| 170 | return; |
| 171 | } |
| 172 | if (event.code === "F3" || event.code === "Backquote") { |
| 173 | togglePerf(); |
| 174 | event.preventDefault(); |
| 175 | return; |
| 176 | } |
| 177 | if (KEY_SLOT[event.code]) { |
| 178 | send({ t: "i", c: KEY_SLOT[event.code] }); |
| 179 | event.preventDefault(); |
| 180 | return; |
| 181 | } |
| 182 | keys.add(event.code); |
| 183 | if (["KeyW", "KeyA", "KeyS", "KeyD", "Space", "KeyF", "KeyR", "ArrowLeft", "ArrowRight"].includes(event.code)) |
| 184 | event.preventDefault(); |
| 185 | }); |
| 186 | addEventListener("keyup", (event) => { |
| 187 | if (event.code === "Tab") mapOpen = false; |
| 188 | keys.delete(event.code); |
| 189 | }); |
| 190 | addEventListener("blur", () => { |
| 191 | keys.clear(); |
| 192 | mapOpen = false; |
| 193 | firing = false; |
| 194 | }); |
| 195 | |
| 196 | // Aiming is pointer lock: click the canvas to capture the mouse, move to |
| 197 | // look, Escape gives it back. The angle sent is the same angle as ever. |
| 198 | view.addEventListener("click", () => { |
| 199 | beeper.wake(); |
| 200 | if (watching(snap)) return; // nothing to aim: capturing the mouse would be a lie |
| 201 | if (mode !== "fp" || locked) return; |
| 202 | if (!view.requestPointerLock) return setMode("top"); // no lock, no first person |
| 203 | // Asked for too soon after the last release, a browser rejects this; that |
| 204 | // is a shrug, not an error, and the hint stays up until it takes. |
| 205 | const asked = view.requestPointerLock(); |
| 206 | if (asked && asked.catch) asked.catch(() => {}); |
| 207 | }); |
| 208 | document.addEventListener("pointerlockchange", () => { |
| 209 | locked = document.pointerLockElement === view; |
| 210 | if (!locked) firing = false; |
| 211 | $("stage").dataset.locked = locked ? "1" : ""; |
| 212 | }); |
| 213 | addEventListener("mousemove", (event) => { |
| 214 | if (locked) turn(head, event.movementX * LOOK); |
| 215 | }); |
| 216 | addEventListener("mousedown", (event) => { |
| 217 | if (locked && event.button === 0) firing = true; |
| 218 | }); |
| 219 | addEventListener("mouseup", (event) => { |
| 220 | if (locked && event.button === 0) firing = false; |
| 221 | }); |
| 222 | |
| 223 | // The top-down view keeps the pointer aim it always had: it is the phone |
| 224 | // control scheme, and the fallback when the first-person view is not wanted. |
| 225 | const canvasPoint = (event) => { |
| 226 | const box = view.getBoundingClientRect(); |
| 227 | return { |
| 228 | x: ((event.clientX - box.left) / box.width) * view.width, |
| 229 | y: ((event.clientY - box.top) / box.height) * view.height, |
| 230 | }; |
| 231 | }; |
| 232 | view.addEventListener("pointermove", (event) => { |
| 233 | if (mode !== "top" || event.pointerType === "touch") return; |
| 234 | pointer = canvasPoint(event); |
| 235 | }); |
| 236 | view.addEventListener("pointerdown", (event) => { |
| 237 | beeper.wake(); |
| 238 | if (mode !== "top") return; |
| 239 | view.setPointerCapture(event.pointerId); |
| 240 | const box = view.getBoundingClientRect(); |
| 241 | if (event.pointerType === "touch") { |
| 242 | if (event.clientX - box.left < box.width / 2) |
| 243 | stick = { id: event.pointerId, ox: event.clientX, oy: event.clientY, mx: 0, my: 0 }; |
| 244 | else { |
| 245 | aimTouch = { id: event.pointerId, ...canvasPoint(event) }; |
| 246 | firing = true; |
| 247 | } |
| 248 | event.preventDefault(); |
| 249 | return; |
| 250 | } |
| 251 | pointer = canvasPoint(event); |
| 252 | firing = true; |
| 253 | }); |
| 254 | view.addEventListener("pointermove", (event) => { |
| 255 | if (stick && event.pointerId === stick.id) { |
| 256 | const dx = event.clientX - stick.ox; |
| 257 | const dy = event.clientY - stick.oy; |
| 258 | const len = Math.hypot(dx, dy) || 1; |
| 259 | const reach = Math.min(len, 48) / 48; |
| 260 | stick.mx = (dx / len) * reach; |
| 261 | stick.my = (dy / len) * reach; |
| 262 | } |
| 263 | if (aimTouch && event.pointerId === aimTouch.id) Object.assign(aimTouch, canvasPoint(event)); |
| 264 | }); |
| 265 | const endPointer = (event) => { |
| 266 | if (stick && event.pointerId === stick.id) stick = null; |
| 267 | else if (aimTouch && event.pointerId === aimTouch.id) { |
| 268 | aimTouch = null; |
| 269 | firing = false; |
| 270 | } else firing = false; |
| 271 | }; |
| 272 | view.addEventListener("pointerup", endPointer); |
| 273 | view.addEventListener("pointercancel", endPointer); |
| 274 | view.addEventListener("contextmenu", (event) => event.preventDefault()); |
| 275 | |
| 276 | // What this person is doing, in the world's terms. In the first-person view |
| 277 | // the keys are read against the way you are facing; in the top-down view they |
| 278 | // are the compass, the way they always were. |
| 279 | function readIntent() { |
| 280 | let ax = 0; |
| 281 | let ay = 0; |
| 282 | if (keys.has("KeyW")) ay -= 1; |
| 283 | if (keys.has("KeyS")) ay += 1; |
| 284 | if (keys.has("KeyA")) ax -= 1; |
| 285 | if (keys.has("KeyD")) ax += 1; |
| 286 | if (stick) { |
| 287 | ax = stick.mx; |
| 288 | ay = stick.my; |
| 289 | } |
| 290 | intent.mx = ax; |
| 291 | intent.my = ay; |
| 292 | if (mode === "fp") { |
| 293 | intent.angle = head.angle; |
| 294 | moveVector(ax, ay, head.angle, walk); |
| 295 | intent.mx = walk.x; |
| 296 | intent.my = walk.y; |
| 297 | } else { |
| 298 | const aim = aimTouch || pointer; |
| 299 | const me = worldToScreen(drawnMe.id ? drawnMe : snap.me); |
| 300 | // The pointer is this view's aim, and it is ours the same way the mouse |
| 301 | // is: with no pointer yet, keep the facing rather than the stale answer. |
| 302 | if (aim) aimAt(head, Math.atan2(aim.y - me.y, aim.x - me.x)); |
| 303 | intent.angle = head.angle; |
| 304 | } |
| 305 | intent.fire = firing || keys.has("Space"); |
| 306 | intent.use = keys.has("KeyF"); |
| 307 | intent.reload = keys.has("KeyR"); |
| 308 | return intent; |
| 309 | } |
| 310 | |
| 311 | // Twenty times a second the server hears it. Intent only — a direction, an |
| 312 | // angle, a held key — never a position: the guess below is for drawing. |
| 313 | setInterval(() => { |
| 314 | if (!snap || !map || watching(snap)) return; // nothing to drive, nothing to send |
| 315 | const now = readIntent(); |
| 316 | send({ t: "i", mx: now.mx, my: now.my, a: now.angle, f: now.fire, u: now.use, r: now.reload }); |
| 317 | // What we told it, so its echo is recognisable as ours when it comes back. |
| 318 | told(head, now.angle, performance.now() / 1000); |
| 319 | }, 50); |
| 320 | |
| 321 | // ------------------------------------------------------------------ drawing |
| 322 | |
| 323 | function resize() { |
| 324 | const box = view.getBoundingClientRect(); |
| 325 | const dpr = Math.min(devicePixelRatio || 1, 2); |
| 326 | view.width = Math.round(box.width * dpr); |
| 327 | view.height = Math.round(box.height * dpr); |
| 328 | sizeRender(); |
| 329 | } |
| 330 | addEventListener("resize", resize); |
| 331 | |
| 332 | /** The offscreen the world is drawn into, at the level in force right now. */ |
| 333 | function sizeRender() { |
| 334 | render = renderSize(view.width, view.height, budget.level); |
| 335 | if (sceneCanvas.width !== render.width) sceneCanvas.width = render.width; |
| 336 | if (sceneCanvas.height !== render.height) sceneCanvas.height = render.height; |
| 337 | } |
| 338 | |
| 339 | const scale = () => (map ? view.width / (map.rows[0].length * map.tile) : 1); |
| 340 | const worldToScreen = (p) => ({ x: p.x * scale(), y: p.y * scale() }); |
| 341 | |
| 342 | /** |
| 343 | * Everybody else is drawn at `drawAt`: between the two samples that bracket |
| 344 | * it, so they move at the server's own speed and arrive where it put them. |
| 345 | * You are not: your own body is the one this browser can run forward |
| 346 | * honestly, and drawing it late is what dragged the camera backwards. |
| 347 | */ |
| 348 | const look = (p) => { |
| 349 | if (predicting() && p.id === snap.me.id) return drawnMe; |
| 350 | // A body still arriving is drawn part of the way in from where it came, |
| 351 | // rather than at the position it had already reached when we first saw it. |
| 352 | return slide(presence, p.id, bodyAt(timeline, p, drawAt), nowSec, slid); |
| 353 | }; |
| 354 | |
| 355 | /** How far into sight somebody is: 0 as they appear, 1 once they are solid. */ |
| 356 | const shownAt = (p) => shown(presence, p.id, nowSec); |
| 357 | |
| 358 | /** |
| 359 | * Your own movement is only guessed at while the round is live and you are |
| 360 | * alive. The buy phase pens everybody in their own spawn — a rule of the |
| 361 | * match, not of the map — and a guess that does not know it would spend the |
| 362 | * phase being pulled back through the door. |
| 363 | */ |
| 364 | const predicting = () => |
| 365 | snap !== null && !watching(snap) && world !== null && snap.phase !== "buy" && snap.me.alive; |
| 366 | |
| 367 | /** The server's answer, caught up to now, then this frame of your own keys. */ |
| 368 | function predict(dt, now) { |
| 369 | if (!predicting()) { |
| 370 | local.ready = false; |
| 371 | drawnMe.id = ""; |
| 372 | return; |
| 373 | } |
| 374 | const held = readIntent(); |
| 375 | const speed = moveSpeed({ |
| 376 | haste: snap.me.haste > 0, |
| 377 | slow: snap.me.slow > 0, |
| 378 | stopped: snap.me.planting > 0 || snap.me.defusing, |
| 379 | heavy: snap.me.weapon === "operator", |
| 380 | }); |
| 381 | // The snapshot is a moment old and the keys held since have not reached |
| 382 | // it; carry it that far forward and lean the drawn body onto it. |
| 383 | const target = project(snap.me, held.mx, held.my, speed, (now - snapAt) / 1000, world); |
| 384 | reconcile(local, target, dt); |
| 385 | advance(local, held.mx, held.my, speed, dt, world); |
| 386 | holdBack(local, target, held.mx, held.my); |
| 387 | // A lean across a corner could put the drawn body in a wall; the server's |
| 388 | // answer is never wrong, so take it rather than draw from inside one. |
| 389 | if (insideWall(local, world)) anchor(local, snap.me); |
| 390 | drawnMe.id = snap.me.id; |
| 391 | drawnMe.x = local.x; |
| 392 | drawnMe.y = local.y; |
| 393 | // Either view: the facing is the one this browser is holding, whether the |
| 394 | // mouse moved it or the pointer aim did. The server hears it a moment later. |
| 395 | drawnMe.angle = head.angle; |
| 396 | } |
| 397 | |
| 398 | function frame(now) { |
| 399 | requestAnimationFrame(frame); |
| 400 | const began = performance.now(); |
| 401 | const dt = Math.min(0.1, (now - last) / 1000); |
| 402 | last = now; |
| 403 | nowSec = began / 1000; |
| 404 | marks = ghosts(presence, nowSec); |
| 405 | drawAt = renderTime(timeline, now / 1000); |
| 406 | // A watching connection draws the watching view and stops there: it has no |
| 407 | // map to stand on and no body to put on it, and must invent neither. |
| 408 | if (watching(snap)) return void drawWatch(); |
| 409 | if (!map) return; |
| 410 | gunTick(gun, dt); |
| 411 | ctx.clearRect(0, 0, view.width, view.height); |
| 412 | |
| 413 | if (!snap) { |
| 414 | drawTopdown(ctx, map, null, look, { x: 0, y: 0, w: view.width, h: view.height }); |
| 415 | return; |
| 416 | } |
| 417 | // Turning with the arrow keys belongs to the frame, at a rate a second, |
| 418 | // rather than to whatever the input timer happens to do. |
| 419 | if (mode === "fp" && keys.has("ArrowLeft")) turn(head, -0.9 * dt); |
| 420 | if (mode === "fp" && keys.has("ArrowRight")) turn(head, 0.9 * dt); |
| 421 | predict(dt, now); |
| 422 | beeper.update(snap.spike.planted, snap.spike.fuse, now / 1000); |
| 423 | const eye = look(snap.me); |
| 424 | const facing = mode === "fp" ? head.angle : eye.angle; |
| 425 | |
| 426 | if (mode === "fp" && !mapOpen) { |
| 427 | // The world at a few hundred columns, then scaled onto the canvas. The |
| 428 | // walls are flat shaded, so the upscale costs the picture almost |
| 429 | // nothing; the crosshair and the map below are drawn sharp on top. |
| 430 | drawScene(sceneCtx, scene, { solid, tile: map.tile }, { x: eye.x, y: eye.y, angle: facing }, snap, { |
| 431 | width: render.width, |
| 432 | height: render.height, |
| 433 | look, |
| 434 | shown: shownAt, |
| 435 | marks, |
| 436 | }); |
| 437 | ctx.drawImage(sceneCanvas, 0, 0, view.width, view.height); |
| 438 | drawGun(ctx, gun, view.width, view.height, snap); |
| 439 | drawMinimap(); |
| 440 | } else { |
| 441 | const box = { x: 0, y: 0, w: view.width, h: view.height }; |
| 442 | ctx.drawImage(tileLayer(view.width, view.height, true), 0, 0); |
| 443 | drawTopdown(ctx, map, snap, look, box, { marks, tiles: false }); |
| 444 | } |
| 445 | |
| 446 | if (snap.me.planting > 0) bar(snap.me.planting / 4, "#e0a040", "planting"); |
| 447 | else if (snap.spike.planted && snap.spike.defuse > 0 && snap.me.side === "def") |
| 448 | bar(snap.spike.defuse / 7, "#4fd6a0", "defusing"); |
| 449 | $("flash").style.opacity = Math.min(0.95, snap.me.blind * 0.8); |
| 450 | $("dead").style.display = snap.me.alive ? "none" : "grid"; |
| 451 | $("aimhint").style.display = mode === "fp" && !locked && !COARSE ? "grid" : "none"; |
| 452 | |
| 453 | // What this frame cost to draw, not how long the browser waited for the |
| 454 | // next one: a machine with headroom is capped at its refresh rate, and the |
| 455 | // renderer would never earn a rung back if that were the measure. |
| 456 | const ended = performance.now(); |
| 457 | if (measure(budget, ended - began, ended / 1000)) sizeRender(); |
| 458 | paintPerf(ended); |
| 459 | } |
| 460 | |
| 461 | /** F3 or ` — the numbers, so "it feels choppy" has something to argue with. */ |
| 462 | function togglePerf() { |
| 463 | perfOn = !perfOn; |
| 464 | const box = $("perf"); |
| 465 | if (!box) return; |
| 466 | box.style.display = perfOn ? "block" : "none"; |
| 467 | // Straight away, whatever the clock says: a readout you turn on and that |
| 468 | // stays blank for half a second reads as a readout that does not work. |
| 469 | if (perfOn) paintPerf(performance.now(), true); |
| 470 | } |
| 471 | |
| 472 | /** |
| 473 | * The readout, rewritten twice a second: the frame rate and the mean frame |
| 474 | * the governor decided on, the rate snapshots are actually arriving at, the |
| 475 | * interpolation delay in force, and how wide the world is being drawn. |
| 476 | */ |
| 477 | function paintPerf(nowMs, force) { |
| 478 | const box = $("perf"); |
| 479 | if (!perfOn || !box || (!force && nowMs - perfAt < 500)) return; |
| 480 | perfAt = nowMs; |
| 481 | const hz = timeline.interval > 0 ? 1 / timeline.interval : 0; |
| 482 | box.textContent = |
| 483 | `${budget.fps.toFixed(1)} fps · ${budget.mean.toFixed(1)} ms/frame · ` + |
| 484 | `${hz.toFixed(1)} Hz in · ${(delay(timeline) * 1000).toFixed(0)} ms behind · ` + |
| 485 | `${render.width}×${render.height} of ${view.width}×${view.height}`; |
| 486 | } |
| 487 | |
| 488 | /** |
| 489 | * The map's own tiles, drawn once a size and kept. There are 570 of them and |
| 490 | * they are the same 570 every frame — on the minimap that was more fills |
| 491 | * than the whole first-person view costs. Called with no snapshot, |
| 492 | * `drawTopdown` draws exactly this layer and nothing else. |
| 493 | */ |
| 494 | const layers = new Map(); |
| 495 | function tileLayer(w, h, labels) { |
| 496 | const key = `${w}x${h}${labels ? "L" : ""}`; |
| 497 | const had = layers.get(key); |
| 498 | if (had) return had; |
| 499 | const layer = document.createElement("canvas"); |
| 500 | layer.width = w; |
| 501 | layer.height = h; |
| 502 | drawTopdown(layer.getContext("2d"), map, null, look, { x: 0, y: 0, w, h }, { labels }); |
| 503 | if (layers.size > 3) layers.clear(); // a window being dragged, not a leak |
| 504 | layers.set(key, layer); |
| 505 | return layer; |
| 506 | } |
| 507 | |
| 508 | /** The same top-down drawing, small, in the corner, with you as an arrow. */ |
| 509 | function drawMinimap() { |
| 510 | const w = Math.min(view.width * 0.3, 260 * (view.width / 900)); |
| 511 | const h = (w * map.rows.length) / map.rows[0].length; |
| 512 | const pad = 8; |
| 513 | ctx.save(); |
| 514 | ctx.globalAlpha = 0.85; |
| 515 | ctx.fillStyle = "#0b0d11"; |
| 516 | ctx.fillRect(pad - 2, pad - 2, w + 4, h + 4); |
| 517 | ctx.drawImage(tileLayer(Math.max(1, Math.round(w)), Math.max(1, Math.round(h)), false), pad, pad, w, h); |
| 518 | drawTopdown(ctx, map, snap, look, { x: pad, y: pad, w, h }, { labels: false, marks, tiles: false }); |
| 519 | ctx.restore(); |
| 520 | ctx.strokeStyle = "rgba(255,255,255,0.18)"; |
| 521 | ctx.lineWidth = 1; |
| 522 | ctx.strokeRect(pad - 2, pad - 2, w + 4, h + 4); |
| 523 | } |
| 524 | |
| 525 | function bar(fraction, colour, label) { |
| 526 | const w = view.width * 0.4; |
| 527 | const x = view.width / 2 - w / 2; |
| 528 | const y = view.height * 0.86; |
| 529 | ctx.fillStyle = "#0009"; |
| 530 | ctx.fillRect(x, y, w, 16); |
| 531 | ctx.fillStyle = colour; |
| 532 | ctx.fillRect(x, y, w * Math.min(1, fraction), 16); |
| 533 | ctx.fillStyle = "#fff"; |
| 534 | ctx.font = "12px system-ui, sans-serif"; |
| 535 | ctx.textAlign = "center"; |
| 536 | ctx.fillText(label, view.width / 2, y + 12); |
| 537 | ctx.textAlign = "left"; |
| 538 | } |
| 539 | |
| 540 | // --------------------------------------------------------------------- hud |
| 541 | |
| 542 | // The buy opens itself every buy phase; closing it is remembered until the |
| 543 | // next one, so nobody has to fight the panel to watch the round start. |
| 544 | function toggleBuy() { |
| 545 | const open = $("buy").classList.toggle("on"); |
| 546 | $("buy").dataset.closed = open ? "" : "1"; |
| 547 | } |
| 548 | $("buytoggle").addEventListener("click", toggleBuy); |
| 549 | $("viewtoggle").addEventListener("click", () => setMode(mode === "fp" ? "top" : "fp")); |
| 550 | $("helptoggle").addEventListener("click", () => toggleHelp()); |
| 551 | $("helpclose").addEventListener("click", () => toggleHelp(false)); |
| 552 | for (const button of document.querySelectorAll("[data-buy]")) |
| 553 | button.addEventListener("click", () => send({ t: "buy", what: button.dataset.buy })); |
| 554 | for (const button of document.querySelectorAll("[data-agent]")) |
| 555 | button.addEventListener("click", () => send({ t: "agent", id: button.dataset.agent })); |
| 556 | |
| 557 | function toggleHelp(force) { |
| 558 | const open = force === undefined ? $("help").style.display !== "grid" : force; |
| 559 | $("help").style.display = open ? "grid" : "none"; |
| 560 | if (!open) { |
| 561 | helpShown = true; |
| 562 | try { |
| 563 | localStorage.setItem(HELP_SEEN, "1"); |
| 564 | } catch { |
| 565 | // A browser that refuses storage still gets the card, every visit. |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | /** The first-run card, once per browser, and never over a round in progress. */ |
| 571 | function maybeHelp(s) { |
| 572 | if (helpShown) return; |
| 573 | try { |
| 574 | if (localStorage.getItem(HELP_SEEN) === "1") { |
| 575 | helpShown = true; |
| 576 | return; |
| 577 | } |
| 578 | } catch { |
| 579 | /* no storage: show it and move on */ |
| 580 | } |
| 581 | if (s.phase === "live" && s.me.alive) return; |
| 582 | helpShown = true; |
| 583 | $("help").style.display = "grid"; |
| 584 | } |
| 585 | |
| 586 | const KITS = {}; |
| 587 | |
| 588 | function paintHud(s) { |
| 589 | $("clock").textContent = Math.ceil(s.phase === "live" && s.spike.planted ? s.spike.fuse : s.clock); |
| 590 | document.querySelector("#scoreline .red").textContent = "red " + s.score.red; |
| 591 | document.querySelector("#scoreline .blue").textContent = s.score.blue + " blue"; |
| 592 | $("phase").textContent = |
| 593 | `round ${s.round} · ${s.phase === "buy" ? "buy phase" : s.phase === "live" ? (s.spike.planted ? "spike down" : "live") : s.phase === "end" ? "round over" : "match over"} · ${s.attackers} attacking · you are ${s.me.side === "atk" ? "attacking" : "defending"}${s.result ? " · " + s.result : ""}`; |
| 594 | $("hp").textContent = `${s.me.hp} hp${s.me.armour ? " +" + s.me.armour : ""}`; |
| 595 | $("gun").textContent = `${s.me.weapon}${s.me.reloading ? " reloading" : " " + s.me.ammo}`; |
| 596 | $("creds").textContent = `${s.me.credits} cr`; |
| 597 | $("ultmeter").textContent = `ult ${s.me.ult}/${s.me.ultNeeds}`; |
| 598 | $("buy").classList.toggle("on", s.phase === "buy" && $("buy").dataset.closed !== "1"); |
| 599 | if (s.phase !== "buy") $("buy").dataset.closed = ""; |
| 600 | |
| 601 | const text = choosePrompt(s, { |
| 602 | onSite: onSite(s.me), |
| 603 | nearSpike: s.spike.x !== null && Math.hypot(s.spike.x - s.me.x, s.spike.y - s.me.y) < REACH, |
| 604 | }); |
| 605 | if ($("prompt").textContent !== text) $("prompt").textContent = text; |
| 606 | |
| 607 | paintKit(s); |
| 608 | paintBuy(s); |
| 609 | paintRoster(s); |
| 610 | paintFeed(s); |
| 611 | paintLog(s); |
| 612 | |
| 613 | for (const side of ["atk", "def"]) { |
| 614 | const body = $(side + "board"); |
| 615 | const rows = s.board.filter((p) => p.side === side).sort((a, b) => b.kills - a.kills); |
| 616 | const key = rows.map((p) => `${p.name}${p.kills}${p.deaths}${p.alive}${p.credits}`).join(); |
| 617 | if (body.dataset.key === key) continue; |
| 618 | body.dataset.key = key; |
| 619 | body.replaceChildren(); |
| 620 | for (const player of rows) { |
| 621 | const tr = document.createElement("tr"); |
| 622 | const cells = [ |
| 623 | player.name + (player.bot ? " (bot)" : "") + (player.alive ? "" : " ✕"), |
| 624 | player.agent + (player.credits !== null ? ` · ${player.credits}cr` : ""), |
| 625 | String(player.kills), |
| 626 | String(player.deaths), |
| 627 | ]; |
| 628 | for (const value of cells) { |
| 629 | const td = document.createElement("td"); |
| 630 | td.textContent = value; |
| 631 | tr.append(td); |
| 632 | } |
| 633 | if (player.id === s.me.id) tr.style.fontWeight = "700"; |
| 634 | body.append(tr); |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | /** The last few things that happened, in words. Rebuilt only when they change. */ |
| 640 | function paintLog(s) { |
| 641 | const log = $("log"); |
| 642 | const lines = (s.events ?? []).slice(0, 3); |
| 643 | if (log.dataset.text === lines.join("\n")) return; |
| 644 | log.dataset.text = lines.join("\n"); |
| 645 | log.replaceChildren(); |
| 646 | for (const line of lines) { |
| 647 | const div = document.createElement("div"); |
| 648 | div.textContent = line; |
| 649 | log.append(div); |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | /** |
| 654 | * The HUD for a connection with no seat. Everything a seat's HUD says about |
| 655 | * you — health, gun, credits, kit, your five — has no answer here, so it says |
| 656 | * so rather than leaving the page's first paint standing there going stale. |
| 657 | */ |
| 658 | function paintWatch(s) { |
| 659 | const lines = watchLines(s); |
| 660 | $("clock").textContent = Math.ceil(Math.max(0, Number(s.clock) || 0)); |
| 661 | document.querySelector("#scoreline .red").textContent = "red " + (s.score?.red ?? 0); |
| 662 | document.querySelector("#scoreline .blue").textContent = (s.score?.blue ?? 0) + " blue"; |
| 663 | $("phase").textContent = lines.phase; |
| 664 | $("hp").textContent = "watching"; |
| 665 | $("gun").textContent = "no seat"; |
| 666 | $("creds").textContent = "—"; |
| 667 | $("ultmeter").textContent = "—"; |
| 668 | $("buy").classList.toggle("on", false); |
| 669 | if ($("prompt").textContent !== lines.why) $("prompt").textContent = lines.why; |
| 670 | paintFeed(s); |
| 671 | paintLog(s); |
| 672 | blank($("kit")); |
| 673 | blank($("roster")); |
| 674 | blank($("atkboard")); |
| 675 | blank($("defboard")); |
| 676 | if (KITS.shape !== "watching") KITS.shape = "watching"; |
| 677 | } |
| 678 | |
| 679 | /** Empty a panel whose answer this connection is not sent, once. */ |
| 680 | function blank(panel) { |
| 681 | if (panel.dataset.key === "watching") return; |
| 682 | panel.dataset.key = "watching"; |
| 683 | panel.dataset.text = "watching"; |
| 684 | panel.replaceChildren(); |
| 685 | } |
| 686 | |
| 687 | /** The canvas, watching: no map, no bodies, and the overlays a seat owns off. */ |
| 688 | function drawWatch() { |
| 689 | ctx.clearRect(0, 0, view.width, view.height); |
| 690 | drawWatching(ctx, snap, view.width, view.height); |
| 691 | $("flash").style.opacity = 0; |
| 692 | $("dead").style.display = "none"; |
| 693 | $("aimhint").style.display = "none"; |
| 694 | } |
| 695 | |
| 696 | /** Is this player standing where the spike arms? The grid says so. */ |
| 697 | function onSite(me) { |
| 698 | if (!map) return false; |
| 699 | const row = map.rows[Math.floor(me.y / map.tile)]; |
| 700 | const cell = row ? row[Math.floor(me.x / map.tile)] : ""; |
| 701 | return cell === "A" || cell === "B"; |
| 702 | } |
| 703 | |
| 704 | /** |
| 705 | * What just happened to whom: newest first, and gone a few seconds later. |
| 706 | * The server sends names and a gun and nothing else, so there is nothing |
| 707 | * here to read a position out of. |
| 708 | */ |
| 709 | function paintFeed(s) { |
| 710 | const box = $("feed"); |
| 711 | const lines = (s.feed ?? []).slice().reverse(); |
| 712 | // The age is bucketed into the key: an entry fades once on its way out |
| 713 | // rather than rebuilding the panel every frame. |
| 714 | const key = lines.map((l) => `${l.k}>${l.v}:${l.w}:${l.h}:${l.t > 6 ? "old" : "new"}`).join("|"); |
| 715 | if (box.dataset.key === key) return; |
| 716 | box.dataset.key = key; |
| 717 | box.replaceChildren(); |
| 718 | for (const line of lines) { |
| 719 | const row = document.createElement("div"); |
| 720 | row.style.opacity = line.t > 6 ? "0.5" : "1"; |
| 721 | const killer = document.createElement("span"); |
| 722 | killer.className = "k"; |
| 723 | killer.textContent = line.k ?? "—"; |
| 724 | const victim = document.createElement("span"); |
| 725 | victim.className = "v"; |
| 726 | victim.textContent = line.v; |
| 727 | const how = document.createElement("span"); |
| 728 | how.className = "w"; |
| 729 | how.textContent = `${line.w ? " " + line.w : " ability"}${line.h ? " ✧" : ""}`; |
| 730 | const arrow = document.createElement("span"); |
| 731 | arrow.textContent = " ▸ "; |
| 732 | row.append(killer, arrow, victim, how); |
| 733 | box.append(row); |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | /** |
| 738 | * Your team, always on screen: five slots, health, and struck through when |
| 739 | * somebody is dead. The one place both questions — who is with me, who is |
| 740 | * still up — are answered whether anybody is in sight or not. |
| 741 | */ |
| 742 | function paintRoster(s) { |
| 743 | const rows = roster(s); |
| 744 | const panel = $("roster"); |
| 745 | const key = rosterKey(rows); |
| 746 | if (panel.dataset.key === key) return; |
| 747 | panel.dataset.key = key; |
| 748 | panel.replaceChildren(); |
| 749 | for (const row of rows) { |
| 750 | const slot = document.createElement("div"); |
| 751 | slot.className = `slot${row.mine ? " mine" : ""}${row.alive ? "" : " down"}`; |
| 752 | slot.style.borderLeftColor = AGENT_COLOUR[row.agent] || "#4a5162"; |
| 753 | const who = document.createElement("span"); |
| 754 | who.className = "who"; |
| 755 | who.textContent = row.name; |
| 756 | const agent = document.createElement("span"); |
| 757 | agent.className = "agent"; |
| 758 | agent.textContent = row.alive ? row.agent : `${row.agent} · dead`; |
| 759 | if (row.spike) { |
| 760 | const spike = document.createElement("span"); |
| 761 | spike.className = "spike"; |
| 762 | spike.textContent = " spike"; |
| 763 | agent.append(spike); |
| 764 | } |
| 765 | const bar = document.createElement("span"); |
| 766 | bar.className = "hp"; |
| 767 | const fill = document.createElement("i"); |
| 768 | fill.style.width = `${row.hp}%`; |
| 769 | fill.style.background = row.hp > 40 ? "#6fcf6f" : "#e0a040"; |
| 770 | bar.append(fill); |
| 771 | slot.append(who, agent, bar); |
| 772 | panel.append(slot); |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | const kitOf = (id) => (agents ? agents.find((a) => a.id === id) : null); |
| 777 | |
| 778 | /** The four ability buttons, each saying what it does and what it has left. */ |
| 779 | function paintKit(s) { |
| 780 | const kit = $("kit"); |
| 781 | const agent = kitOf(s.me.agent); |
| 782 | const shape = |
| 783 | ["c", "q", "e", "x"].map((slot) => `${slot}${s.me.charges[slot]}${Math.ceil(s.me.cooldown[slot])}`).join("|") + |
| 784 | s.me.agent + |
| 785 | s.me.ult + |
| 786 | (agent ? "k" : ""); |
| 787 | if (KITS.shape === shape) return; |
| 788 | KITS.shape = shape; |
| 789 | kit.replaceChildren(); |
| 790 | for (const slot of ["c", "q", "e", "x"]) { |
| 791 | const ability = agent ? agent.abilities[slot] : null; |
| 792 | const button = document.createElement("button"); |
| 793 | const ready = slot === "x" ? s.me.ult >= s.me.ultNeeds : s.me.charges[slot] > 0 && s.me.cooldown[slot] <= 0; |
| 794 | button.disabled = !ready; |
| 795 | button.type = "button"; |
| 796 | const count = |
| 797 | slot === "x" |
| 798 | ? `${s.me.ult}/${s.me.ultNeeds}` |
| 799 | : s.me.cooldown[slot] > 0 |
| 800 | ? `${Math.ceil(s.me.cooldown[slot])}s` |
| 801 | : s.me.charges[slot]; |
| 802 | const name = document.createElement("span"); |
| 803 | name.textContent = `${slot.toUpperCase()}${ability ? " " + ability.name : ""}`; |
| 804 | const tally = document.createElement("b"); |
| 805 | tally.textContent = String(count); |
| 806 | button.append(name, tally); |
| 807 | if (ability) button.title = `${ability.name} — ${ability.text}`; |
| 808 | button.addEventListener("click", () => send({ t: "i", c: slot })); |
| 809 | kit.append(button); |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | /** Prices on every button, greyed when you cannot afford it. */ |
| 814 | function paintBuy(s) { |
| 815 | const agent = kitOf(s.me.agent); |
| 816 | for (const button of document.querySelectorAll("[data-buy]")) { |
| 817 | const what = button.dataset.buy; |
| 818 | let cost = Number(button.dataset.cost ?? 0); |
| 819 | if ((what === "c" || what === "q") && agent) { |
| 820 | const ability = agent.abilities[what]; |
| 821 | cost = ability.cost; |
| 822 | button.replaceChildren(); |
| 823 | const name = document.createElement("span"); |
| 824 | name.textContent = `${what.toUpperCase()} ${ability.name}`; |
| 825 | const price = document.createElement("b"); |
| 826 | price.textContent = `${ability.cost} · ${s.me.charges[what]}/${ability.charges}`; |
| 827 | button.append(name, price); |
| 828 | button.title = `${ability.text} (${ability.charges} charge${ability.charges === 1 ? "" : "s"} a round)`; |
| 829 | } |
| 830 | button.disabled = cost > s.me.credits; |
| 831 | } |
| 832 | for (const button of document.querySelectorAll("[data-agent]")) { |
| 833 | const picked = button.dataset.agent === s.me.agent; |
| 834 | button.style.outline = picked ? "2px solid #6fcf9f" : ""; |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | // ------------------------------------------------------------------- start |
| 839 | |
| 840 | Promise.all([fetch("/map.json").then((r) => r.json()), fetch("/agents.json").then((r) => r.json())]) |
| 841 | .then(([mapData, kit]) => { |
| 842 | map = mapData; |
| 843 | agents = kit.agents; |
| 844 | const rows = map.rows; |
| 845 | const cols = rows[0].length; |
| 846 | solid = (col, row) => |
| 847 | col < 0 || row < 0 || row >= rows.length || col >= cols || rows[row][col] === "#"; |
| 848 | // The same grid the server collides against, so a guess about your own |
| 849 | // movement lands where the server's answer is about to. |
| 850 | world = { solid, tile: map.tile, r: BODY_R }; |
| 851 | $("stage").dataset.mode = mode; |
| 852 | fillHelp(); |
| 853 | resize(); |
| 854 | connect(); |
| 855 | }) |
| 856 | .catch(() => ($("conn").textContent = "offline")); |
| 857 | |
| 858 | /** The card says the round, the sides, the keys and the kit, in that order. */ |
| 859 | function fillHelp() { |
| 860 | const list = $("helpagents"); |
| 861 | if (!list || !agents) return; |
| 862 | list.replaceChildren(); |
| 863 | for (const agent of agents) { |
| 864 | const li = document.createElement("li"); |
| 865 | li.textContent = `${agent.name} (${agent.role}) — ${agent.blurb}`; |
| 866 | list.append(li); |
| 867 | } |
| 868 | } |
| 869 | |
| 870 | requestAnimationFrame(frame); |