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

The view comes back: survive a lost WebGL context instead of playing on behind a black canvas #75

Merged opened this

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

Merged

vesper/cs:vesper/68-the-view-comes-back-survive-a-lost-webgl → main 1 commit fork

  • Merged. vesper/68-the-view-comes-back-survive-a-lost-webgl was merged into main as 861e20b.

Review

Sign in to review this change.
7 files changed +352 −52
README.md +18 −1
@@ -146,6 +146,20 @@ buy menu is the exception: it opens in the freeze time, and a frozen freeze
146146 clock is a round that never starts, so the world goes on while you shop (your
147147 shots do not — a click on a gun is a purchase and never a trigger).
148148
149 **If the browser takes the 3D view away** — a phone that backgrounded the tab,
150 an operating system reclaiming graphics memory, a driver that reset — the match
151 pauses instead of playing on behind a frozen canvas. The renderer catches
152 `webglcontextlost`, asks the browser for the context back (without that the
153 loss is permanent), and stops making GL calls entirely; the pause overlay comes
154 up with a line saying the view is coming back, and **Resume** is disabled while
155 there is nothing to resume to. When the context returns the renderer builds
156 everything it owns a second time — both programs, the texture array, the
157 meshes, the level and the line buffer — at the same render scale and the same
158 viewport, and the next frame is the scene you left. No reload, no lost round,
159 and the level is uploaded once for the new context rather than once a frame. If
160 the browser never gives it back, the overlay is where the match stays: **Leave
161 match** goes to the menu.
162
149163 A **Fullscreen** button sits in the menu and in the pause overlay — wherever
150164 the browser can do it at all; iOS Safari on an iPhone cannot, so there the
151165 button is not shown and the game plays exactly as it does without one. It
@@ -221,7 +235,10 @@ with the canvas as you turn; nobody re-walks the grid to draw it.
221235 `renderer`, `hud`, `input`, `audio`, `main`.
222236 Everything except the last five is headless and tested; `renderer` and `hud`
223237 are checked against recording contexts, which is how a frame's draws are
224 counted without a GPU.
238 counted without a GPU — and how a lost context is tested too, since the
239 recorder's canvas takes listeners and a test can fire `webglcontextlost` at
240 it. Every GL resource the renderer owns comes from one `build(gl)`, so the
241 restore is that same function a second time.
225242 - `src/rl/` — training, which the game never imports: `arena` is the environment
226243 (a real duel on de_forge with the round and the economy taken out), `ppo` is
227244 the algorithm, with its backward pass checked against finite differences, and
src/client/main.ts +33 −5
@@ -59,7 +59,23 @@ function boot(): void {
5959 const fullscreenMenuButton = $<HTMLButtonElement>("fullscreen-menu");
6060 const fullscreenPauseButton = $<HTMLButtonElement>("fullscreen-pause");
6161
62 const renderer = createRenderer(scene);
62 const viewLost = $("view-lost");
63 const resumeButton = $<HTMLButtonElement>("resume");
64 // A lost WebGL context is a pause with a reason: the overlay goes up, the
65 // world stops, and Resume is not offered until there is something to resume
66 // to — playing on behind a frozen canvas is the failure this prevents.
67 const renderer = createRenderer(scene, {
68 onLost: () => {
69 show(viewLost, true);
70 resumeButton.disabled = true;
71 pauseMatch();
72 if (!pause.hidden) focusPause();
73 },
74 onRestored: () => {
75 show(viewLost, false);
76 resumeButton.disabled = false;
77 },
78 });
6379 if (renderer === null) {
6480 menu.innerHTML = "<h2>No WebGL2</h2><p>This browser cannot run the game. Everything else on the page still works.</p>";
6581 return;
@@ -151,9 +167,11 @@ function boot(): void {
151167 * second copy of the answer to go stale — which of them count is loop.ts's
152168 * decision, not this file's. A dialog over a live match is a player standing
153169 * still in the open while the clock, the bots and the bomb go on without
154 * them.
170 * them — and so is a view the browser has taken away, which is the one
171 * reason that is not an overlay: it is a flag on the renderer, set by the
172 * event, read once a frame and never asked of the GL object.
155173 */
156 const paused = (): boolean => waiting(!pause.hidden, !summaryPanel.hidden);
174 const paused = (): boolean => waiting(!pause.hidden, !summaryPanel.hidden) || renderer.lost;
157175
158176 // A touch screen has no pointer lock — asking for it there is a promise that
159177 // rejects — so the phone build never asks, and the look comes off the glass.
@@ -233,9 +251,14 @@ function boot(): void {
233251 show(pause, true);
234252 refreshPad();
235253 document.exitPointerLock();
236 $("resume").focus();
254 focusPause();
237255 }
238256
257 /** Whatever the overlay offers: Resume, unless there is no view to go back to. */
258 const focusPause = (): void => {
259 (resumeButton.disabled ? $("quit") : resumeButton).focus();
260 };
261
239262 controls.onPause = () => {
240263 if (buyPanel.hidden) pauseMatch();
241264 };
@@ -316,10 +339,15 @@ function boot(): void {
316339 audio.resume();
317340 lock();
318341 localStorage.setItem("cs.name", name);
342 // Every overlay is down by now, so the only thing left that can be waiting
343 // is a view the browser took away while the menu was up: a match started
344 // into that one waits from its first frame rather than running unseen.
345 if (paused()) pauseMatch();
319346 }
320347
321348 $("play").addEventListener("click", start);
322 $("resume").addEventListener("click", () => {
349 resumeButton.addEventListener("click", () => {
350 if (renderer.lost) return;
323351 show(pause, false);
324352 refreshPad();
325353 lock();
src/client/renderer.test.ts +152 −3
@@ -3,17 +3,29 @@
33 * the calls it would have made. What can be checked here is the shape of a
44 * frame — which player is skipped, how many draws a body costs, and that a
55 * body costs nothing at all in a round where nobody died.
6 *
7 * And the lifetime of the context itself: the canvas here remembers its
8 * listeners, so a lost context and the restore after it are two events a test
9 * can fire, and what the renderer does about them is the calls it stops making
10 * and the ones it makes again.
611 */
712
813 import { expect, test } from "bun:test";
914 import { addBody } from "./bodies.ts";
15 import { advance, TICK, waiting } from "./loop.ts";
1016 import { SHORT } from "./match.ts";
11 import { createRenderer, type Camera } from "./renderer.ts";
17 import { levelMesh } from "./models.ts";
18 import { createRenderer, type Camera, type Renderer, type RendererHooks } from "./renderer.ts";
1219 import { createWorld, type Player, type World } from "./world.ts";
1320
1421 type Call = { name: string; args: unknown[] };
1522
16 function recorder(): { canvas: HTMLCanvasElement; calls: Call[] } {
23 function recorder(): {
24 canvas: HTMLCanvasElement;
25 calls: Call[];
26 /** Fire an event at the canvas, the way the browser does. */
27 fire(type: string, event?: Record<string, unknown>): void;
28 } {
1729 const calls: Call[] = [];
1830 const log = (name: string, result: unknown = undefined) =>
1931 (...args: unknown[]): unknown => {
@@ -45,11 +57,25 @@ function recorder(): { canvas: HTMLCanvasElement; calls: Call[] } {
4557 get: (target, prop) =>
4658 typeof prop === "string" ? target[prop] ?? prop.length + 0x1000 : undefined,
4759 });
60 // A canvas that remembers its listeners, the way input.test.ts's `target`
61 // does: the renderer's own lifetime is two events on this element.
62 const listeners = new Map<string, Set<(event: unknown) => void>>();
4863 const canvas = {
4964 clientWidth: 1280, clientHeight: 720, width: 0, height: 0,
5065 getContext: () => gl,
66 addEventListener(type: string, fn: (event: unknown) => void): void {
67 const set = listeners.get(type) ?? new Set<(event: unknown) => void>();
68 set.add(fn);
69 listeners.set(type, set);
70 },
71 removeEventListener(type: string, fn: (event: unknown) => void): void {
72 listeners.get(type)?.delete(fn);
73 },
5174 };
52 return { canvas: canvas as unknown as HTMLCanvasElement, calls };
75 const fire = (type: string, event: Record<string, unknown> = {}): void => {
76 for (const fn of Array.from(listeners.get(type) ?? [])) fn({ preventDefault: () => {}, ...event });
77 };
78 return { canvas: canvas as unknown as HTMLCanvasElement, calls, fire };
5379 }
5480
5581 const CAMERA: Camera = { pos: [0, 0, 64], yaw: 0, pitch: 0, fov: 90 };
@@ -127,3 +153,126 @@ test("a grenade in the air is one more draw, off a mesh uploaded before the fram
127153 world.grenades.length = 0;
128154 expect(frame(canvas, calls, world, world.me).length).toBe(empty);
129155 });
156
157 // --- a context the browser takes away
158
159 /** A renderer of this canvas's own, with the hooks main.ts would pass. */
160 const attach = (canvas: HTMLCanvasElement, hooks: RendererHooks = {}): Renderer =>
161 createRenderer(canvas, hooks) as Renderer;
162
163 /** One frame, and every call it made — not only the draws. */
164 function record(renderer: Renderer, calls: Call[], world: World): Call[] {
165 calls.length = 0;
166 renderer.draw(world, CAMERA, world.me, 1 / 60);
167 return calls.slice();
168 }
169
170 const count = (calls: Call[], name: string): number => calls.filter((c) => c.name === name).length;
171
172 test("a lost context is prevented, marks the renderer lost, and draws nothing at all", () => {
173 const { canvas, calls, fire } = recorder();
174 const world = scene();
175 let lost = 0;
176 const renderer = attach(canvas, { onLost: () => { lost += 1; } });
177 record(renderer, calls, world);
178 expect(renderer.lost).toBe(false);
179
180 let prevented = 0;
181 fire("webglcontextlost", { preventDefault: () => { prevented += 1; } });
182 // Without this the browser never even attempts a restore: the loss would be
183 // permanent whatever the renderer did next.
184 expect(prevented).toBe(1);
185 expect(renderer.lost).toBe(true);
186 expect(lost).toBe(1);
187
188 // Not a viewport, not a clear, not a single GL call while it is gone.
189 expect(record(renderer, calls, world)).toEqual([]);
190 expect(record(renderer, calls, world)).toEqual([]);
191
192 // A second loss before the restore is the same loss, not a second report.
193 fire("webglcontextlost");
194 expect(lost).toBe(1);
195 });
196
197 test("a restore builds the context again and uploads the level once, not once a frame", () => {
198 const { canvas, calls, fire } = recorder();
199 const world = scene();
200 let restored = 0;
201 const renderer = attach(canvas, { onRestored: () => { restored += 1; } });
202 const fresh = record(renderer, calls, world); // the level and the view model go up
203 const steady = record(renderer, calls, world);
204 expect(count(steady, "bufferData")).toBe(0);
205
206 fire("webglcontextlost");
207 calls.length = 0;
208 fire("webglcontextrestored");
209 expect(restored).toBe(1);
210 expect(renderer.lost).toBe(false);
211 // Both programs linked again and the texture array uploaded again: every
212 // handle died with the old context and none of them is reused.
213 expect(count(calls, "linkProgram")).toBe(2);
214 expect(count(calls, "texImage3D")).toBe(1);
215
216 const level = levelMesh(world.boxes).index.length;
217 const isLevel = (c: Call): boolean => c.name === "drawElements" && c.args[1] === level;
218 const back = record(renderer, calls, world);
219 // The same scene as before the loss, drawn the same way.
220 expect(count(back, "drawElements") + count(back, "drawArrays"))
221 .toBe(count(fresh, "drawElements") + count(fresh, "drawArrays"));
222 expect(back.filter(isLevel).length).toBe(1);
223 expect(count(back, "bufferData")).toBe(count(fresh, "bufferData"));
224 // …and it stays uploaded: the frame after the restore pays nothing again.
225 const after = record(renderer, calls, world);
226 expect(count(after, "bufferData")).toBe(0);
227 expect(after.filter(isLevel).length).toBe(1);
228 });
229
230 test("the render scale survives the loss, and the viewport comes back at it", () => {
231 const { canvas, calls, fire } = recorder();
232 const world = scene();
233 const renderer = attach(canvas);
234 renderer.setScale(0.5);
235 const half = record(renderer, calls, world).find((c) => c.name === "viewport");
236 expect(half?.args).toEqual([0, 0, 640, 360]);
237
238 fire("webglcontextlost");
239 fire("webglcontextrestored");
240 // A restore is not a reset: the scale `quality` last asked for is still the
241 // scale, and the drawing buffer is the size it was.
242 expect(record(renderer, calls, world).find((c) => c.name === "viewport")?.args)
243 .toEqual([0, 0, 640, 360]);
244 });
245
246 test("a lost view waits exactly as a pause does: no steps, and nothing banked", () => {
247 const { canvas, fire } = recorder();
248 // What main.ts does with the callback: the pause overlay goes up.
249 let pauseUp = false;
250 const renderer = attach(canvas, {
251 onLost: () => { pauseUp = true; },
252 onRestored: () => { pauseUp = true; }, // the overlay stays up; a person resumes
253 });
254 fire("webglcontextlost");
255 expect(pauseUp).toBe(true);
256
257 // main.ts's `paused()`, both halves: the overlay loop.ts counts, and the
258 // renderer's own flag, so a Resume clicked before the view is back is still
259 // a waiting match and not a world stepping behind a black canvas.
260 const halted = (): boolean => waiting(pauseUp, false) || renderer.lost;
261 expect(halted()).toBe(true);
262 let accumulator = TICK / 2;
263 for (let i = 0; i < 300; i += 1) {
264 const frame = advance(accumulator, 1 / 60, halted());
265 expect(frame.steps).toBe(0);
266 expect(frame.measured).toBe(false);
267 accumulator = frame.accumulator;
268 }
269 expect(accumulator).toBeCloseTo(TICK / 2, 12);
270
271 // Five seconds of lost view cost the match nothing, and the first frame back
272 // is an ordinary frame: no lost round, no flood of banked ticks.
273 fire("webglcontextrestored");
274 pauseUp = false;
275 expect(renderer.lost).toBe(false);
276 expect(halted()).toBe(false);
277 expect(advance(accumulator, 1 / 60, halted()).steps).toBe(1);
278 });
src/client/renderer.ts +131 −43
@@ -3,6 +3,14 @@
33 * draw, each player is one draw of a shared mesh, and tracers and sparks share
44 * a single line buffer that is refilled each frame. Nothing is allocated in
55 * the frame loop except the numbers that change.
6 *
7 * Every one of those resources is made by `build`, and `build` can be run
8 * again: a browser may take the context away at any moment — a phone
9 * backgrounded, an OS reclaiming GPU memory, a driver reset — and everything
10 * held here dies with it. `webglcontextlost` is caught and prevented (without
11 * `preventDefault` the browser never offers the context back), the renderer
12 * says it is lost so the loop can stop the match, `draw` makes no GL call at
13 * all, and `webglcontextrestored` builds the lot a second time.
614 */
715
816 import { fallenMatrix, multiply, perspective, viewMatrix, modelMatrix, type Vec3 } from "./math.ts";
@@ -148,37 +156,36 @@ const BODY_SHADE = 0.66;
148156 const BODY_FALL = 0.4;
149157
150158 const LINE_CAPACITY = 4096; // vertices
159 const LINE_BYTES = LINE_CAPACITY * 6 * Float32Array.BYTES_PER_ELEMENT;
151160
152 export type Renderer = {
153 /** `view` is the player the camera is inside: their own mesh is not drawn. */
154 draw(world: World, camera: Camera, view: Player, dt: number): void;
155 resize(): void;
156 /**
157 * The fraction of the device pixel ratio the drawing buffer uses. `quality`
158 * decides it from the frame time; the CSS size of the canvas never moves,
159 * so nothing on the page reflows when it changes.
160 */
161 setScale(scale: number): void;
162 readonly gl: WebGL2RenderingContext;
161 /**
162 * Everything that lives inside one GL context: the two programs and their
163 * uniform locations, the texture array, the four meshes that never change, the
164 * view models cached as a weapon is first held, the level once a world has
165 * been drawn, and the line buffer. Nothing outside this object is a GL handle,
166 * so a lost context is one reference to drop and one call to make again.
167 */
168 type Gpu = {
169 scene: WebGLProgram;
170 lines: WebGLProgram;
171 u: Record<"viewProj" | "model" | "eye" | "tint" | "fog" | "atlas" | "lineViewProj", WebGLUniformLocation | null>;
172 texture: WebGLTexture | null;
173 player: Buffers;
174 bomb: Buffers;
175 pickup: Buffers;
176 grenade: Buffers;
177 viewModels: Map<string, Buffers>;
178 /** Built on the first frame of a world, and once only: it is the map. */
179 level: Buffers | null;
180 lineVao: WebGLVertexArrayObject;
181 lineBuffer: WebGLBuffer | null;
163182 };
164183
165 export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
166 const gl = canvas.getContext("webgl2", { antialias: true, alpha: false, depth: true });
167 if (gl === null) return null;
168
184 function build(gl: WebGL2RenderingContext): Gpu {
169185 const scene = link(gl, SCENE_VS, SCENE_FS);
170186 const lines = link(gl, LINE_VS, LINE_FS);
171187 const uniform = (program: WebGLProgram, name: string): WebGLUniformLocation | null =>
172188 gl.getUniformLocation(program, name);
173 const u = {
174 viewProj: uniform(scene, "uViewProj"),
175 model: uniform(scene, "uModel"),
176 eye: uniform(scene, "uEye"),
177 tint: uniform(scene, "uTint"),
178 fog: uniform(scene, "uFog"),
179 atlas: uniform(scene, "uAtlas"),
180 lineViewProj: uniform(lines, "uViewProj"),
181 };
182189
183190 const texture = gl.createTexture();
184191 gl.bindTexture(gl.TEXTURE_2D_ARRAY, texture);
@@ -192,31 +199,106 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
192199 gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_S, gl.REPEAT);
193200 gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_T, gl.REPEAT);
194201
195 let levelBuffers: Buffers | null = null;
196 const player = upload(gl, playerMesh());
197 const bomb = upload(gl, bombMesh());
198 const pickup = upload(gl, pickupMesh());
199 const grenade = upload(gl, grenadeMesh());
200 const viewModels = new Map<string, Buffers>();
201
202202 // One buffer for every line drawn this frame: tracers, sparks, the bomb beam.
203 const lineData = new Float32Array(LINE_CAPACITY * 6);
204203 const lineVao = gl.createVertexArray() as WebGLVertexArrayObject;
205204 const lineBuffer = gl.createBuffer();
206205 gl.bindVertexArray(lineVao);
207206 gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer);
208 gl.bufferData(gl.ARRAY_BUFFER, lineData.byteLength, gl.DYNAMIC_DRAW);
207 gl.bufferData(gl.ARRAY_BUFFER, LINE_BYTES, gl.DYNAMIC_DRAW);
209208 gl.enableVertexAttribArray(0);
210209 gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0);
211210 gl.enableVertexAttribArray(1);
212211 gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 24, 12);
213212 gl.bindVertexArray(null);
214213
214 // Context state, not a resource, but it is lost with the context all the
215 // same: a rebuilt renderer that forgot this would draw with no depth test.
215216 gl.enable(gl.DEPTH_TEST);
216217 gl.enable(gl.CULL_FACE);
217218 gl.cullFace(gl.BACK);
218219 gl.clearColor(SKY[0], SKY[1], SKY[2], 1);
219220
221 return {
222 scene,
223 lines,
224 u: {
225 viewProj: uniform(scene, "uViewProj"),
226 model: uniform(scene, "uModel"),
227 eye: uniform(scene, "uEye"),
228 tint: uniform(scene, "uTint"),
229 fog: uniform(scene, "uFog"),
230 atlas: uniform(scene, "uAtlas"),
231 lineViewProj: uniform(lines, "uViewProj"),
232 },
233 texture,
234 player: upload(gl, playerMesh()),
235 bomb: upload(gl, bombMesh()),
236 pickup: upload(gl, pickupMesh()),
237 grenade: upload(gl, grenadeMesh()),
238 viewModels: new Map<string, Buffers>(),
239 level: null,
240 lineVao,
241 lineBuffer,
242 };
243 }
244
245 export type Renderer = {
246 /** `view` is the player the camera is inside: their own mesh is not drawn. */
247 draw(world: World, camera: Camera, view: Player, dt: number): void;
248 resize(): void;
249 /**
250 * The fraction of the device pixel ratio the drawing buffer uses. `quality`
251 * decides it from the frame time; the CSS size of the canvas never moves,
252 * so nothing on the page reflows when it changes.
253 */
254 setScale(scale: number): void;
255 /**
256 * Has the browser taken the context away? The loop reads this once a frame —
257 * it is a flag set by an event, never a `gl.isContextLost()` in the frame
258 * path — and a lost view waits exactly as a pause does.
259 */
260 readonly lost: boolean;
261 readonly gl: WebGL2RenderingContext;
262 };
263
264 export type RendererHooks = {
265 /** The context is gone: stop the match, nothing will be drawn until it is back. */
266 onLost?: () => void;
267 /** It came back and every resource has been built again: drawing may resume. */
268 onRestored?: () => void;
269 };
270
271 export function createRenderer(canvas: HTMLCanvasElement, hooks: RendererHooks = {}): Renderer | null {
272 const gl = canvas.getContext("webgl2", { antialias: true, alpha: false, depth: true });
273 if (gl === null) return null;
274
275 let gpu = build(gl);
276 let lost = false;
277
278 canvas.addEventListener("webglcontextlost", (event: Event) => {
279 // Without this the browser never even attempts a restore, and the loss is
280 // permanent by construction.
281 event.preventDefault();
282 if (lost) return;
283 lost = true;
284 hooks.onLost?.();
285 });
286 canvas.addEventListener("webglcontextrestored", () => {
287 if (!lost) return;
288 // Every handle in the old `gpu` died with the old context — deleting them
289 // now is a no-op — so dropping the object is the whole of the cleanup.
290 gpu = build(gl);
291 lost = false;
292 hooks.onRestored?.();
293 });
294
295 // The scratch the lines are filled into is this side of the bus: it survives
296 // a lost context, so it is made once and not in `build`.
297 const lineData = new Float32Array(LINE_CAPACITY * 6);
298
299 // The render scale is a decision, not a resource: a restore comes back at
300 // whatever `quality` had last asked for, and `draw` sets the viewport from
301 // the canvas it sizes, so the view returns exactly as it went.
220302 let scale = MAX_SCALE;
221303
222304 const resize = (): void => {
@@ -237,6 +319,11 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
237319 let bobPhase = 0;
238320
239321 const draw = (world: World, camera: Camera, view: Player, dt: number): void => {
322 // The flag the event set, asked once: a GL call on a lost context is at
323 // best ignored and `isContextLost()` is a synchronous question the frame
324 // path should never have to ask.
325 if (lost) return;
326 const { u, player, bomb, pickup, grenade, viewModels } = gpu;
240327 resize();
241328 const width = canvas.width, height = canvas.height;
242329 gl.viewport(0, 0, width, height);
@@ -250,11 +337,12 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
250337 const look = viewMatrix(camera.pos, camera.yaw, camera.pitch);
251338 const viewProj = multiply(proj, look);
252339
253 if (levelBuffers === null) levelBuffers = upload(gl, levelMesh(world.boxes));
340 if (gpu.level === null) gpu.level = upload(gl, levelMesh(world.boxes));
341 const level = gpu.level;
254342
255 gl.useProgram(scene);
343 gl.useProgram(gpu.scene);
256344 gl.activeTexture(gl.TEXTURE0);
257 gl.bindTexture(gl.TEXTURE_2D_ARRAY, texture);
345 gl.bindTexture(gl.TEXTURE_2D_ARRAY, gpu.texture);
258346 gl.uniform1i(u.atlas, 0);
259347 gl.uniformMatrix4fv(u.viewProj, false, viewProj);
260348 gl.uniform3fv(u.eye, camera.pos);
@@ -263,8 +351,8 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
263351 const identity = modelMatrix([0, 0, 0], 0);
264352 gl.uniformMatrix4fv(u.model, false, identity);
265353 gl.uniform3f(u.tint, 1, 1, 1);
266 gl.bindVertexArray(levelBuffers.vao);
267 gl.drawElements(gl.TRIANGLES, levelBuffers.count, gl.UNSIGNED_INT, 0);
354 gl.bindVertexArray(level.vao);
355 gl.drawElements(gl.TRIANGLES, level.count, gl.UNSIGNED_INT, 0);
268356
269357 // The player the camera is inside is the one we skip — while dead that is
270358 // the teammate being watched, not the person, who is now a body below.
@@ -363,10 +451,10 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
363451 push(world.bomb.pos[0], world.bomb.pos[1], world.bomb.pos[2] + 140, 1 * blink, 0.15, 0.1);
364452 }
365453 if (n > 0) {
366 gl.useProgram(lines);
454 gl.useProgram(gpu.lines);
367455 gl.uniformMatrix4fv(u.lineViewProj, false, viewProj);
368 gl.bindVertexArray(lineVao);
369 gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer);
456 gl.bindVertexArray(gpu.lineVao);
457 gl.bindBuffer(gl.ARRAY_BUFFER, gpu.lineBuffer);
370458 gl.bufferSubData(gl.ARRAY_BUFFER, 0, lineData, 0, n * 6);
371459 gl.drawArrays(gl.LINES, 0, n - (n % 2));
372460 }
@@ -386,7 +474,7 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
386474 viewModels.set(kind, model);
387475 }
388476 gl.clear(gl.DEPTH_BUFFER_BIT);
389 gl.useProgram(scene);
477 gl.useProgram(gpu.scene);
390478 const vmProj = perspective(58, aspect, 0.05, 40);
391479 gl.uniformMatrix4fv(u.viewProj, false, vmProj);
392480 gl.uniform3f(u.tint, 1, 1, 1);
@@ -402,5 +490,5 @@ export function createRenderer(canvas: HTMLCanvasElement): Renderer | null {
402490 gl.bindVertexArray(null);
403491 };
404492
405 return { draw, resize, setScale, gl };
493 return { draw, resize, setScale, gl, get lost(): boolean { return lost; } };
406494 }
src/pages/game.test.ts +8
@@ -50,3 +50,11 @@ test("a fullscreen control sits in the menu and in the pause overlay", () => {
5050 expect(pause).toContain(`id="fullscreen-pause"`);
5151 expect(pause).toContain(`aria-pressed="false"`);
5252 });
53
54 test("the pause overlay carries the line a lost view raises", () => {
55 const pause = element(gamePage(db, options), "pause");
56 // Hidden until the renderer says the browser took the context away, and
57 // inside the overlay that is already the waiting state — not a new dialog.
58 expect(pause).toContain(`class="hint" id="view-lost" hidden`);
59 expect(pause).toContain("took the 3D view away");
60 });
src/pages/game.ts +3
@@ -217,6 +217,9 @@ export function gamePage(db: Database, options: PageOptions): string {
217217 <h2>Paused</h2>
218218 <p>The match is waiting: the clock, the bots and the bomb are stopped, and the round
219219 comes back exactly where it left off.</p>
220 <p class="hint" id="view-lost" hidden>The browser took the 3D view away — a backgrounded
221 tab, a driver reset or the system reclaiming graphics memory. The match is held here
222 while it comes back; nothing is lost, and Resume lights up when the view does.</p>
220223 <div class="row">
221224 <label>Sensitivity<input id="pause-sens" type="number" min="0.2" max="12" step="0.1"></label>
222225 <label>Volume<input id="volume" type="range" min="0" max="100" step="1"></label>
src/readme.test.ts +7
@@ -55,6 +55,13 @@ test("the readme says what pauses a match, on a desktop and on a phone", () => {
5555 expect(playing).toContain("A hidden tab pauses the same way");
5656 });
5757
58 test("the readme says what happens when the browser takes the view away", () => {
59 const playing = section("Playing");
60 expect(playing).toContain("webglcontextlost");
61 expect(playing).toContain("the match\npauses instead of playing on behind a frozen canvas");
62 expect(playing).toContain("builds\neverything it owns a second time");
63 });
64
5865 test("the readme names the check and the build the same way the app does", () => {
5966 const local = section("Run it locally");
6067 const { app } = JSON.parse(read("forge.json")) as { app: { test: string } };

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs