Split The code is public; the app answers only to the crew.

What a frame costs, counted: a draw-call budget the recording GL context enforces #116

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

vesper/cs:vesper/89-what-a-frame-costs-counted-a-draw-call-b → main 1 commit fork

  • Merged. vesper/89-what-a-frame-costs-counted-a-draw-call-b was merged into main as 779ddc6.

Review

Sign in to review this change.
3 files changed +240 −3
README.md +11
@@ -295,6 +295,17 @@ pixels you are getting. Nothing on the page moves when it changes. Only frames
295295 that were actually drawn in an unclamped time count towards it, so a pause or a
296296 minute in another tab cannot talk the scale down.
297297
298 What a frame costs is counted, not hoped for: one draw for the level, one per
299 player drawn, one per body, one per gun on the floor, one per grenade, one for
300 a bomb that is down, one batched draw for every line and one more for the
301 muzzle flashes over them, plus the view model and its own flash — two programs,
302 switched at most four times. `src/client/renderer.test.ts` draws a frame
303 through the recording context and checks the count against that rule, so a
304 change that costs a second draw per player fails the check rather than a phone;
305 the worst round the game can build (ten players, ten bodies, a floor of
306 twenty-four dropped guns, ten grenades in the air, a planted bomb and a screen
307 full of tracers) is 59 draws against a budget of 80.
308
298309 The radar in the bottom-left corner is your view, not the room: rotated so
299310 the way you are facing is up, it shows your living teammates, the bomb once
300311 it is planted, and both sites marked A and B — never the other team, because
src/client/renderer.test.ts +222 −3
@@ -8,15 +8,19 @@
88 * listeners, so a lost context and the restore after it are two events a test
99 * can fire, and what the renderer does about them is the calls it stops making
1010 * and the ones it makes again.
11 *
12 * And what the frame costs: the last section counts every `drawElements`,
13 * `drawArrays` and `useProgram` a frame makes, against the rule they follow
14 * and against a ceiling the worst round this game can build may not cross.
1115 */
1216
1317 import { expect, test } from "bun:test";
1418 import { addBody } from "./bodies.ts";
1519 import { advance, TICK, waiting } from "./loop.ts";
1620 import { SHORT } from "./match.ts";
17 import { HELD_MUZZLE, levelMesh, viewModelMesh } from "./models.ts";
21 import { HELD_MUZZLE, levelMesh, muzzle, viewModelMesh } from "./models.ts";
1822 import { createRenderer, LINE_CAPACITY, type Camera, type Renderer, type RendererHooks } from "./renderer.ts";
19 import type { WeaponId } from "./weapons.ts";
23 import { WEAPONS, type WeaponId } from "./weapons.ts";
2024 import { createWorld, eyePos, type Effect, type Player, type World } from "./world.ts";
2125
2226 type Call = { name: string; args: unknown[] };
@@ -33,7 +37,15 @@ function recorder(): {
3337 calls.push({ name, args });
3438 return result;
3539 };
36 const handle = (name: string) => log(name, { name });
40 // A handle per call, the way GL hands one out: two programs are two objects,
41 // so a test can say which of them a `useProgram` switched to.
42 let handles = 0;
43 const handle = (name: string) =>
44 (...args: unknown[]): unknown => {
45 calls.push({ name, args });
46 handles += 1;
47 return { name, id: handles };
48 };
3749 const methods: Record<string, unknown> = {
3850 createShader: handle("shader"), shaderSource: log("shaderSource"), compileShader: log("compileShader"),
3951 getShaderParameter: log("getShaderParameter", true), getShaderInfoLog: log("getShaderInfoLog", ""),
@@ -419,3 +431,210 @@ test("a lost view waits exactly as a pause does: no steps, and nothing banked",
419431 expect(halted()).toBe(false);
420432 expect(advance(accumulator, 1 / 60, halted()).steps).toBe(1);
421433 });
434
435 // --- what a frame costs
436
437 /**
438 * The rule a frame's draws follow, as a sum rather than a number. Nothing here
439 * is a count taken from the renderer: it is read off the world, so a change
440 * that adds a second draw per player disagrees with it and fails.
441 *
442 * level 1, always — one static mesh, one indexed draw
443 * players one per player who is alive and is not the camera's own
444 * bodies one per corpse of this round, the player mesh again
445 * pickups one per gun on the floor
446 * grenades one per grenade in the air
447 * bomb one while it is down (planted or dropped)
448 * lines one batched draw for the world's tracers, sparks and beam
449 * flashes one more, additive, for everyone else's muzzles
450 * view model one while the holder is alive and not scoped
451 * view flash one more for the star off the end of it
452 *
453 * Age is not a term in it: every effect in the worlds below is stamped at
454 * `world.time`, so a live effect is one that is there at all. The rule refuses
455 * a stale one rather than guessing which of the renderer's windows it fell out
456 * of — a test that pinned those windows would pin them twice.
457 */
458 function ruledDraws(world: World, view: Player): Record<string, number> {
459 for (const effect of world.effects)
460 if (effect.at !== world.time) throw new Error("this rule only counts effects stamped now");
461 if (view.lastShotAt !== world.time && world.time - view.lastShotAt < 1)
462 throw new Error("this rule only counts a shot of the view's own stamped now");
463
464 const down = world.bomb.state === "planted" || world.bomb.state === "dropped";
465 const spark = world.effects.some((e) => e.kind === "tracer" || e.kind === "impact" || e.kind === "blood");
466 // Somebody else's trigger, on a gun that has a muzzle: a knife flashes not
467 // at all, and the view's own gun is the one below and not this pass.
468 const flashed = world.effects.some(
469 (e) => e.kind === "shot" && e.shooter !== view.id && muzzle(WEAPONS[e.weapon].kind) !== null);
470 const held = view.alive && !view.scoped;
471 return {
472 level: 1,
473 players: world.players.filter((p) => p.alive && p !== view).length,
474 bodies: world.bodies.length,
475 pickups: world.pickups.length,
476 grenades: world.grenades.length,
477 bomb: down ? 1 : 0,
478 lines: spark || world.bomb.state === "planted" ? 1 : 0,
479 flashes: flashed ? 1 : 0,
480 viewModel: held ? 1 : 0,
481 viewFlash: held && muzzle(WEAPONS[view.weapon].kind) !== null && view.lastShotAt === world.time ? 1 : 0,
482 };
483 }
484
485 const total = (terms: Record<string, number>): number =>
486 Object.values(terms).reduce((sum, n) => sum + n, 0);
487
488 /** The two programs `build` linked, in the order it linked them. */
489 function linkedPrograms(calls: Call[]): { scene: unknown; lines: unknown } {
490 const linked = calls.filter((c) => c.name === "linkProgram").map((c) => c.args[0]);
491 expect(linked.length).toBe(2);
492 return { scene: linked[0], lines: linked[1] };
493 }
494
495 /** Which program each `useProgram` of this frame switched to, in order. */
496 const passes = (calls: Call[], of: { scene: unknown; lines: unknown }): string[] =>
497 calls.filter((c) => c.name === "useProgram")
498 .map((c) => (c.args[0] === of.scene ? "scene" : c.args[0] === of.lines ? "lines" : "unknown"));
499
500 /**
501 * The passes the same rule predicts: the scene, then the world's lines if it
502 * drew any, then the scene again for the view model's own projection and
503 * depth, then the lines again for the flash off its barrel. Two programs, and
504 * never a third.
505 */
506 function ruledPasses(terms: Record<string, number>): string[] {
507 const list = ["scene"];
508 if ((terms.lines as number) + (terms.flashes as number) > 0) list.push("lines");
509 if ((terms.viewModel as number) > 0) list.push("scene");
510 if ((terms.viewFlash as number) > 0) list.push("lines");
511 return list;
512 }
513
514 test("a frame's draws are the world's, one apiece, and its passes are two programs", () => {
515 const { canvas, calls } = recorder();
516 const renderer = attach(canvas);
517 const of = linkedPrograms(calls);
518 const world = scene();
519
520 // A quiet frame: the level, nine other players, and the gun in your hands.
521 const quiet = ruledDraws(world, world.me);
522 expect(quiet).toEqual({
523 level: 1, players: 9, bodies: 0, pickups: 0, grenades: 0, bomb: 0,
524 lines: 0, flashes: 0, viewModel: 1, viewFlash: 0,
525 });
526 let frameCalls = record(renderer, calls, world);
527 expect(count(frameCalls, "drawElements") + count(frameCalls, "drawArrays")).toBe(total(quiet));
528 expect(passes(frameCalls, of)).toEqual(["scene", "scene"]);
529
530 // One more player is one more draw and not two: this is the assertion that
531 // fails if a muzzle, a pair of legs or a shadow becomes a draw of its own.
532 const twin = { ...(world.players[3] as Player), id: 97 };
533 world.players.push(twin);
534 frameCalls = record(renderer, calls, world);
535 expect(count(frameCalls, "drawElements") + count(frameCalls, "drawArrays"))
536 .toBe(total(quiet) + 1);
537 expect(total(ruledDraws(world, world.me))).toBe(total(quiet) + 1);
538 world.players.pop();
539
540 // And a loud one: bodies, guns on the floor, grenades in the air, a bomb
541 // down and lines over the lot. Every term of the rule non-zero at once.
542 for (let i = 0; i < 4; i += 1)
543 addBody(world.bodies, { id: 30 + i, team: "t", pos: [i * 96, 0, 0], yaw: i * 40 }, world.boxes, world.time);
544 for (let i = 0; i < 6; i += 1)
545 world.pickups.push({ weapon: "ak47", pos: [i * 64, 128, 0], ammo: { mag: 30, reserve: 90 } });
546 world.grenades.push({ kind: "he", owner: world.me.id, team: "ct", pos: [0, 0, 60], vel: [200, 0, 0], fuse: 1 });
547 world.bomb.state = "planted";
548 world.bomb.pos = [256, 256, 0];
549 world.effects.push({ kind: "tracer", at: world.time, from: [0, 0, 40], to: [400, 0, 40] });
550 world.effects.push({ kind: "impact", at: world.time, pos: [400, 0, 40], normal: [1, 0, 0] });
551 world.effects.push({ kind: "blood", at: world.time, pos: [200, 0, 40] });
552 const shooter = world.players.find((p) => p !== world.me && p.alive) as Player;
553 world.effects.push(shotBy(world, shooter, "ak47"));
554 world.me.lastShotAt = world.time;
555
556 const loud = ruledDraws(world, world.me);
557 for (const [term, n] of Object.entries(loud)) expect([term, n > 0]).toEqual([term, true]);
558 frameCalls = record(renderer, calls, world);
559 expect(count(frameCalls, "drawElements") + count(frameCalls, "drawArrays")).toBe(total(loud));
560 // Scene, the world's lines, the scene again for the hands, the lines again
561 // for the flash off them. Four switches of two programs, and no third one.
562 expect(passes(frameCalls, of)).toEqual(ruledPasses(loud));
563 expect(passes(frameCalls, of)).toEqual(["scene", "lines", "scene", "lines"]);
564 expect(new Set(passes(frameCalls, of)).size).toBe(2);
565 });
566
567 /**
568 * The ceiling. Not what a frame draws today — what the worst round this game
569 * can build is allowed to draw, ever.
570 *
571 * Where the number comes from: 60 fps on a phone is 16.6 ms of wall clock for
572 * everything — the fixed-step simulation, ten bots thinking, the HUD's 2D
573 * canvas and this renderer. A draw here is one `uniformMatrix4fv`, one
574 * `uniform3f` and one indexed draw of a mesh that is already resident, which
575 * on a mid-range phone's browser costs tens of microseconds of CPU rather than
576 * any GPU time worth counting. At the pessimistic end of that — call it 40 µs
577 * a draw on a phone that is throttling — eighty draws is about 3 ms, under a
578 * fifth of the frame, which is the most of it the draws may have with the
579 * simulation and the HUD still to pay for.
580 *
581 * So eighty is the budget. The worst frame below is 59 of it, and the rest is
582 * not spare: it is what an unlucky round has in hand. A change that wants the
583 * eighty-first draw batches something away instead of raising this line.
584 */
585 const FRAME_BUDGET = 80;
586
587 test("the worst round this game can build stays inside the frame's draw budget", () => {
588 const { canvas, calls } = recorder();
589 const renderer = attach(canvas);
590 const of = linkedPrograms(calls);
591 const world = scene();
592 record(renderer, calls, world); // the level and the view model go up here
593
594 // Ten players, all alive — the camera is inside one, so nine are drawn.
595 expect(world.players.length).toBe(10);
596 // Ten bodies: more than a round can hold at once alongside ten living
597 // players, which is the point of a ceiling.
598 for (let i = 0; i < 10; i += 1)
599 addBody(world.bodies, { id: 40 + i, team: i % 2 ? "t" : "ct", pos: [i * 72, 0, 0], yaw: i * 36 }, world.boxes, world.time);
600 // A floor of dropped guns: `MAX_PICKUPS` in world.ts is 24 and it shifts the
601 // oldest off, so 24 is every gun that can be lying about at once.
602 for (let i = 0; i < 24; i += 1)
603 world.pickups.push({ weapon: "m4a4", pos: [i * 48, 256, 0], ammo: { mag: 30, reserve: 90 } });
604 // Every player's grenade in the air on the same frame.
605 for (const p of world.players)
606 world.grenades.push({ kind: "he", owner: p.id, team: p.team, pos: [p.pos[0], p.pos[1], 60], vel: [0, 0, 100], fuse: 2 });
607 world.bomb.state = "planted";
608 world.bomb.pos = [512, 512, 0];
609 // A screen full of effects: forty tracers, forty sparks, twenty hits, and
610 // every gun in the server firing at once.
611 for (let i = 0; i < 40; i += 1) {
612 world.effects.push({ kind: "tracer", at: world.time, from: [0, 0, 40], to: [i * 16, 300, 40] });
613 world.effects.push({ kind: "impact", at: world.time, pos: [i * 16, 300, 40], normal: [0, -1, 0] });
614 }
615 for (let i = 0; i < 20; i += 1)
616 world.effects.push({ kind: "blood", at: world.time, pos: [i * 32, 100, 40] });
617 for (const p of world.players) world.effects.push(shotBy(world, p, "ak47"));
618 world.me.lastShotAt = world.time;
619
620 const terms = ruledDraws(world, world.me);
621 const frameCalls = record(renderer, calls, world);
622 const draws = count(frameCalls, "drawElements") + count(frameCalls, "drawArrays");
623 expect(draws).toBe(total(terms));
624 expect(draws).toBeLessThanOrEqual(FRAME_BUDGET);
625 // Said again as the sum it is, so a reader can see which term grew when this
626 // number moves: 1 level + 9 players + 10 bodies + 24 pickups + 10 grenades
627 // + 1 bomb + 2 line draws + the view model and its flash.
628 expect(terms).toEqual({
629 level: 1, players: 9, bodies: 10, pickups: 24, grenades: 10, bomb: 1,
630 lines: 1, flashes: 1, viewModel: 1, viewFlash: 1,
631 });
632
633 // The passes do not grow with the world: the worst frame is still the two
634 // programs, switched four times.
635 expect(passes(frameCalls, of)).toEqual(["scene", "lines", "scene", "lines"]);
636 // Nor does the worst frame spill the line buffer or upload a mesh.
637 for (const run of lineRuns(frameCalls))
638 expect(run.first + run.count).toBeLessThanOrEqual(LINE_CAPACITY);
639 expect(count(frameCalls, "bufferData")).toBe(0);
640 });
src/readme.test.ts +7
@@ -62,6 +62,13 @@ test("the readme says what happens when the browser takes the view away", () =>
6262 expect(playing).toContain("builds\neverything it owns a second time");
6363 });
6464
65 test("the readme quotes the draw budget the renderer's own test enforces", () => {
66 const budget = /const FRAME_BUDGET = (\d+);/.exec(read("src/client/renderer.test.ts"));
67 expect(budget).not.toBeNull();
68 // The number lives in the test that enforces it; the README may only repeat it.
69 expect(section("Playing")).toContain(`a budget of ${(budget as RegExpExecArray)[1]}`);
70 });
71
6572 test("the readme names the check and the build the same way the app does", () => {
6673 const local = section("Run it locally");
6774 const { app } = JSON.parse(read("forge.json")) as { app: { test: string } };

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs