diff --git a/CHANGELOG.md b/CHANGELOG.md index 46ed97e..7192957 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,11 @@ All notable changes to this project are documented here. The project follows - Leasing a dark fiber pair now costs about half as much again ($600 plus $1.50 per km a month, amplifiers as before), so it pays off once you light a couple of 400G waves on it. Leases you already hold keep their price (#203). - Extra crews can now cut a fiber build on land to half its planned time at most, since permits and rights of way do not speed up; the button shows the day it would be done (#203). - A link ordered by typing both ends (the AI tools) can no longer end in a city the map does not show (#203). +- The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same, and zoomed out the card draws the coastlines with fewer points where the extra detail was smaller than a pixel, which helps phones most. Settings › Map drawing › Always 2D keeps the old drawing and frees what the graphics card held, and browsers without WebGL2 or without a usable graphics card keep it on their own. If the graphics card stops for a moment (on a phone, switching apps can do that), the map is drawn in 2D until it is back, and stays in 2D for a game where it keeps failing. (#281) +- Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the map also draws far fewer shapes each frame. (#281) +- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in: its land picture now stays on the graphics card instead of being sent to it again on every frame. Firefox on Android keeps the old way, which avoids its drawing glitches. (#281) +- Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report. (#281) + ## [2.9.1] — 2026-11-04 - Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a14bb92..e71afad 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -41,7 +41,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning | | `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints | | `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals | -| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, `draw()`, the world layer, cities, input and click delegation | +| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation | | `99-loop.js` | `frame()` and `boot()` | `src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone. @@ -75,6 +75,7 @@ Development runs on `npm run dev` (assembles the development page on every reque | `scripts/test.js` | `npm test`: runs every `tests/*.test.js` | | `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets | | `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` | +| `scripts/gpu-bench.js`, `scripts/lib/gpu-bench-client.js` | `npm run bench:gpu -- --save FILE`: the map in your own browser on your own graphics card, 2D against WebGL, scenario by scenario; the table shows in the page and in the terminal | | `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-headless.js`, `src/agent/` | The game as a local MCP server, on the official SDK over stdio or HTTP: typed tools to play, inspect and debug it from an AI client, headless or in the player's own tab ([MCP.md](MCP.md)) | | `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab | | `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries | diff --git a/package.json b/package.json index 997c3d1..41b7083 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "page": "node scripts/lib/page.js", "serve": "npm run build && npx --yes serve@14.2.4 _site", "perf": "node scripts/perf-bench.js", + "bench:gpu": "node scripts/gpu-bench.js", "mcp": "node scripts/mcp.js", "mcp:browser": "node scripts/mcp.js --browser" }, diff --git a/scripts/gpu-bench.js b/scripts/gpu-bench.js new file mode 100644 index 0000000..52cfd8a --- /dev/null +++ b/scripts/gpu-bench.js @@ -0,0 +1,56 @@ +#!/usr/bin/env node +// The map's speed on your own graphics card, 2D against WebGL, in the browser you play in: +// +// npm run bench:gpu -- --save path/to/save.json (an exported save, or a plain one; default: the perf fixture) +// +// then open the printed address in Chrome, Edge or Firefox and press Start. Headless benchmarks (npm run perf) draw the +// canvas in software, so they cannot say what a GPU does; this one runs where the GPU is. Each scenario plays a few +// seconds with the 2D map and with the WebGL tubes, the table shows in the page, and the server prints it here when the +// run ends. Options: --port N (8090), --secs N per scenario (6), --host 0.0.0.0 to open it from a phone on your network, +// --out FILE to also write the table there. Under WSL, the Windows browser reaches http://localhost:PORT as it is. +// In the address: ?only=gl or ?only=2d (one renderer), ?scen=x1-mid,pan (some scenarios), ?dpr=2 (a 4K screen's +// pixels on a smaller one), ?auto (start at once). The game's clock keeps running: incidents do not pause it. +const fs = require('node:fs'); +const os = require('node:os'); +const http = require('node:http'); +const path = require('node:path'); +const { assemble, ROOT } = require('./lib/page'); + +const args = process.argv.slice(2); +const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; }; +const PORT = +opt('port', 8090), HOST = opt('host', 'localhost'), SECS = +opt('secs', 6), OUT = opt('out', null); +const SAVE = path.resolve(opt('save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json'))); +const SITE = path.join(ROOT, 'site'); +const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json', + '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json' }; + +// An exported save is {app, version, S}; a plain one is S itself. +const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); return JSON.stringify({ S: d && d.S && d.S.pops ? d.S : d }); })(); +const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8'); +const page = () => assemble().html.replace('', ``); + +http.createServer((req, res) => { + const url = new URL(req.url, 'http://localhost'); + try { + if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); } + if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); } + if (url.pathname === '/__bench/results' && req.method === 'POST') { + let body = ''; req.on('data', (c) => { body += c; }); req.on('end', () => { + try { const r = JSON.parse(body); console.log('\n' + r.md + '\n'); if (OUT) { fs.writeFileSync(OUT, r.md + '\n\n```json\n' + JSON.stringify(r, null, 1) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results', e); } + res.writeHead(204); res.end(); }); + return; + } + // The service worker would cache this page over the real one: none here. + if (url.pathname === '/sw.js') { res.writeHead(404); return res.end(); } + const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, '')); + if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); } + res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); + fs.createReadStream(file).pipe(res); + } catch (e) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); res.end(String(e && e.stack || e)); } +}).listen(PORT, HOST, () => { + const s = JSON.parse(save).S; + console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`); + console.log(`Open http://localhost:${PORT}/ in your browser, press Start and keep the tab in front.`); + if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4' && !l.internal) console.log(` from another device: http://${l.address}:${PORT}/`); + console.log('Ctrl+C to stop.'); +}); diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 9a2c532..c8feb56 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -3,7 +3,7 @@ // stay in lockstep; this file only offers what a player could do now (buttons on screen, POPs, cities) and digests what // routing gave, as strings the driver compares. (() => { - const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed', + const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'mapSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed', 'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu', 'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare', // Leave the game or open what is not this game: the title screen, menus of other modes, AI helpers that fetch. diff --git a/scripts/lib/gpu-bench-client.js b/scripts/lib/gpu-bench-client.js new file mode 100644 index 0000000..690fbb3 --- /dev/null +++ b/scripts/lib/gpu-bench-client.js @@ -0,0 +1,155 @@ +// The benchmark panel that scripts/gpu-bench.js adds to the game page. It runs in your own browser, so it measures your +// graphics card: the save is loaded, then each scenario plays for a few seconds with the 2D map and with the WebGL +// tubes, and the frames are timed as they really reach the screen (requestAnimationFrame). Results show in the panel +// and go back to the terminal that started the server. Nothing is saved: the page's save() is switched off. +// What each number is: the frame rate and p95 frame are the cadence of requestAnimationFrame (what you see); draw() is +// the main thread's time to build and submit a frame (CPU only: the card may still be drawing when it returns); GPU is +// the card's own time for a WebGL frame, from EXT_disjoint_timer_query_webgl2 where the browser offers it (read back +// frames later, never waited for, and thrown away when the card says its timing was disturbed). +(() => { + const CFG = window.__BENCH__ || {}, QS = new URLSearchParams(location.search); + const SECS = CFG.secs || 6, WARM = CFG.warm ?? 1500, SETTLE = CFG.settleMs || 5000, SEED = CFG.seed || 777; + const SCEN = [ + { id: 'x1-far', label: 'Map at x1, zoomed out (0.6)', speed: 1, z: 0.6 }, + { id: 'x1-mid', label: 'Map at x1 (zoom 1.4)', speed: 1, z: 1.4 }, + { id: 'x1-near', label: 'Map at x1, zoomed in (3.2)', speed: 1, z: 3.2 }, + { id: 'pan', label: 'Panning at x1 (zoom 1.4)', speed: 1, z: 1.4, pan: true }, + { id: 'x8', label: 'Game at x8 (zoom 1.4)', speed: 8, z: 1.4 }, + ]; + // ?only=gl or ?only=2d runs one renderer; ?scen=x1-mid,pan runs only those scenarios; ?reps=3 runs each one three + // times (the renderers take turns going first, and the table shows the medians); ?dpr=2 below. + const ONLY = QS.get('only'), PICK = QS.get('scen'), REPS = Math.max(1, Math.min(9, +QS.get('reps') || CFG.reps || 1)); + if (PICK) SCEN.splice(0, SCEN.length, ...SCEN.filter((s) => PICK.split(',').includes(s.id))); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const box = document.createElement('div'); + box.style.cssText = 'position:fixed;top:8px;left:50%;transform:translateX(-50%);z-index:100000;background:rgba(30,38,64,.94);color:#fff;font:13px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:12px;max-width:94vw;max-height:80vh;overflow:auto;box-shadow:0 6px 24px rgba(0,0,0,.35)'; + box.innerHTML = 'Series of Tubes · GPU benchmark
Loading…
'; + const st = (t) => { box.querySelector('#bst').textContent = t; }; + let SAVE = null, MD = '', TRIAL = 0; + + // Ends what the last trial left running before the next one starts, so nothing of one lands on the other: the clock + // stops, its frame callback is cancelled (measure() does that, and TRIAL turns away one already queued), and a day + // still being routed in the worker is waited for. Its answer runs dayPost() on the old save; one that never comes is + // dropped (rwDone() ignores an answer to no job). Then the clock's leftovers are cleared. + async function settle() { + UI.speed = 0; TRIAL++; + const t0 = performance.now(); + while (RW.job && performance.now() - t0 < SETTLE) await sleep(10); + if (RW.job) { console.warn('[bench] the route worker did not answer: its day is dropped'); RW.job = null; } + acc = 0; animT = 0; + } + // The save again, with the same random numbers every time (S.rng makes Math.random() follow it, as in a scenario). + function fresh() { + S = migrate(JSON.parse(SAVE)); S.rng = SEED; UI.started = true; UI.pitched = true; UI.sel = null; UI.anim = 'on'; applyAnim(); + closeModal(); compute(); renderAll(); + const h = CITY[S.home] || CITIES[0]; cam.x = h.x; cam.y = h.y; + } + async function reset() { await settle(); fresh(); } + const q = (s, x) => (s.length ? s[Math.min(s.length - 1, Math.floor(s.length * x))] : 0); + async function measure(sc, hz, r) { + await reset(); cam.z = sc.z; UI.speed = sc.speed; WL.key = null; + const trial = TRIAL; + await sleep(WARM); + const fr = [], dr = [], gpu = [], pend = [], day0 = S.day; let last = 0, stop = false, hidden = false, long = 0, panX = cam.x, raf = 0, glF = 0, flatF = 0, disjoint = 0; + // The card's own time, where the browser lets us read it: a timer around each WebGL draw(), read when it is ready. + const gl = r === 'gl' ? GLX.gl : null; let tq = null; try { tq = gl && gl.getExtension('EXT_disjoint_timer_query_webgl2'); } catch (e) { /* none */ } + const poll = () => { while (pend.length) { const x = pend[0]; if (!gl.getQueryParameter(x, gl.QUERY_RESULT_AVAILABLE)) break; pend.shift(); + const ns = gl.getQueryParameter(x, gl.QUERY_RESULT); gl.deleteQuery(x); if (gl.getParameter(tq.GPU_DISJOINT_EXT)) disjoint++; else gpu.push(ns / 1e6); } }; + const D0 = draw; + draw = function (t) { let x = null; if (tq && GLX.gl === gl && pend.length < 16) { x = gl.createQuery(); gl.beginQuery(tq.TIME_ELAPSED_EXT, x); } + const a = performance.now(); + try { return D0(t); } finally { dr.push(performance.now() - a); if (x) { gl.endQuery(tq.TIME_ELAPSED_EXT); pend.push(x); } if (GLX.shown) glF++; else flatF++; } }; + let po = null; try { po = new PerformanceObserver((l) => { long += l.getEntries().length; }); po.observe({ type: 'longtask' }); } catch (e) { /* not in this browser */ } + // Frames slower than three refreshes, with the day they fell on and their draw(): where the stutters are. + const t00 = performance.now(), slow = []; + const tick = (t) => { if (stop || trial !== TRIAL) return; + if (last) { fr.push(t - last); if (t - last > 50) slow.push({ at: Math.round(t - t00), ms: Math.round(t - last), day: S.day, draw: +(dr[dr.length - 1] || 0).toFixed(1) }); } last = t; if (document.hidden) hidden = true; + if (sc.pan) { panX += 0.18 * (t - (tick.p || t)) / cam.z; cam.x = panX; tick.p = t; } + if (tq) poll(); + raf = requestAnimationFrame(tick); }; + raf = requestAnimationFrame(tick); + const t0 = performance.now(); await sleep(SECS * 1000); stop = true; cancelAnimationFrame(raf); const T = (performance.now() - t0) / 1000; + draw = D0; if (po) po.disconnect(); UI.speed = 0; + if (tq) { poll(); for (const x of pend) gl.deleteQuery(x); } + const s = fr.slice().sort((a, b) => a - b), d = dr.slice().sort((a, b) => a - b), g = gpu.slice().sort((a, b) => a - b), budget = 1000 / hz; + return { fps: +(fr.length / T).toFixed(1), p50: +q(s, 0.5).toFixed(1), p95: +q(s, 0.95).toFixed(1), p99: +q(s, 0.99).toFixed(1), max: +q(s, 1).toFixed(1), + dropped: +(100 * fr.filter((x) => x > budget * 1.5).length / Math.max(1, fr.length)).toFixed(1), + drawMs: +(d.reduce((a, x) => a + x, 0) / Math.max(1, d.length)).toFixed(2), drawP95: +q(d, 0.95).toFixed(2), + gpuMs: g.length ? +(g.reduce((a, x) => a + x, 0) / g.length).toFixed(2) : null, gpuP95: g.length ? +q(g, 0.95).toFixed(2) : null, gpuN: g.length, disjoint, + // Which map really drew the frames: a WebGL run that fell back to 2D (or a 2D run on the card) is not what it says. + drawn: glF && flatF ? 'mixed' : glF ? 'gl' : flatF ? '2d' : 'none', glFrames: glF, flatFrames: flatF, + daysPerSec: +((S.day - day0) / T).toFixed(2), longTasks: long, hidden, drawMax: +q(d, 1).toFixed(1), slow }; + } + // Several runs of one scenario: the median of each number; the flags and the stutters of all of them. + function merge(ms) { + if (ms.length === 1) return ms[0]; + const o = {}, med = (a) => { const s = a.slice().sort((x, y) => x - y); return s[(s.length - 1) >> 1]; }; + for (const k of Object.keys(ms[0])) { + const v = ms.map((m) => m[k]); + o[k] = k === 'slow' ? v.flat() : k === 'drawn' ? [...new Set(v)].join('+') : typeof v[0] === 'boolean' ? v.some(Boolean) : v.every((x) => typeof x === 'number') ? med(v) : v[0]; + } + o.runs = ms.length; return o; + } + async function refresh() { + const a = []; let l = 0; await new Promise((r) => { const f = (t) => { if (l) a.push(t - l); l = t; if (a.length < 90) requestAnimationFrame(f); else r(); }; requestAnimationFrame(f); }); + a.sort((x, y) => x - y); return Math.round(1000 / a[a.length >> 1]); + } + function table(res, env) { + const gpu = res.gl && SCEN.some((sc) => res.gl[sc.id] && res.gl[sc.id].gpuMs != null); + const rows = SCEN.map((sc) => { const a = res['2d'] && res['2d'][sc.id], b = res.gl && res.gl[sc.id]; + const f = (m, k, u = '') => (m && m[k] != null ? `${m[k]}${u}` : '-'); + return `| ${sc.label} | ${f(a, 'fps')} | ${f(b, 'fps')} | ${f(a, 'p95', ' ms')} | ${f(b, 'p95', ' ms')} | ${f(a, 'drawMs', ' ms')} | ${f(b, 'drawMs', ' ms')} |${gpu ? ` ${f(b, 'gpuMs', ' ms')} |` : ''}`; }); + // A run is only what it says if its frames were drawn by the map it names. + const off = []; for (const [r, want] of [['2d', '2d'], ['gl', 'gl']]) for (const sc of SCEN) { const m = res[r] && res[r][sc.id]; if (m && m.drawn !== want && m.drawn !== 'none') off.push(`${sc.label} (${r === 'gl' ? 'WebGL' : '2D'}: ${m.flatFrames} frames in 2D, ${m.glFrames} on the card)`); } + return [`**${env.gpu || 'unknown GPU'}** · ${env.ua}`, `${env.w}×${env.h} at ${env.dpr}× · ${env.hz} Hz screen · ${env.cores} threads · ${env.save}${env.reps > 1 ? ` · median of ${env.reps} runs` : ''}`, '', + `| Scenario | 2D fps | WebGL fps | 2D p95 frame | WebGL p95 frame | 2D draw() | WebGL draw() |${gpu ? ' WebGL GPU |' : ''}`, + `|---|--:|--:|--:|--:|--:|--:|${gpu ? '--:|' : ''}`, ...rows, + '', `fps and p95 frame: requestAnimationFrame's cadence (p95: the slowest 5% of frames). draw(): CPU time on the main thread to build and submit a frame; the card may still be working when it returns, so it is not the cost of drawing.${gpu ? ' WebGL GPU: the card\'s own time per frame (EXT_disjoint_timer_query_webgl2).' : ' No GPU timer in this browser: the card\'s own time is not measured.'}${env.invalid ? ' ⚠️ The tab was hidden during a run: those numbers are not valid.' : ''}`, + ...(off.length ? ['', `⚠️ Not drawn by the map they name: ${off.join('; ')}.`] : [])].join('\n'); + } + async function run() { + const go = box.querySelector('#bgo'); go.disabled = true; + save = () => {}; + // An incident pauses the game (autoPause): the clock must keep running for the timings to mean anything. + autoPause = () => false; + await reset(); st('Measuring the screen refresh…'); await sleep(500); + const hz = await refresh(); + const want0 = GLX.want, glOk = mapGl(true, false) && glInit(); const env = { gpu: GLX.gpu, ua: navigator.userAgent.replace(/^Mozilla\/5\.0 /, ''), w: innerWidth, h: innerHeight, dpr: devicePixelRatio, hz, cores: navigator.hardwareConcurrency, save: `${Object.keys(S.pops).length} POPs · ${S.links.length} links`, reps: REPS }; + mapGl(false, false); + const rends = (glOk ? ['2d', 'gl'] : ['2d']).filter((x) => !ONLY || x === ONLY), all = {}; + // Scenario by scenario, both renderers in turn, the first one changing every time: neither always runs on a cold or + // a tired browser. + let n = 0; + for (let rep = 0; rep < REPS; rep++) for (const [i, sc] of SCEN.entries()) for (const r of (rep + i) % 2 ? rends.slice().reverse() : rends) { + mapGl(r === 'gl', false); n++; + st(`${r === 'gl' ? 'WebGL' : '2D'} · ${sc.label}${REPS > 1 ? ` · run ${rep + 1}/${REPS}` : ''} (${SECS}s, ${n}/${REPS * SCEN.length * rends.length})… keep this tab in front`); + const m = await measure(sc, hz, r); ((all[r] = all[r] || {})[sc.id] = all[r][sc.id] || []).push(m); if (m.hidden) env.invalid = true; + } + const res = { '2d': null, gl: null }; + for (const r of Object.keys(all)) { res[r] = {}; for (const id of Object.keys(all[r])) res[r][id] = merge(all[r][id]); } + mapGl(want0, false); await reset(); + MD = table(res, env); + st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).'); + box.querySelector('#bout').innerHTML = '
' + MD.replace(/&/g, '&').replace(/';
+    box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
+    try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
+  }
+  // tests/gpu-bench.test.js drives the pieces without the panel.
+  if (CFG.expose) { window.__bench = { settle, reset, measure, merge, table, setSave: (s) => { SAVE = s; } }; return; }
+  addEventListener('load', async () => {
+    document.body.appendChild(box);
+    while (typeof migrate !== 'function' || typeof GLX === 'undefined') await sleep(50);
+    // A software renderer is measured too here (the game itself keeps the 2D map on one); the table names the renderer.
+    GLX.soft = true;
+    // ?dpr=2 draws the map as a screen of that density would (a 4K screen's pixels, measured on a smaller one).
+    const DPRQ = +QS.get('dpr'); if (DPRQ > 0) { Object.defineProperty(window, 'devicePixelRatio', { get: () => DPRQ }); resize(); WL.key = null; }
+    await sleep(800);
+    try { SAVE = JSON.stringify((await (await fetch('/__bench/save.json')).json()).S || null); } catch (e) { st('Could not load the save: ' + e); return; }
+    if (SAVE === 'null') { st('The save file has no game in it.'); return; }
+    const runs = SCEN.length * (ONLY ? 1 : 2) * REPS;
+    st(`Ready: ${SCEN.length} scenarios × ${ONLY ? 1 : 2} renderers${REPS > 1 ? ` × ${REPS}` : ''}, about ${Math.ceil(runs * (SECS + 3) / 60)} minutes. Keep this tab in front and do not touch the map.`);
+    const go = box.querySelector('#bgo'); go.disabled = false; go.onclick = () => run().catch((e) => st('Failed: ' + (e && e.stack || e)));
+    box.querySelector('#bcp').onclick = () => navigator.clipboard.writeText(MD).then(() => st('Copied.'), () => st('Copy failed: select the table instead.'));
+    if (/[?&]auto\b/.test(location.search)) go.onclick();
+  });
+})();
diff --git a/scripts/perf-bench.js b/scripts/perf-bench.js
index 272e9ac..2732cf2 100644
--- a/scripts/perf-bench.js
+++ b/scripts/perf-bench.js
@@ -98,7 +98,10 @@ md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its
 const slow = base ? slowIn(res, 2) : [];
 const { PROFILES } = browser ? require('./perf-browser') : { PROFILES: [] };
 for (const p of PROFILES) {
-  md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.\n\n` + table(browser.profiles[p.key], 2 * p.rate);
+  // The map row is the whole frame, up to a pixel read back from the surface that drew it; say which one that was.
+  const mp = browser.profiles[p.key].maps, mapName = (m) => (!m || !m.length ? 'no map' : m.map((x) => (x === 'gl' ? 'WebGL' : '2D canvas')).join(' then '));
+  const drew = mp ? ` The map was drawn with ${base ? `${mapName(mp.base)} (base) and ${mapName(mp.head)} (this PR)` : mapName(mp.head)}; its row waits for that surface to finish.` : '';
+  md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.${drew}\n\n` + table(browser.profiles[p.key], 2 * p.rate);
   if (base) slow.push(...slowIn(browser.profiles[p.key], 2 * p.rate).map((l) => `${l} (Chromium ${p.key})`));
 }
 if (base) {
diff --git a/scripts/perf-browser.js b/scripts/perf-browser.js
index a8a7123..01bf39e 100644
--- a/scripts/perf-browser.js
+++ b/scripts/perf-browser.js
@@ -36,10 +36,15 @@ async function openPage(browser, profile, file, save, errors) {
   // One run of a workload, timed inside the page so the round trip to Node does not count. Garbage is collected
   // first, so a run never pays for the one before it (its own garbage still costs it, as in the game).
   // The browser leaves layout and canvas drawing for the next frame, so code that changes the DOM or draws the map
-  // would look free: each run ends by forcing both (reading a size, and one pixel back from the map canvas).
+  // would look free: each run ends by forcing both (reading a size, and one pixel back from the surface the map was
+  // last drawn on: the WebGL canvas when the card drew it, which waits for the card to finish, else the 2D canvas).
+  // A run also says which map drew (gl, 2d, or none when it drew nothing).
   const time = async (k, body) => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(([k, body]) => {
     const F = window.__fx || (window.__fx = {}); const f = F[k] || (F[k] = new Function(body)); const map = document.getElementById('map').getContext('2d');
-    const t = performance.now(); f(); void document.documentElement.offsetHeight; map.getImageData(0, 0, 1, 1); return performance.now() - t; }, [k, body]); };
+    const G = typeof GLX === 'object' ? GLX : null, px = window.__px || (window.__px = new Uint8Array(4));
+    const t = performance.now(); f(); void document.documentElement.offsetHeight;
+    const gl = G && G.shown && G.gl; if (gl) gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); else map.getImageData(0, 0, 1, 1);
+    return { ms: performance.now() - t, map: G && G.shown ? 'gl' : '2d' }; }, [k, body]); };
   return { ctx, time };
 }
 
@@ -54,15 +59,18 @@ async function runBrowser({ head, base, save, metrics, runs, exe }) {
     for (const p of PROFILES) {
       const h = await openPage(hb, p, head, save, errors), b = base ? await openPage(bb, p, base, save, errors) : null;
       const res = out.profiles[p.key] = {};
+      // Which map each version drew with, over all the runs that drew one (a version falling back mid-run shows both).
+      const maps = res.maps = { head: new Set(), base: new Set() };
       for (const [k, , body] of metrics) {
-        const H = [], B = [];
+        const H = [], B = [], go = async (v, into, m) => { const r = await v.time(k, body); into.push(r.ms); if (k === 'map') m.add(r.map); };
         for (const v of [h, b].filter(Boolean)) { await v.time(k, body); await v.time(k, body); }   // warm up
         for (let i = 0; i < runs; i++) {
           // Alternate who goes first, like the jsdom runs.
-          if (b && i % 2) { B.push(await b.time(k, body)); H.push(await h.time(k, body)); } else { H.push(await h.time(k, body)); if (b) B.push(await b.time(k, body)); }
+          if (b && i % 2) { await go(b, B, maps.base); await go(h, H, maps.head); } else { await go(h, H, maps.head); if (b) await go(b, B, maps.base); }
         }
         res[k] = { head: median(H), base: b ? median(B) : null, samples: { head: H.map((x) => +x.toFixed(1)), base: b ? B.map((x) => +x.toFixed(1)) : null } };
       }
+      res.maps = { head: [...maps.head], base: b ? [...maps.base] : null };
       await h.ctx.close(); if (b) await b.ctx.close();
     }
   } finally { await hb.close(); if (bb) await bb.close(); }
diff --git a/site/i18n/de.js b/site/i18n/de.js
index e8a6fd1..9c01579 100644
--- a/site/i18n/de.js
+++ b/site/i18n/de.js
@@ -1614,7 +1614,6 @@
 "common.vendor_tac":"Hersteller-TAC",
 "common.venus":"Venus",
 "common.via_rs":"über RS",
-"common.viewport_info":"Ansichtsinfo",
 "common.vigilante":"Selbstjustiz",
 "common.walk_away":"Aussteigen",
 "common.wave_lease":"Wave-Miete",
@@ -4031,12 +4030,16 @@
 "settings.agent_api":"Agent-API",
 "settings.agent_relay_connected":"Agenten-Relay verbunden: Jetzt kann ein Tool dieses Spiel in diesem Tab spielen.",
 "settings.agent_s_clock":"Uhr des Agenten",
+"settings.always_2d":"Immer 2D",
 "settings.an_early_heads_up_below_60":"Eine frühe Warnung unter 60 % Zufriedenheit, lange bevor sie wütend sind.",
+"settings.auto_draws_the_map_with_your":"Auto zeichnet die Karte mit deiner Grafikkarte, wenn der Browser es erlaubt, damit auch große Netze flüssig bleiben. Immer 2D läuft überall, ist auf großen Karten aber langsamer.",
 "settings.auto_follows_your_device_s_reduce":"Auto folgt der Einstellung „Bewegung reduzieren“ deines Geräts. Aus friert die Karte ein: keine wandernden Pakete, kein Pulsieren, kein schwebender Text.",
 "settings.customers_and_alerts":"Kunden und Warnungen",
+"settings.diagnostic_info":"Diagnoseinfos",
 "settings.display_and_sound":"Anzeige und Ton",
-"settings.for_reporting_layout_bugs_shows_what":"Zum Melden von Layout-Fehlern: zeigt, was dein Bildschirm dem Spiel mitteilt.",
+"settings.for_bug_reports_shows_your_screen":"Für Fehlerberichte: zeigt in einer Ecke die Größe deines Bildschirms, wie die Karte gezeichnet wird (Grafikkarte oder 2D, und warum) und wie schnell.",
 "settings.let_an_ai_agent_drive_this_game":"Eine KI soll dieses Spiel spielen",
+"settings.map_drawing":"Kartendarstellung",
 "settings.n_min":"{n} Min.",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Nur Ärger und Meilensteine poppen auf; alles andere landet still im NOC-Log. In Best Effort standardmäßig an.",
@@ -4049,6 +4052,7 @@
 "settings.the_agent_moves_it":"Der Agent stellt sie",
 "settings.the_clock_while_an_agent_plays":"Die Uhr, während ein Agent spielt",
 "settings.the_game_stops_so_you_can":"Das Spiel hält an, damit du ihren Dienst reparieren kannst, bevor sie kündigen. Am nützlichsten bei hoher Geschwindigkeit.",
+"settings.this_browser_cannot_so_the_map":"Dieser Browser kann das nicht, also wird die Karte in 2D gezeichnet.",
 "settings.warn_when_a_customer_gets_unhappy":"Bei unzufriedenen Kunden warnen",
 "settings.while_agent_mode_is_on_the":"Solange der Agenten-Modus an ist, gehört die Uhr nicht dir. Mit Tempo läuft sie von selbst und lässt sich von Hand nicht anhalten, auch nicht durch ein offenes Fenster (deins eingeschlossen), und sie wartet, solange kein Agent verbunden ist. Oder der Agent stellt sie, und nichts passiert, bis er nach Tagen fragt. Die Seite verbindet sich mit dem lokalen Agenten-Relay (npm run dev bringt eins mit), damit Tools wie der MCP-Server dieses Spiel spielen können, während du zusiehst.",
 "share_card.build_the_internet_one_tube_at":"Bau das Internet, eine Röhre nach der anderen",
diff --git a/site/i18n/es.js b/site/i18n/es.js
index dc68dc0..cb93331 100644
--- a/site/i18n/es.js
+++ b/site/i18n/es.js
@@ -1612,7 +1612,6 @@
 "common.vendor_tac":"TAC del fabricante",
 "common.venus":"Venus",
 "common.via_rs":"vía RS",
-"common.viewport_info":"Información del viewport",
 "common.vigilante":"Justiciero",
 "common.walk_away":"Marcharse",
 "common.wave_lease":"Alquiler de onda",
@@ -4029,12 +4028,16 @@
 "settings.agent_api":"API de agentes",
 "settings.agent_relay_connected":"Relay de agentes conectado: ahora una herramienta puede jugar esta partida en esta pestaña.",
 "settings.agent_s_clock":"Reloj del agente",
+"settings.always_2d":"Siempre 2D",
 "settings.an_early_heads_up_below_60":"Un aviso temprano por debajo del 60 % de felicidad, mucho antes de que estén furiosos.",
+"settings.auto_draws_the_map_with_your":"Auto dibuja el mapa con tu tarjeta gráfica cuando el navegador lo permite, y así las redes grandes siguen fluidas. Siempre 2D funciona en todas partes, pero va más lento en mapas grandes.",
 "settings.auto_follows_your_device_s_reduce":"Auto sigue el ajuste de reducir movimiento de tu dispositivo. Desactivado congela el mapa: sin paquetes en movimiento, pulsos ni texto flotante.",
 "settings.customers_and_alerts":"Clientes y alertas",
+"settings.diagnostic_info":"Información de diagnóstico",
 "settings.display_and_sound":"Pantalla y sonido",
-"settings.for_reporting_layout_bugs_shows_what":"Para informar de fallos de diseño: muestra lo que tu pantalla le dice al juego.",
+"settings.for_bug_reports_shows_your_screen":"Para informar de fallos: muestra en una esquina el tamaño de tu pantalla, cómo se dibuja el mapa (tarjeta gráfica o 2D, y por qué) y a qué velocidad.",
 "settings.let_an_ai_agent_drive_this_game":"Deja que un agente de IA juegue",
+"settings.map_drawing":"Dibujo del mapa",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Solo aparecen los problemas y los hitos; todo lo demás va en silencio al registro del NOC. Activado por defecto en Best Effort.",
@@ -4047,6 +4050,7 @@
 "settings.the_agent_moves_it":"Lo mueve el agente",
 "settings.the_clock_while_an_agent_plays":"El reloj mientras juega un agente",
 "settings.the_game_stops_so_you_can":"El juego se detiene para que arregles su servicio antes de que cancelen. Muy útil a alta velocidad.",
+"settings.this_browser_cannot_so_the_map":"Este navegador no puede, así que el mapa se dibuja en 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Avisar cuando un cliente se descontenta",
 "settings.while_agent_mode_is_on_the":"Mientras el modo agente está activo, el reloj no es tuyo. Con un ritmo, corre solo y no se puede pausar a mano, ni siquiera con una ventana abierta (las tuyas incluidas), y espera mientras no haya ningún agente conectado. O lo mueve el agente, y no pasa nada hasta que pide días. La página se conecta al relay local de agentes (npm run dev trae uno), para que herramientas como el servidor MCP jueguen esta partida mientras miras.",
 "share_card.build_the_internet_one_tube_at":"Construye internet, un tubo a la vez",
diff --git a/site/i18n/fr.js b/site/i18n/fr.js
index 45c2445..1920ea1 100644
--- a/site/i18n/fr.js
+++ b/site/i18n/fr.js
@@ -1612,7 +1612,6 @@
 "common.vendor_tac":"TAC du constructeur",
 "common.venus":"Vénus",
 "common.via_rs":"via RS",
-"common.viewport_info":"Infos viewport",
 "common.vigilante":"Justicier",
 "common.walk_away":"Laisser tomber",
 "common.wave_lease":"Location de longueur d’onde",
@@ -4029,12 +4028,16 @@
 "settings.agent_api":"API agent",
 "settings.agent_relay_connected":"Relais pour agents connecté : un outil peut maintenant jouer cette partie dans cet onglet.",
 "settings.agent_s_clock":"Horloge de l'agent",
+"settings.always_2d":"Toujours en 2D",
 "settings.an_early_heads_up_below_60":"Une alerte précoce sous 60 % de satisfaction, bien avant qu’il soit furieux.",
+"settings.auto_draws_the_map_with_your":"Auto dessine la carte avec ta carte graphique quand le navigateur le permet, ce qui garde les grands réseaux fluides. Toujours en 2D marche partout mais rame sur les grandes cartes.",
 "settings.auto_follows_your_device_s_reduce":"Auto suit le réglage « réduire les animations » de ton appareil. Inactif fige la carte : plus de paquets en mouvement, de pulsations ni de texte flottant.",
 "settings.customers_and_alerts":"Clients et alertes",
+"settings.diagnostic_info":"Infos de diagnostic",
 "settings.display_and_sound":"Affichage et son",
-"settings.for_reporting_layout_bugs_shows_what":"Pour signaler des bugs de mise en page : montre ce que ton écran dit au jeu.",
+"settings.for_bug_reports_shows_your_screen":"Pour signaler un bug : affiche dans un coin la taille de ton écran, comment la carte est dessinée (carte graphique ou 2D, et pourquoi) et à quelle vitesse.",
 "settings.let_an_ai_agent_drive_this_game":"Laisser un agent IA jouer",
+"settings.map_drawing":"Dessin de la carte",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Seuls les problèmes et les étapes s'affichent ; tout le reste va discrètement dans le journal du NOC. Activé par défaut en Best Effort.",
@@ -4047,6 +4050,7 @@
 "settings.the_agent_moves_it":"L'agent l'avance",
 "settings.the_clock_while_an_agent_plays":"L'horloge pendant qu'un agent joue",
 "settings.the_game_stops_so_you_can":"Le jeu s’arrête pour que tu répares leur service avant qu’ils résilient. Surtout utile à grande vitesse.",
+"settings.this_browser_cannot_so_the_map":"Ce navigateur ne peut pas, la carte est donc dessinée en 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Prévenir quand un client devient mécontent",
 "settings.while_agent_mode_is_on_the":"Tant que le mode agent est actif, l'horloge n'est plus à toi. Avec un rythme, elle tourne toute seule et ne peut pas être mise en pause à la main, pas même par une fenêtre ouverte (les tiennes comprises), et elle attend tant qu'aucun agent n'est connecté. Ou bien c'est l'agent qui l'avance, et rien ne se passe tant qu'il ne demande pas de jours. La page se connecte au relais local pour agents (npm run dev en lance un), pour que des outils comme le serveur MCP jouent cette partie pendant que tu regardes.",
 "share_card.build_the_internet_one_tube_at":"Construis Internet, un tube à la fois",
diff --git a/site/i18n/it.js b/site/i18n/it.js
index 7ab959c..d6aec00 100644
--- a/site/i18n/it.js
+++ b/site/i18n/it.js
@@ -1612,7 +1612,6 @@
 "common.vendor_tac":"TAC del vendor",
 "common.venus":"Venere",
 "common.via_rs":"via RS",
-"common.viewport_info":"Info viewport",
 "common.vigilante":"Giustiziere",
 "common.walk_away":"Lascia perdere",
 "common.wave_lease":"Affitto della wave",
@@ -4029,12 +4028,16 @@
 "settings.agent_api":"API per agenti",
 "settings.agent_relay_connected":"Relay per agenti collegato: ora uno strumento può giocare questa partita in questa scheda.",
 "settings.agent_s_clock":"Orologio dell'agente",
+"settings.always_2d":"Sempre 2D",
 "settings.an_early_heads_up_below_60":"Un avviso in anticipo sotto il 60% di soddisfazione, molto prima che siano furiosi.",
+"settings.auto_draws_the_map_with_your":"Auto disegna la mappa con la tua scheda grafica quando il browser lo consente, così anche le reti grandi restano fluide. Sempre 2D funziona ovunque ma è più lento sulle mappe grandi.",
 "settings.auto_follows_your_device_s_reduce":"Auto segue l’impostazione “riduci movimento” del tuo dispositivo. Off congela la mappa: niente pacchetti in movimento, pulsazioni o testo fluttuante.",
 "settings.customers_and_alerts":"Clienti e avvisi",
+"settings.diagnostic_info":"Info di diagnostica",
 "settings.display_and_sound":"Schermo e audio",
-"settings.for_reporting_layout_bugs_shows_what":"Per segnalare bug di layout: mostra cosa lo schermo dice al gioco.",
+"settings.for_bug_reports_shows_your_screen":"Per segnalare bug: mostra in un angolo le dimensioni dello schermo, come viene disegnata la mappa (scheda grafica o 2D, e perché) e a che velocità.",
 "settings.let_an_ai_agent_drive_this_game":"Lascia giocare un agente IA",
+"settings.map_drawing":"Disegno della mappa",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Compaiono solo i problemi e i traguardi; tutto il resto finisce in silenzio nel registro del NOC. Attivo di default in Best Effort.",
@@ -4047,6 +4050,7 @@
 "settings.the_agent_moves_it":"Lo muove l'agente",
 "settings.the_clock_while_an_agent_plays":"L'orologio mentre gioca un agente",
 "settings.the_game_stops_so_you_can":"Il gioco si ferma così puoi sistemare il servizio prima che disdicano. Utilissimo ad alta velocità.",
+"settings.this_browser_cannot_so_the_map":"Questo browser non può, quindi la mappa è disegnata in 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Avvisa quando un cliente diventa scontento",
 "settings.while_agent_mode_is_on_the":"Finché la modalità agente è attiva, l'orologio non è tuo. Con un ritmo va da solo e non si può fermare a mano, nemmeno con una finestra aperta (comprese le tue), e aspetta finché non è collegato nessun agente. Oppure lo muove l'agente, e non succede nulla finché non chiede dei giorni. La pagina si collega al relay locale per agenti (npm run dev ne avvia uno), così strumenti come il server MCP possono giocare questa partita mentre guardi.",
 "share_card.build_the_internet_one_tube_at":"Costruisci internet, un tubo alla volta",
diff --git a/site/i18n/pt.js b/site/i18n/pt.js
index bd87f12..6d5bff7 100644
--- a/site/i18n/pt.js
+++ b/site/i18n/pt.js
@@ -1612,7 +1612,6 @@
 "common.vendor_tac":"TAC do fabricante",
 "common.venus":"Vênus",
 "common.via_rs":"via RS",
-"common.viewport_info":"Info do viewport",
 "common.vigilante":"Justiceiro",
 "common.walk_away":"Desistir",
 "common.wave_lease":"Aluguel da wave",
@@ -4029,12 +4028,16 @@
 "settings.agent_api":"API para agentes",
 "settings.agent_relay_connected":"Relay de agentes ligado: agora uma ferramenta pode jogar este jogo nesta aba.",
 "settings.agent_s_clock":"Relógio do agente",
+"settings.always_2d":"Sempre 2D",
 "settings.an_early_heads_up_below_60":"Um aviso antecipado abaixo de 60% de satisfação, bem antes de ficarem furiosos.",
+"settings.auto_draws_the_map_with_your":"Auto desenha o mapa com sua placa de vídeo quando o navegador permite, o que mantém redes grandes fluidas. Sempre 2D funciona em qualquer lugar, mas é mais lento em mapas grandes.",
 "settings.auto_follows_your_device_s_reduce":"Auto segue a configuração de reduzir movimento do seu aparelho. Desligado congela o mapa: sem pacotes andando, pulsos ou texto flutuante.",
 "settings.customers_and_alerts":"Clientes e alertas",
+"settings.diagnostic_info":"Informações de diagnóstico",
 "settings.display_and_sound":"Tela e som",
-"settings.for_reporting_layout_bugs_shows_what":"Para reportar bugs de layout: mostra o que sua tela informa ao jogo.",
+"settings.for_bug_reports_shows_your_screen":"Para reportar bugs: mostra em um canto o tamanho da sua tela, como o mapa é desenhado (placa de vídeo ou 2D, e por quê) e a que velocidade.",
 "settings.let_an_ai_agent_drive_this_game":"Deixa um agente de IA jogar",
+"settings.map_drawing":"Desenho do mapa",
 "settings.n_min":"{n} min",
 "settings.n_sec":"{n} s",
 "settings.only_trouble_and_milestones_pop_up":"Só aparecem problemas e marcos; todo o resto vai em silêncio para o registro do NOC. Ligado por padrão no Best Effort.",
@@ -4047,6 +4050,7 @@
 "settings.the_agent_moves_it":"O agente move-o",
 "settings.the_clock_while_an_agent_plays":"O relógio enquanto um agente joga",
 "settings.the_game_stops_so_you_can":"O jogo para para você consertar o serviço antes que cancelem. Muito útil em alta velocidade.",
+"settings.this_browser_cannot_so_the_map":"Este navegador não consegue, então o mapa é desenhado em 2D.",
 "settings.warn_when_a_customer_gets_unhappy":"Avisar quando um cliente ficar insatisfeito",
 "settings.while_agent_mode_is_on_the":"Enquanto o modo agente estiver ligado, o relógio não é teu. Com um ritmo, corre sozinho e não pode ser parado à mão, nem por uma janela aberta (as tuas incluídas), e espera enquanto nenhum agente estiver ligado. Ou é o agente que o move, e nada acontece até ele pedir dias. A página liga-se ao relay local de agentes (npm run dev traz um), para que ferramentas como o servidor MCP joguem este jogo enquanto vês.",
 "share_card.build_the_internet_one_tube_at":"Construa a internet, um tubo de cada vez",
diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js
index cda7563..9a2ee36 100644
--- a/src/agent/20-commands.js
+++ b/src/agent/20-commands.js
@@ -564,6 +564,6 @@ const API_DENY={
   start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start',
   exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',
   slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots',
-  animSet:'prefs',langSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs',
+  animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs',
   install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',
 };
diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js
index b75c863..4224aac 100644
--- a/src/game/90-actions/10-interface.js
+++ b/src/game/90-actions/10-interface.js
@@ -22,6 +22,7 @@ const ACT={
    toast(B.equity?tr('interface.you_bought_out_bank_they_flew',{bank:esc(B.name)}):tr('interface.loan_from_bank_repaid_early',{bank:esc(B.name)}),'good');after();renderBank();},
  leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=lvl()>=3?'roadm':'lite';openLinkModal(a,b);},
  dashLink:({id})=>{$('dash').hidden=true;selectLink(id);focusLink(id);},
+ mapSet:({v})=>{if(!['auto','2d'].includes(v))return;mapGl(v==='auto');refreshSettings();},
  animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();},
  soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();},
  langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();},
diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js
index fb83f74..a1671dc 100644
--- a/src/game/90-actions/89-game-and-settings.js
+++ b/src/game/90-actions/89-game-and-settings.js
@@ -35,7 +35,7 @@ Object.assign(ACT,{
  settings:()=>{UI.setOpen=true;openModal(settingsHtml());},
  settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();},
  prefSet:({v})=>{const [k,b]=String(v).split(':');if(!own(PREF_DEF,k))return;setPref(k,b==='1');sfx('click');refreshSettings();},
- vpSet:({v})=>{vpOn(v==='on');refreshSettings();},
+ vpSet:({v})=>{diagOn(v==='on');refreshSettings();},
  resetAsk:()=>openModal(`

${tr('game_and_settings.start_a_new_network')}

${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(S?S.name:tr('common.your_network'))})}

${btn(tr('game_and_settings.delete_and_start_over'),'newgame',{},'red big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`), whatsNewShow:()=>whatsNew(true,true), updateNow:()=>{save(true);location.reload();}, diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 69433ea..3af3af5 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -58,6 +58,6 @@ Object.assign(ACT,{ // open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's // routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone. // This file is the last of the actions, so every one is here to wrap. -const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); +const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']); for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);} diff --git a/src/game/96-map/10-canvas.js b/src/game/96-map/10-canvas.js index 3210b61..ff76dfb 100644 --- a/src/game/96-map/10-canvas.js +++ b/src/game/96-map/10-canvas.js @@ -1,5 +1,6 @@ /* ================= CANVAS ================= */ -const cv=$('map'),ctx=cv.getContext('2d'); +// ctx is the 2D context draw() paints with: the map's own (CTX0), or with WebGL on the overlay above the card (56-webgl.js). +const cv=$('map'),CTX0=cv.getContext('2d');let ctx=CTX0; const cam={x:1050,y:330,z:0.8}; let CW=0,CH=0,DPR=1; /* Installed on an iPhone home screen with a translucent status bar, iOS can report a viewport one status bar @@ -13,15 +14,5 @@ function fixStandaloneHeight(){const R0=document.documentElement; R0.classList.toggle('iosfix',on);if(on)R0.style.setProperty('--app-h',sh+'px');else R0.style.removeProperty('--app-h');return on?sh:0;} function resize(){const ah=fixStandaloneHeight();DPR=Math.min(2,window.devicePixelRatio||1);CW=innerWidth;CH=ah||innerHeight;cv.width=CW*DPR;cv.height=CH*DPR;} addEventListener('resize',()=>{resize();WL.key=null;renderLeft();fitHud();});resize(); -// Viewport readout for debugging phone layouts: open the game once with ?vp in the address (or the start URL). -function vpDebug(){let el=document.getElementById('vpdbg');if(!el){el=document.createElement('pre');el.id='vpdbg';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none';document.body.appendChild(el); - const pr=document.createElement('div');pr.id='vpprobe';pr.style.cssText='position:fixed;visibility:hidden;padding:env(safe-area-inset-top,0px) 0 env(safe-area-inset-bottom,0px)';document.body.appendChild(pr);} - const pr=document.getElementById('vpprobe'),cs=getComputedStyle(pr),vv=window.visualViewport,de=document.documentElement,tb=document.getElementById('tabbar').getBoundingClientRect(); - el.textContent=`inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height}\nvv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\nstandalone ${navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches)} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}`;} -let VP_T=null;const vpOn=on=>{clearInterval(VP_T);VP_T=null;const el=document.getElementById('vpdbg');if(el)el.remove();if(on){VP_T=setInterval(vpDebug,500);vpDebug();}try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');}catch(e){}}; -if(/[?&]vp\b/.test(location.search))vpOn(true);else if(/[?&]novp\b/.test(location.search))vpOn(false); -try{if(localStorage.getItem('sot-vp')==='1')vpOn(true);}catch(e){} -// Inside an installed app there is no address bar: five quick taps on the date toggle the readout. -{let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];vpOn(!VP_T);}});} // iOS settles the standalone viewport a moment after launch and after rotating. for(const t of [300,1000])setTimeout(()=>{resize();WL.key=null;},t);addEventListener('pageshow',()=>{resize();WL.key=null;}); diff --git a/src/game/96-map/30-settings.js b/src/game/96-map/30-settings.js index 98750ea..b2874fd 100644 --- a/src/game/96-map/30-settings.js +++ b/src/game/96-map/30-settings.js @@ -30,9 +30,10 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${tr('settings.display_and_sound')} ${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))} + ${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glCan()?' '+tr('settings.this_browser_cannot_so_the_map'):''))} ${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])}
${langPick('langSel')}
- ${seg(tr('common.viewport_info'),'vpSet',VP_T?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_reporting_layout_bugs_shows_what'))} + ${seg(tr('settings.diagnostic_info'),'vpSet',DIAG.on?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_bug_reports_shows_your_screen'))} ${installRow()}
${btn(tr('common.done_8dd3'),'settingsClose',{},'pink')}
`;} const refreshSettings=()=>{if(UI.setOpen)openModal(settingsHtml());}; function animOn(){const m=UI.anim||'auto';if(m==='on')return true;if(m==='off')return false;try{return !matchMedia('(prefers-reduced-motion: reduce)').matches;}catch(e){return true;}} diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index 5c03a54..f737267 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -30,8 +30,9 @@ function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const // Cable names are drawn in one font, so each width is measured once. const LBW=new Map(),labW=t=>{let w=LBW.get(t);if(w===undefined)LBW.set(t,w=ctx.measureText(t).width);return w;}; try{document.fonts&&document.fonts.ready.then(()=>LBW.clear());}catch(e){} -function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab); - if(!selC&&z<1.7&&cached)return; +function drawCables(ks){const G=glOn(),z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab)&&!G; + // On the card the cables are drawn by glBegin(); here only their labels are left. + if(!selC&&z<1.7&&cached)return;if(G&&!selC&&z<1.7)return; ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle'; // Labels that would sit on another, or on a segment shorter than the name, are left out (a selected city's always show). // Placed labels go in a 64px grid, so each check only looks at its neighbours. @@ -41,8 +42,8 @@ function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.dra for(let cx=c0;cx<=c1;cx++)for(let cy=r0;cy<=r1;cy++){const k=cx*8192+cy;let o=LG.get(k);if(!o)LG.set(k,o=[]);o.push(b);}return true;}; const ar=arOn();for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;const col=cableCol(C); for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]mx)mx=q[0];}if(mx<-20||mn>CW+20)continue; - if(hot||!cached){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);} + if(!G&&(hot||!cached)){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,'rgba(255,255,255,.85)',3,m[0],m[1]-8);} ctx.globalAlpha=1;}}} function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit; const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js new file mode 100644 index 0000000..8ca98b6 --- /dev/null +++ b/src/game/96-map/55-link-look.js @@ -0,0 +1,17 @@ +/* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in + 58-webgl-links.js), so they cannot drift apart. */ +// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable. +const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5]]; +// A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. +function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; + const cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); + return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), + col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:bld?3:idle?4:0, + pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills +// The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the +// links and with the day's routing (R), not with the camera, so it is kept until one of those changes. +let MLK=null; +function mapLinks(day){const key=[S.links,S.links.length,R,day]; + if(MLK&&key.every((v,i)=>v===MLK.key[i]))return MLK; + const PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))); + return MLK={key,PI,LG,GM,looks:LG.map(g=>linkLook(g,day))};} diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js new file mode 100644 index 0000000..7f4196d --- /dev/null +++ b/src/game/96-map/56-webgl.js @@ -0,0 +1,100 @@ +/* The map on the graphics card (WebGL2), wherever the browser can; Settings › Map drawing › Always 2D keeps the 2D + canvas instead (a choice per device). A late-game map sends the 2D canvas several strokes per tube every frame (thousands on a + big network) and repaints the land whenever you pan; here the card draws it all from buffers that change only with + the network, so a frame costs the processor a few draws and uniforms. + Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and + packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for + the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used. + Puzzles, and any browser without WebGL2 or whose context fails, keep the 2D map; a lost context, until it is back. So does WebGL drawn by + the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs + microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */ +const GLX={want:true,dead:false,lost:false,sleep:false,losses:0,lose:null,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; +try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){} +// Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark). +const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i; +const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit(); +// Whether the card can draw the map, as far as is known without asking it: Settings says so without making a context +// (on the title screen or in a puzzle that made the 64 MB atlas for a map drawn in 2D). A card not tried yet counts as able. +const glCan=()=>!GLX.dead&&typeof WebGL2RenderingContext!=='undefined'; +// Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not. +// Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back. +function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){} + if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}} + GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;} +function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;} +// Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame. +function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;} +function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true; + const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);} +/* The card given up for good (not Always 2D: glSleep()) still held what was sent to it, the atlas alone + 64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go + (WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps + the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */ +function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf); + const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){} + GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;} +/* A lost context comes back. The browser may lose it (a driver reset; on a phone, sometimes just leaving the app) and + give it back (webglcontextrestored): the 2D map draws meanwhile, and everything on the card is built again on the + same context, as for the first frame. A card lost more than GL_LOSSES times is given up for the session, so a card + that keeps failing does not keep the map switching. Always 2D lets the context go the same way (WEBGL_lose_context) + and Auto asks for it back, so 64 MB of atlas and the rest are not held for a map that is not drawn. */ +const GL_LOSSES=2; +// Forgets what was on the card (the context itself is kept): glInit() builds it all again. +function glForget(){GLX.gl=null;spritesDrop();GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;Object.assign(GLX,{tex:null,land:{},ckey:null,key:[]});glShow(false);UI.drawnAt=0;} +function glLost(e){if(GLX.dead)return;e.preventDefault();if(GLX.lost)return; // let go by Always 2D (glSleep()) + if(++GLX.losses>GL_LOSSES){glKill('the graphics context was lost '+GLX.losses+' times');return;} + GLX.lost=true;glForget();} +function glRestored(){if(GLX.dead)return;GLX.lost=false;glForget();if(!GLX.want)glSleep();} +// Always 2D: lets the context go, unless the browser has it already (its restore then finds Always 2D and lets it go). +function glSleep(){const L=GLX.lose;if(!GLX.ctx||GLX.dead||!L||typeof L.restoreContext!=='function')return; + if(GLX.lost){GLX.sleep=true;return;}glForget();GLX.sleep=GLX.lost=true;try{L.loseContext();}catch(e){GLX.sleep=GLX.lost=false;}} +/* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for + getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big + uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never + every frame: each read waits for the card. Up to four flags are read, as one call returns only one. */ +function glMem(gl,what){for(let i=0;i<4;i++){const e=gl.getError();if(!e||e===gl.CONTEXT_LOST_WEBGL)return; + if(e===gl.OUT_OF_MEMORY)throw glErr(new Error('the graphics card is out of memory ('+what+')'));}} +const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n'; +// Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing). +const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n'; +function glProg(gl,vs,fs){const sh=(t,s)=>{const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))throw new Error('shader: '+gl.getShaderInfoLog(x));return x;}; + const p=gl.createProgram();gl.attachShader(p,sh(gl.VERTEX_SHADER,vs));gl.attachShader(p,sh(gl.FRAGMENT_SHADER,fs));gl.linkProgram(p); + if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw new Error('link: '+gl.getProgramInfoLog(p)); + const u={},n=gl.getProgramParameter(p,gl.ACTIVE_UNIFORMS);for(let i=0;ia+x,0)*4; + gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW); + let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;}); + gl.bindVertexArray(null);return {v,b};} +function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false; + try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers'); + const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'}); + if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl; + if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}} + try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){} + if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu); + const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)}; + // The tubes' points for the packets: floats read with texelFetch, never filtered. + const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST); + glsInit(gl); + // The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every + // frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself. + const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype; + if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}} + const V=s=>glVao(gl,s); + Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;} + catch(e){glKill(e);return false;}} +// Colours as [r,g,b,a] from '#rrggbb', '#rgb' or 'rgba(r,g,b,a)', kept by string. +const GLCOL=new Map(); +function glColor(s){let v=GLCOL.get(s);if(v)return v;let r=0,g=0,b=0,a=1; + if(s[0]==='#'){let h=s.slice(1);if(h.length===3)h=h.replace(/./g,x=>x+x);r=parseInt(h.slice(0,2),16)/255;g=parseInt(h.slice(2,4),16)/255;b=parseInt(h.slice(4,6),16)/255;} + else{const m=/rgba?\(([^)]*)\)/.exec(s);if(m){const p=m[1].split(',').map(x=>parseFloat(x));r=p[0]/255;g=p[1]/255;b=p[2]/255;a=p.length>3?p[3]:1;}} + v=[r,g,b,a];GLCOL.set(s,v);return v;} +// Sets a line or a point program's view for copy k of the map (wm: the line width multiplier). +function glSet(gl,P,k,wm){gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.uniform1f(P.u.uWMul,wm);gl.uniform1f(P.u.uDpr,DPR);} +// A full-screen fill, from one premultiplied colour at the bottom to another at the top (the sea), or of one colour +// (the land and the clouds, through the stencil). +const FILL_VS=GL_HEAD+`void main(){vec2 p=vec2((gl_VertexID&1)==0?-1.:1.,(gl_VertexID&2)==0?-1.:1.);gl_Position=vec4(p,0.,1.);}`; +const FILL_FS=GL_HEAD+`uniform vec4 uTop,uBot;uniform float uH;out vec4 o;void main(){o=mix(uBot,uTop,gl_FragCoord.y/uH);}`; +function glFill(gl,top,bot=top){const P=GLX.fill;gl.useProgram(P.p);gl.uniform4fv(P.u.uTop,top);gl.uniform4fv(P.u.uBot,bot);gl.uniform1f(P.u.uH,GLX.c.height);gl.bindVertexArray(GLX.empty);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);} diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js new file mode 100644 index 0000000..5055126 --- /dev/null +++ b/src/game/96-map/57-webgl-background.js @@ -0,0 +1,126 @@ +/* The background on the card, painted first each frame: the sea, the land, the waves, the clouds and the cables, as + the 2D map paints them (drawFrame(), paintWorld()) and in the same colours. The land and the cables are geometry + built once, so panning and zooming repaint nothing; only the waves and the clouds move. */ +const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends +const SEA_TOP=glPm('#62CBEA'),SEA_BOT=glPm('#43AED6'),CLOUD_COL=glPm('rgba(255,255,255,.55)'); +const LAND_SHADOW=glPm('rgba(20,90,130,.35)'),LAND_GRASS=glPm('#9BDA6C'),HILL_COL=glPm('#86CB5B'),HILL_SHINE=glPm('rgba(255,255,255,.18)'); +// The land's fill: a fan of triangles per coastline, counted in the stencil (how many times the coasts wind round each +// pixel: glLandFill()), then one cover where the count is not zero. uOff shifts it in CSS px (the shadow). +const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam; +void main(){gl_Position=clip((aV-uCam.xy)*uCam.z+uView*.5+uOff,uView,0.);}`; +const FAN_FS=GL_HEAD+`out vec4 o;void main(){o=vec4(0.);}`; +// Ellipses (the hills and their shine): centre and radii in map units, one premultiplied colour, smooth edges. +const ELL_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aE;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out vec2 vr; +void main(){vec2 c=(aE.xy-uCam.xy)*uCam.z+uView*.5,r=aE.zw*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m.x:m.x,(gl_VertexID&2)==0?-m.y:m.y);vr=r;gl_Position=clip(c+vq,uView,0.);}`; +const ELL_FS=GL_HEAD+`in vec2 vq;flat in vec2 vr;uniform vec4 uCol;uniform float uDpr;out vec4 o; +void main(){float d=(length(vq/vr)-1.)*min(vr.x,vr.y),a=clamp(.5-d*uDpr,0.,1.);if(a<=0.)discard;o=uCol*a;}`; +// Discs for the stencil only (the clouds' puffs): centre and radius in map units. +const CIRC_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aC;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out float vr; +void main(){vec2 c=(aC.xy-uCam.xy)*uCam.z+uView*.5;float r=aC.z*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vr=r;gl_Position=clip(c+vq,uView,0.);}`; +const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(length(vq)>vr)discard;o=vec4(1.);}`; +/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does) and per zoom level + lv (powers of 2): the fan for the fills, the coastlines as line segments (paintWorld()'s curves, four segments each) + for the sand and the dark edge, and the hills. Zoomed out a coastline has far more points than pixels, and its + vertices were most of the card's work: at level lv it is simplified so that no point moves more than COAST_TOL px at + the level's zoom (Douglas-Peucker). Without lv, the whole coastline. COAST and onLand() are not touched. + Each level stays on the card once built (GLX.land, freed with the card): from 0.4 MB zoomed out to 3 MB at the + closest zoom, about 15 MB if a game visits every zoom, so zooming back never builds one again mid-gesture. */ +const COAST_TOL=0.25,COASTP=[]; +// A coastline as paintWorld() draws it (smoothPath(): a quadratic curve from the middle of each side to the next, +// through the corner between them), four segments per curve; the first point is repeated at the end. +function coastPts(ri){let P=COASTP[ri];if(P)return P;const ring=COAST[ri],n=ring.length;P=[]; + const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(ring[n-1],ring[0]);P.push(m); + for(let i=0;i0))return P;const keep=new Uint8Array(n),st=[0,n-1],t2=tol*tol;keep[0]=keep[n-1]=1; + while(st.length){const b=st.pop(),a=st.pop(),ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;let m=-1,md=t2; + for(let i=a+1;i1?1:t;const ex=ax+t*dx-P[i][0],ey=ay+t*dy-P[i][1],d=ex*ex+ey*ey;if(d>md){md=d;m=i;}} + if(m>=0){keep[m]=1;st.push(a,m,m,b);}} + const o=[];for(let i=0;icur||z{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return; + const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return; + coastFan(P,fan); + // Round ends make the joins round, as lineJoin='round' does; both lines are opaque, so the overlaps do not show. + for(let i=0;i+1new Float32Array(a); + G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE, + hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length}; + glMem(gl,'the land');return GLX.land[key]=G;} +// Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map. +// The stencil counts the coasts' windings (+1 for a triangle facing one way, -1 the other: coastFan()), as the 2D +// canvas's nonzero rule does; counting only odd or even made two overlapping coasts cancel out into sea. +function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST); + gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan); + gl.colorMask(false,false,false,false);gl.stencilFunc(gl.ALWAYS,0,255);gl.stencilMask(255); + gl.stencilOpSeparate(gl.FRONT,gl.KEEP,gl.KEEP,gl.INCR_WRAP);gl.stencilOpSeparate(gl.BACK,gl.KEEP,gl.KEEP,gl.DECR_WRAP); + for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArrays(gl.TRIANGLES,0,G.nFan);} + // The cover paints where the count is not zero and sets the stencil back to zero for the next user. + gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,255);gl.stencilOp(gl.ZERO,gl.ZERO,gl.ZERO); + glFill(gl,col);gl.disable(gl.STENCIL_TEST);} +function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col); + for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} +// In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline. +function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z)); + glLandFill(gl,G,ks,5,7,LAND_SHADOW); + glLines(gl,G.sand,G.nSeg,ks); + glLandFill(gl,G,ks,0,0,LAND_GRASS); + glEllipses(gl,G.hills,G.nHill,ks,HILL_COL);glEllipses(gl,G.shine,G.nHill,ks,HILL_SHINE); + glLines(gl,G.edge,G.nSeg,ks);} +// The waves: each one two quadratic curves of four segments, swaying with the map's clock as in drawFrame(). They are +// written into the same array every frame (no garbage for the collector to pick up while you play). +const WAVE_COL=glColor('rgba(255,255,255,.45)'); +function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0; + for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3; + // Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame). + for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y; + for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}} + gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);} +// The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack. +function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)return; + // Written into one array kept from frame to frame, grown when more copies of the map show. + if(!GLX.ca||GLX.ca.lengthv!==GLX.ckey[i])){const A=[]; + for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue; + const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0; + for(let j=0;j+1d.length?`if(k==${i})return vec2(${d[0]}.,${d[1]}.);`:'').join('')}return vec2(0.);} +void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h; + float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false; + if(uPass==${LP.halo}){hw=(w+14.)*.5;col=vec4(1.,79./255.,154./255.,.35);dash=vec2(0.);skip=(fl&${LINE_SEL})==0;} + else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(30./255.,38./255.,64./255.,1.);} + else if(uPass==${LP.dots}){hw=max(1.,w*.25)*.5;col=vec4(1.,1.,1.,.75);dash=dashOf(5);skip=(fl&${LINE_FIBER})==0||uBusy>.5;} + else if(uPass==${LP.plain})col.a=aC.x; + if(skip){gl_Position=vec4(2.,2.,2.,1.);return;} + vec2 d=b-a;float L=length(d);vec2 t=L>1e-4?d/L:vec2(1.,0.),n=vec2(-t.y,t.x);float m=hw+1./uDpr; + float sx=(gl_VertexID&1)==0?-m:L+m,sy=(gl_VertexID&2)==0?-m:m; + vLoc=vec2(sx,sy);vLen=L;vS0=aP.x*uCam.z;vHalf=hw;vCol=col;vDash=dash;vButt=uPass==${LP.plain}&&(fl&${LINE_ROUND})==0?1.:0.; + gl_Position=clip(a+t*sx+n*sy,uView,(uPass==${LP.plain}?.9998:aC.x)*2.-1.);}`; +const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol;flat in vec2 vDash;uniform float uDpr;out vec4 o; +void main(){float x=vLoc.x,y=vLoc.y,d; + if(vButt>.5&&(x<0.||x>vLen))discard; + if(vDash.x<=0.){float c=clamp(x,0.,vLen);d=length(vec2(x-c,y));} + else{float P=vDash.x+vDash.y,g=vS0+x,k=floor(g/P);d=1e9; + for(int i=-1;i<=1;i++){float a0=(k+float(i))*P,lo=max(a0,vS0),hi=min(a0+vDash.x,vS0+vLen);if(lo<=hi){float c=clamp(g,lo,hi);d=min(d,length(vec2(g-c,y)));}}} + float al=clamp((vHalf-d)*uDpr+.5,0.,1.);if(al<=0.)discard;o=vec4(vCol.rgb*vCol.a*al,vCol.a*al);}`; +// Plain lines (coasts, waves, cables): colour and opacity from the data, flat ends unless LINE_ROUND, under the tubes. +function glLines(gl,vao,n,ks){const L=GLX.line;gl.useProgram(L.p);gl.bindVertexArray(vao);gl.uniform1i(L.u.uPass,LP.plain);gl.uniform1f(L.u.uBusy,0); + for(const k of ks){glSet(gl,L,k,1);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} +/* Packets: one instance per packet; where it is on its tube comes from the tube's points (a float texture of x, y and + the share of the length so far, GL_PTS_W texels a row), found by bisection the way polyAtXY() finds it. */ +const GL_PTS_W=2048; +const GL_PK_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aK;layout(location=1) in vec4 aQ; +uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uT,uFar;uniform highp sampler2D uPts; +out vec2 vLoc;flat out float vR,vLw; +vec4 P(int i){return texelFetch(uPts,ivec2(i%${GL_PTS_W},i/${GL_PTS_W}),0);} +void main(){float n=uFar>.5?max(1.,floor(aK.w*.5)):aK.w,i=aQ.x;if(i>=n){gl_Position=vec4(2.,2.,2.,1.);return;} + float t=fract(uT*90./max(aK.z*uCam.z,40.)+i/n);if(mod(i,2.)>.5)t=1.-t; + int o=int(aK.x+.5),lo=1,hi=int(aK.y+.5)-1;for(int s=0;s<16&&lop0.z?(t-p0.z)/(p1.z-p0.z):0.;vec2 c=(mix(p0.xy,p1.xy,f)-uCam.xy)*uCam.z+uView*.5; + float w=aQ.y*uWMul,r=uFar>.5?1.6:max(2.2,w*.42),lw=uFar>.5?1.:1.5,m=r+lw*.5+1./uDpr; + vec2 q=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vLoc=q;vR=r;vLw=lw; + gl_Position=clip(c+q,uView,aQ.z*2.-1.);}`; +const GL_PK_FS=GL_HEAD+`in vec2 vLoc;flat in float vR,vLw;uniform float uDpr;out vec4 o; +void main(){float d=length(vLoc),out_=clamp((vR+vLw*.5-d)*uDpr+.5,0.,1.);if(out_<=0.)discard; + float inn=clamp((vR-vLw*.5-d)*uDpr+.5,0.,1.);vec3 c=mix(vec3(30./255.,38./255.,64./255.),vec3(1.),inn);o=vec4(c*out_,out_);}`; +/* The tubes as instance data: their segments (see LINE_STRIDE; later tubes are nearer), their packets (first point, + points, length, packets | which, base width, depth, -), and every tube's points in the texture. */ +const glDepth=(gi,N)=>1-(gi+1)/(N+2); +function glBuild(LG,GM,looks){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0; + for(let gi=0;gix.id===selId))continue;const L=looks[gi],{pts,cum,len}=GM[gi],dep=glDepth(gi,N),col=glColor(L.col); + for(let j=0;j+1{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass); + for(const k of ks){glSet(gl,L,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}; + if(GLX.nSeg)for(const pass of [LP.casing,LP.colour,LP.dots])lines(pass); + if(GLX.nPk){gl.useProgram(K.p);gl.bindVertexArray(GLX.pv.v);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.uniform1i(K.u.uPts,0); + gl.uniform1f(K.u.uT,now/1000);gl.uniform1f(K.u.uFar,far?1:0);for(const k of ks){glSet(gl,K,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,GLX.nPk);}} + // The selection's halo goes over earlier tubes but under its own line and later ones, as in 2D. + if(GLX.nHalo){gl.depthFunc(gl.LESS);gl.depthMask(false);lines(LP.halo,GLX.hv.v,GLX.nHalo);gl.depthMask(true);} + gl.bindVertexArray(null);} diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js new file mode 100644 index 0000000..997e7a1 --- /dev/null +++ b/src/game/96-map/59-gl-sprites.js @@ -0,0 +1,151 @@ +/* Pictures on the card. Cities, labels, markers and everything that bobs or pulses on them (cones, ships, offer + bubbles, hot badges, floaters) are painted once with the 2D canvas, packed into one texture (the atlas), and drawn + as instanced quads, with the small round things (lights, steam, glows) as discs, in one draw per frame after the + tubes. Without WebGL the same calls draw the pictures with the 2D canvas, so the map's code does not care which. */ +const SPR_MAX=1400,SPR_STRIDE=13; +// The card's pictures (SPRS) and the 2D map's (SPRC), by key; both at the screen's pixel density SPR_DPR. +const SPRS=new Map(),SPRC=new Map();let SPR_DPR=0; +/* The 2D map's pictures each keep a canvas, so they are also held to a size: a long zoom on a big network paints every + city again at each step, and the list (only capped at SPR_MAX) held up to 180 MB of them where a frame shows 2 to + 23 MB. At the end of a frame over SPRC_BUDGET bytes, the pictures it did not use go, those unused the longest first, + down to 3/4 of the budget (so this happens once in a while, not every frame). The frame's own are always kept: a + screen that needs more than the budget keeps what it needs. A canvas let go is emptied (0×0) at once, which frees + its pixels without waiting for the collector. The card's atlas has its own fixed size (GLS.size). + SPR_F counts frames (draw()); finding or drawing a picture marks it as used in this one (e.f). */ +const SPRC_BUDGET=48*1048576;let SPRC_B=0,SPR_F=0; +const sprFree=e=>{if(e.cv){e.cv.width=e.cv.height=0;e.cv=null;}}; +function sprcTrim(){if(SPRC_B<=SPRC_BUDGET)return;const old=[];for(const [k,e] of SPRC)if(e.fa[0]-b[0]);const goal=SPRC_BUDGET*0.75; + for(const [,k,e] of old){if(SPRC_B<=goal)break;SPRC.delete(k);SPRC_B-=e.pw*e.ph*4;sprFree(e);}} +const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0,upq:false,memT:-1e9}; +/* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its + colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */ +const SPR_VS=GL_HEAD+`layout(location=0) in vec4 aP;layout(location=1) in vec4 aUV;layout(location=2) in vec4 aC;layout(location=3) in float aK; +uniform vec2 uDev;uniform float uDpr;out vec2 vUV,vQ;out vec4 vC;flat out float vK,vR; +void main(){vec2 c=vec2((gl_VertexID&1)==0?0.:1.,(gl_VertexID&2)==0?0.:1.),p; + if(aK>.5){float m=aP.z+1./uDpr;vQ=(c*2.-1.)*m;vR=aP.z;vUV=vec2(0.);p=aP.xy+vQ;} + else{vQ=vec2(0.);vR=0.;vUV=mix(aUV.xy,aUV.zw,c);p=aP.xy+c*aP.zw;} + vC=aC;vK=aK;gl_Position=vec4(p.x*uDpr/uDev.x*2.-1.,1.-p.y*uDpr/uDev.y*2.,0.,1.);}`; +const SPR_FS=GL_HEAD+`uniform sampler2D uTex;uniform float uDpr;in vec2 vUV,vQ;in vec4 vC;flat in float vK,vR;out vec4 o; +void main(){if(vK>.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);} + else o=texture(uTex,vUV)*vC.a;}`; +function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b; + // 4096 px square (64 MB), or what the card allows if that is less (some phones). A card that has not the memory for + // it gets 2048 (16 MB: more resets of the atlas, the same map); without even that, the map stays 2D (glMem). + GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);glMem(gl,'setup'); + for(GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096);;GLS.size>>=1){ + gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null); + try{glMem(gl,'the pictures');break;}catch(e){if(GLS.size<=2048)throw e;}} + for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR); + for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE); + GLS.shx=GLS.shy=GLS.shh=0;GLS.memT=-1e9;GLS.upq=false;} +// Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it). +function spritesReset(){glsDrawNow();for(const e of SPRC.values())sprFree(e);SPRS.clear();SPRC.clear();SPRC_B=0;GLS.shx=GLS.shy=GLS.shh=0;} +// The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten. +function spritesDrop(){GLS.n=GLS.up=0;GLS.upq=false;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} +/* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a + canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context + and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. + Each picture goes in with a clear border of GLS_GAP px: the card blends the texels around the point it reads, so a + picture drawn off whole pixels or a little stretched read half a texel past its edge, and showed a thin line of its + neighbour in the atlas (or of a picture from before the last reset, which leaves the texture as it was). */ +const GLS_GAP=1; +const GLS_PAD={cv:null,g:null}; +function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('canvas');P.cv.width=P.cv.height=256;} + if(P.cv.width{const e=sprMap().get(key);if(e)e.f=SPR_F;return e;}; +// A picture of w×h CSS px with its anchor at (ax,ay): painted once by paint(g) (the 2D canvas, at the screen's pixel +// density), and kept by key in SPRS (the card's) or SPRC (the 2D map's). +function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.get(key);if(e){e.f=SPR_F;return e;} + if(SPRS.size+SPRC.size>=SPR_MAX)spritesReset(); + const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx; + e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1,f:SPR_F}; + const G=GLS_GAP; + if(gpu&&pw+2*G<=GLS.size&&ph+2*G<=GLS.size){const P=glsPad(pw+2*G,ph+2*G),g=P.g; + // Clipped to the picture, as its own canvas would be, so the border stays clear. + g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw+2*G,ph+2*G);g.beginPath();g.rect(G,G,pw,ph);g.clip();ctx=g; + try{g.setTransform(DPR,0,0,DPR,G,G);sprPen(g);paint(g);}finally{ctx=saved;g.restore();} + // A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next. + try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);} + }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g; + try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;}e.cv=cv; + if(M===SPRC)SPRC_B+=pw*ph*4;} + M.set(key,e);return e;} +/* A picture starts with the pen the map's own canvas has when it draws cities and markers: the tubes leave it with + round line ends and corners, the labels with text centred on its middle. Drawn straight on the map, the dashed rings, + the cones' tips and a sleeping POP's "zzz" took those, and a new canvas has others (square ends, text on its baseline). */ +function sprPen(g){g.lineCap='round';g.lineJoin='round';g.textAlign='center';g.textBaseline='middle';} +// Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame. +function glsEnsure(e){if(e.up)return true;const gl=GLX.gl,G=GLS_GAP;if(!gl||!GLS.prog||!e.cv)return false; + if(e.pw+2*G>GLS.size||e.ph+2*G>GLS.size)return false; + const P=glsPad(e.pw+2*G,e.ph+2*G),g=P.g;g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,e.pw+2*G,e.ph+2*G);g.drawImage(e.cv,G,G); + try{return glsPut(gl,e,P.cv);}catch(x){throw glErr(x);}} +// src holds the picture at (GLS_GAP,GLS_GAP), in a clear border that goes into the atlas with it. +function glsPut(gl,e,src){const G=GLS_GAP,pw=e.pw+2*G,ph=e.ph+2*G,A=GLS.size;if(pw>A||ph>A)return false; + if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;} + if(GLS.shy+ph>A){spritesReset();return false;} + const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph); + gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true); + // Only the picture's corner of the source (with its border): the pad is bigger than most pictures. + gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); + GLS.up++;Object.assign(e,{up:true,u0:(x+G)/A,v0:(y+G)/A,u1:(x+pw-G)/A,v1:(y+ph-G)/A});return true;} +// The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace. +function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;} +// Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas. +function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const o=glsNext(),d=GLS.data; + d[o]=x;d[o+1]=y;d[o+2]=w;d[o+3]=h;d[o+4]=e.u0;d[o+5]=e.v0;d[o+6]=e.u1;d[o+7]=e.v1;d[o+8]=d[o+9]=d[o+10]=0;d[o+11]=ctx.globalAlpha;d[o+12]=0;} + else if(e.cv)ctx.drawImage(e.cv,x,y,w,h);} +// A round dot of radius r at (x,y), in colour col (CSS colour string) at opacity a, on the card or the 2D canvas. +function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),o=glsNext(),d=GLS.data; + d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;} + else{const sa=ctx.globalAlpha;if(a!==undefined)ctx.globalAlpha=a;ctx.fillStyle=col;ctx.beginPath();ctx.arc(x,y,r,0,7);ctx.fill();ctx.globalAlpha=sa;}} +/* Pictures that grow with the zoom (cities, ships, badges) are painted at steps of 1/24 of their scale. On the card, + while the zoom moves, they keep the step of the scale they had when it began, stretched by up to 1.25× either way + (the card filters them smoothly), and are painted again at the right step once the zoom rests (ZOOM_REST ms): a + pinch otherwise repainted every city at every step, hundreds of pictures a frame, and filled the atlas over and + over. ZH.sc is the icon scale held, ZH.f how much a picture is painted smaller (<1) or bigger than it shows. */ +const CSPR_STEP=24,ZOOM_REST=250,ZH={z:0,t:-1e9,sc:0,f:1}; +function zoomHold(sc,G){const t=performance.now();if(cam.z!==ZH.z){ZH.z=cam.z;ZH.t=t;} + if(!G||!ZH.sc||t-ZH.t>=ZOOM_REST||sc/ZH.sc>1.25||ZH.sc/sc>1.25)ZH.sc=sc;ZH.f=ZH.sc/sc;} +// The zoom moved a moment ago: the pictures may be stretched, so a still map is drawn again once it rests (mapStill()). +const zoomMoving=()=>performance.now()-ZH.tMath.max(1/CSPR_STEP,Math.round(k*ZH.f*CSPR_STEP)/CSPR_STEP); +// A small picture w×h px at scale k with its anchor at (ax,ay), painted once by paint(g) with the origin on the anchor +// (k in steps of 1/24, as the cities; zoomed: k grows with the zoom, and is held while it moves, sprQ()), then drawn with +// the anchor at (x,y). Things that bob or pulse are drawn as these at a moving place, so the overlay above the card +// stays untouched (repainting it costs a whole screen of pixels). +// The full key of a stamp at scale kq, kept per key: it was built again for every stamp on every frame. +const STK=new Map(); +function stamp(key,w,h,ax,ay,k,x,y,paint,zoomed){const kq=zoomed?sprQ(k):Math.max(1/CSPR_STEP,Math.round(k*CSPR_STEP)/CSPR_STEP),r=k/kq; + let m=STK.get(key);if(!m||m.kq!==kq){if(STK.size>4000)STK.clear();STK.set(key,m={kq,k:key+'|'+kq});} + const e=spriteHas(m.k)||spriteEntry(m.k,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);}); + blit(e,x-e.ax*r,y-e.ay*r,e.w*r,e.h*r);} +// Text with an outline, centred on (x,y), as a picture placed on whole device pixels; tw is its width, px its size. +function textStamp(t,font,px,tw,fill,stroke,lw,x,y){const W=Math.ceil(tw+lw+4),H=Math.ceil(px*1.5+lw+2); + const e=spriteEntry(['txt',t,font,fill,stroke,lw].join('|'),W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.font=font;g.textAlign='center';g.textBaseline='middle'; + if(lw){g.lineWidth=lw;g.lineJoin='round';g.strokeStyle=stroke;g.strokeText(t,0,0);}g.fillStyle=fill;g.fillText(t,0,0);}); + blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);} +// Sends the queued pictures to the card in one draw. +function glsDrawNow(){const gl=GLX.gl,n=GLS.n;GLS.n=0;if(!gl||!GLS.prog||!n)return; + try{glsDraw(gl,n);}catch(x){throw glErr(x);}} +function glsDraw(gl,n){gl.useProgram(GLS.prog.p);gl.bindVertexArray(GLS.vao);gl.bindBuffer(gl.ARRAY_BUFFER,GLS.buf); + gl.bufferData(gl.ARRAY_BUFFER,GLS.data.subarray(0,n*SPR_STRIDE),gl.STREAM_DRAW); + gl.uniform2f(GLS.prog.u.uDev,GLX.c.width,GLX.c.height);gl.uniform1f(GLS.prog.u.uDpr,DPR);gl.uniform1i(GLS.prog.u.uTex,0); + gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex); + gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST); + gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);gl.bindVertexArray(null);} +/* The end of a frame on the card: the pictures go up over the tubes. The frame is over even if that draw fails. + Pictures sent are checked (did the card take them?): a card short of memory may refuse one without throwing, and the + picture would be kept as sent. It then gives the map to 2D (glMem() throws, draw() draws the frame again there and + glKill() forgets the card's pictures). Each read waits for the card to finish everything sent so far, so it is done + at most once every GL_MEM_EVERY ms: the card keeps an error until it is read, so a later read still finds it, and a + picture refused in between shows at worst as a dark box for that time. The first pictures sent into a new atlas are + checked at once (a card that allocates it lazily refuses there). A frame that only reuses the atlas asks nothing. */ +const GL_MEM_EVERY=1000; +function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;if(GLS.up)GLS.upq=true;GLS.up=0; + if(GLS.upq&&GLX.gl){const t=performance.now();if(t-GLS.memT>=GL_MEM_EVERY){GLS.memT=t;GLS.upq=false;glMem(GLX.gl,'the pictures');}} + glsDrawNow();} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 6324735..6709e30 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -1,11 +1,25 @@ -function draw(now){DFC=new Map();try{drawFrame(now);}finally{DFC=null;}} +/* A frame. An error from the card itself (glErr()) gives WebGL up for this session and draws the same frame again in + 2D, once; any other error goes on to the loop's tickErr(). Either way the 2D context and the sprite queue are reset. */ +function draw(now){for(let pass=0;;pass++){let err=null;DFC=new Map();SPR_F++; + try{drawFrame(now);}catch(e){err=e;} + try{glsFrameEnd();}catch(e){if(!err)err=e;}finally{DFC=null;GLS.frame=false;GLS.n=0;ctx=CTX0;sprcTrim();} + if(!err)return;if(!err.glErr||pass)throw err;glKill(err);}} +// Rectangles on a 64 px grid: a new one is compared only with the few that share its cells (a plain list made the +// label placement quadratic in the number of cities). +class RGrid{constructor(){this.m=new Map();} + cells(r,f){for(let cx=Math.floor(r.x/64);cx<=Math.floor((r.x+r.w)/64);cx++)for(let cy=Math.floor(r.y/64);cy<=Math.floor((r.y+r.h)/64);cy++)f(cx*100003+cy);} + push(r){this.cells(r,k=>{const a=this.m.get(k);if(a)a.push(r);else this.m.set(k,[r]);});} + hits(r){let h=false;this.cells(r,k=>{if(h)return;const a=this.m.get(k);if(a)for(const q of a)if(r.x