Merge #281: draw the map with WebGL2 by default, 2D as fallback

This commit is contained in:
Frederic Jung 2026-11-05 10:13:28 +01:00
commit 13768c61cb
No known key found for this signature in database
50 changed files with 2690 additions and 118 deletions

View file

@ -6,7 +6,7 @@ const { load } = require('./harness');
// land on another is left out, unless the cable touches the selected city.
const labels = (ev, sel) => JSON.parse(ev(`(()=>{ACT.start({});S.nextFail=1e9;S.nextEvent=1e9;UI.sel=${sel ? `{type:'city',id:'${sel}'}` : 'null'};
cam.x=(CITY.mnl.x+CITY.dvo.x)/2;cam.y=(CITY.mnl.y+CITY.dvo.y)/2;cam.z=4.5;const out=[];
ctx.fillText=(t,x,y)=>out.push({t,x,y,w:ctx.measureText(t).width});ctx.strokeText=()=>{};drawCables([0]);return JSON.stringify(out);})()`));
const ts=textStamp;textStamp=(t,f,px,w,c,sk,lw,x,y)=>out.push({t,x,y,w});try{drawCables([0]);}finally{textStamp=ts;}return JSON.stringify(out);})()`));
test('cable names never sit on top of each other', () => {
const { ev, errors } = load();

View file

@ -0,0 +1,109 @@
// Settings › Diagnostic info (src/game/96-map/97-diagnostics.js): one readout for bug reports, which replaced the
// separate viewport readout and frame meter. It shows the screen, what draws the map (and why it is 2D), and how fast;
// the setting, ?vp/?fps and five taps on the date open it, and it is remembered on the device.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open(opts = {}) {
const h = load({ seed: 777, ...opts });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();console.warn=()=>{};`);
// The readout refreshes on an interval: closing the window stops it, so the test process can end.
h.done = () => h.dom.window.close();
return h;
}
const text = (ev) => ev('(()=>{const e=document.getElementById("diag");return e?e.textContent:null;})()');
test('the setting shows one readout with the screen, the map and its speed, and remembers it', () => {
const h = open();
const { ev, errors } = h;
try {
assert.equal(text(ev), null, 'off by default');
ev('ACT.settings()');
assert.match(ev('$("modal").innerHTML'), new RegExp(ev('tr("settings.diagnostic_info")')));
ev('ACT.vpSet({v:"on"})');
const t = text(ev);
for (const part of ['Series of Tubes', 'inner ', 'screen ', 'safe top', 'tabbar', 'map: ', 'fps', 'draw ']) assert.ok(t.includes(part), `shows "${part}"`);
assert.equal(ev('document.querySelectorAll("#diag").length'), 1, 'one readout');
assert.equal(ev('localStorage.getItem("sot-vp")'), '1');
ev('ACT.vpSet({v:"off"})');
assert.equal(text(ev), null);
assert.equal(ev('localStorage.getItem("sot-vp")'), null);
assert.deepEqual(errors, []);
} finally { h.done(); }
});
test('it says what draws the map, and why it is the 2D canvas', () => {
const h = open();
const { ev, errors } = h;
try {
ev('diagOn(true)');
const map = () => ev('diagMap()');
ev('mapGl(false,false)');
assert.equal(map(), 'map: 2D (Always 2D)');
ev('mapGl(true,false);glKill(new Error("the graphics card is out of memory (the pictures)"))');
assert.equal(map(), 'map: 2D (the graphics card is out of memory (the pictures))');
ev('GLX.dead=false;GLX.lost=true');
assert.equal(map(), 'map: 2D (graphics context lost, waiting for it back)');
ev('GLX.lost=false;GLX.gl={};GLX.shown=true;GLX.gpu="ANGLE (NVIDIA GeForce GTX 980)"');
assert.equal(map(), 'map: WebGL2 · ANGLE (NVIDIA GeForce GTX 980)');
ev('const s=S;S=null;window.__S=s');
assert.equal(map(), 'map: none (title screen)');
ev('S=__S;GLX.gl=null;GLX.shown=false');
assert.deepEqual(errors, []);
} finally { h.done(); }
});
test('it measures frames per second, the slowest frames and draw()', () => {
const h = open();
const { ev, errors } = h;
try {
ev('diagOn(true)');
// 60 frames, so 59 intervals: 58 of 16 ms and a last one of 50 ms (978 ms in all); the map drawn on every other
// one (a still map is not drawn again), in 2 ms: 30 in 978 ms, 31 a second.
ev('let t=1000;for(let i=0;i<60;i++){t+=i===59?50:16;if(i%2)DIAG.dms=2;diagFrame(t);}diagShow();');
const t = text(ev);
assert.match(t, /\b60 fps · map drawn 31\/s · p95 16 ms · max 50 ms/);
assert.match(t, /draw 2\.0 ms · x0 · zoom /);
assert.deepEqual(errors, []);
} finally { h.done(); }
});
test('?fps and ?vp open it, ?nofps closes it, and it stays open on this device', () => {
for (const [url, storage, want] of [['?fps', {}, true], ['?vp', {}, true], ['?nofps', { 'sot-vp': '1' }, false], ['', { 'sot-vp': '1' }, true], ['', {}, false]]) {
const h = load({ seed: 777, url: 'https://tests.invalid/' + url, storage });
try {
assert.equal(h.ev('!!document.getElementById("diag")'), want, `${url || 'no flag'} ${JSON.stringify(storage)}`);
assert.equal(h.ev('localStorage.getItem("sot-vp")'), want ? '1' : null, 'remembered as one setting');
} finally { h.dom.window.close(); }
}
});
test('five quick taps on the date toggle it (an installed app has no address bar)', () => {
const h = open();
const { ev, errors } = h;
try {
const tap = () => ev('document.getElementById("hDate").click()');
for (let i = 0; i < 5; i++) tap();
assert.equal(ev('DIAG.on'), true);
for (let i = 0; i < 5; i++) tap();
assert.equal(ev('DIAG.on'), false);
assert.deepEqual(errors, []);
} finally { h.done(); }
});
test('on a 360 px phone the readout wraps inside the screen instead of running off it', () => {
const h = open();
const { ev } = h;
try {
ev('diagOn(true)');
const st = ev('document.getElementById("diag").style.cssText');
assert.match(st, /max-width: calc\(100vw - 32px\)/);
assert.match(st, /white-space: pre-wrap/);
assert.match(st, /pointer-events: none/, 'it never takes a tap meant for the map');
} finally { h.done(); }
});

80
tests/gpu-bench.test.js Normal file
View file

@ -0,0 +1,80 @@
// The GPU benchmark's panel (scripts/lib/gpu-bench-client.js): one trial must never reach into the next. A day the route
// worker is still routing lands on the save it was routed for, a pan's frame callback stops with its trial, every
// trial starts from the same random numbers, and the table says which map really drew each run.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const CLIENT = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'gpu-bench-client.js'), 'utf8');
function open(cfg = {}) {
const h = load({ seed: 777 });
h.ev(`window.__BENCH__=${JSON.stringify({ expose: true, secs: 0.15, warm: 0, settleMs: 300, ...cfg })};`);
h.ev(CLIENT);
h.ev(`__bench.setSave(${JSON.stringify(SAVE)});save=()=>{};`);
return h;
}
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
// A day in flight in the worker when the trial ends: rwDone() would run its dayPost() whenever the answer comes.
const IN_FLIGHT = `window.__old=S;RW.seq=41;RW.job={seq:41,d:201,gen:RW.gen-1,t:0};window.__posts=[];
dayPost=function(d){__posts.push({d,old:S===__old});};`;
test('a late answer from the route worker lands on the trial it belongs to, not the next one', async () => {
const { ev, errors } = open();
await ev('__bench.reset()');
ev(IN_FLIGHT);
ev('setTimeout(()=>rwDone({seq:41}),60)');
await ev('__bench.reset()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(__posts)')), [{ d: 201, old: true }], 'its day ran on the old save, before the new one was loaded');
assert.equal(ev('S!==__old&&RW.job===null'), true);
assert.deepEqual(errors, []);
});
test('an answer that never comes is dropped, and coming late it changes nothing', async () => {
const { ev, errors } = open();
await ev('__bench.reset()');
ev(IN_FLIGHT);
ev('console.warn=()=>{}');
await ev('__bench.reset()');
assert.equal(ev('RW.job'), null, 'the next trial does not wait for it forever');
ev('rwDone({seq:41})');
assert.deepEqual(JSON.parse(ev('JSON.stringify(__posts)')), [], 'nothing ran on the new save');
assert.deepEqual(errors, []);
});
test('a pan stops with its trial: the next trial’s camera is left alone', async () => {
const { ev, errors } = open();
const m = JSON.parse(await ev('__bench.measure({id:"pan",pan:true,z:1.4,speed:0},60,"2d").then(JSON.stringify)'));
assert.ok(m.fps > 0, 'the pan ran');
ev('cam.x=0');
await wait(120);
assert.equal(ev('cam.x'), 0, 'no frame of the pan came after it');
const x8 = await ev('(async()=>{const p=__bench.measure({id:"x8",z:1.4,speed:8},60,"2d");await new Promise(r=>setTimeout(r,20));const x=cam.x;await p;return [x,cam.x];})()');
assert.equal(x8[0], x8[1], 'the next scenario keeps its camera where it put it');
assert.deepEqual(errors, []);
});
test('every trial starts from the same random numbers and an empty clock', async () => {
const { ev, errors } = open();
const draws = async () => { await ev('acc=12345;animT=999;__bench.reset()'); return ev('JSON.stringify([acc,animT,Math.random(),Math.random(),Math.random()])'); };
const a = await draws(), b = await draws();
assert.equal(a, b);
assert.deepEqual(JSON.parse(a).slice(0, 2), [0, 0]);
assert.deepEqual(errors, []);
});
test('the table says which map drew each run, and what each column measures', () => {
const { ev } = open();
const md = ev(`(()=>{const m=(drawn,gl,flat,gpu)=>({fps:60,p95:17,drawMs:1,drawn,glFrames:gl,flatFrames:flat,gpuMs:gpu});
const res={'2d':{'x1-mid':m('2d',0,300,null)},gl:{'x1-mid':m('mixed',12,288,0.8)}};
return __bench.table(res,{gpu:'stub',ua:'ua',w:1,h:1,dpr:1,hz:60,cores:1,save:'s',reps:1});})()`);
assert.match(md, /WebGL GPU/, 'a GPU column when the card timed its frames');
assert.match(md, /CPU time on the main thread/, 'draw() is said to be CPU time');
assert.match(md, /Not drawn by the map they name: Map at x1 \(zoom 1\.4\) \(WebGL: 288 frames in 2D/, 'a run that fell back to 2D is flagged');
const merged = JSON.parse(ev(`JSON.stringify(__bench.merge([{fps:50,drawn:'gl',hidden:false,slow:[1]},{fps:70,drawn:'gl',hidden:true,slow:[2]},{fps:60,drawn:'2d',hidden:false,slow:[]}]))`));
assert.deepEqual(merged, { fps: 60, drawn: 'gl+2d', hidden: true, slow: [1, 2], runs: 3 });
});

View file

@ -0,0 +1,68 @@
// The 2D map keeps a canvas per picture (59-gl-sprites.js). A long zoom on a big network paints every city again at
// each step, and the list, capped only by its length, held up to 180 MB of pictures where a frame shows at most 23 MB.
// It is now held to SPRC_BUDGET bytes: past it, the pictures no frame used since the one before are let go, and those
// in use are always kept. The page's clock is set by hand, so nothing depends on how fast the test runs.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
// The big network on a 1280×800 screen at 2× in 2D. Canvases are counted as they are made; their contexts take any call.
function open() {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false,false);
DPR=2;CW=1280;CH=800;cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=0.6;window.__cv=0;
const ce=document.createElement.bind(document);document.createElement=function(t){const e=ce(t);if(String(t).toLowerCase()==='canvas')__cv++;return e;};
HTMLCanvasElement.prototype.getContext=function(){return this.__c||(this.__c=new Proxy({},{get(t,k){if(k in t)return t[k];
if(k==='measureText')return s=>({width:String(s).length*7});if(k==='createLinearGradient')return ()=>({addColorStop(){}});return ()=>{};},set(t,k,v){t[k]=v;return true;}}));};
window.__bytes=()=>{let b=0;for(const e of SPRC.values())b+=e.pw*e.ph*4;return b;};
// What the last frame drew: its pictures and their bytes.
window.__used=()=>{let n=0,b=0;for(const e of SPRC.values())if(e.f===SPR_F){n++;b+=e.pw*e.ph*4;}return {n,b};};`);
return h;
}
// A pinch from 0.6 to 3.2 and back in 180 frames of 16 ms: the most bytes held, and the most a frame used.
const PINCH = `(()=>{let held=0,used=0,drift=0;for(let i=0;i<=180;i++){const f=i<=90?i/90:(180-i)/90;cam.z=0.6*Math.pow(3.2/0.6,f);__T+=16;draw(__T);
const b=__bytes();held=Math.max(held,b);used=Math.max(used,__used().b);drift=Math.max(drift,Math.abs(b-SPRC_B));}return JSON.stringify({held,used,drift});})()`;
test('a long zoom on the 2D map holds its pictures to the budget, plus what one frame needs', () => {
const { ev, errors } = open();
const r = JSON.parse(ev(PINCH));
const MB = 1048576, budget = ev('SPRC_BUDGET');
assert.equal(r.drift, 0, 'the bytes counted are the bytes held');
assert.ok(r.used > 5 * MB, `a frame uses a real share of it (${(r.used / MB).toFixed(1)} MB)`);
// After a frame, over the budget only if that frame alone needs more.
assert.ok(r.held <= Math.max(budget, r.used), `held ${(r.held / MB).toFixed(1)} MB, budget ${budget / MB} MB`);
assert.ok(r.held < 80 * MB, `far under the 180 MB it held before (${(r.held / MB).toFixed(1)} MB)`);
assert.deepEqual(errors, []);
});
test('the pictures a frame uses are never let go, and a still map paints nothing new', () => {
const { ev, errors } = open();
ev(PINCH);
// Every picture the last frame drew is still kept (it was used, so it cannot have been let go).
ev('window.__keep=[];const b0=blit;blit=function(e,...a){__keep.push(e);return b0(e,...a);};__T+=16;draw(__T);blit=b0;');
assert.ok(ev('__keep.length') > 50);
assert.equal(ev('__keep.every(e=>[...SPRC.values()].includes(e))'), true, 'every picture of the frame is kept');
// The same view again and again: everything comes from the kept pictures.
ev('window.__c0=__cv;for(let i=0;i<5;i++){__T+=16;draw(__T);}');
assert.equal(ev('__cv-__c0'), 0, 'no picture painted again');
assert.deepEqual(errors, []);
});
test('under the budget nothing is let go', () => {
const { ev, errors } = open();
ev('cam.z=1.1;__T+=16;draw(__T);window.__n=SPRC.size;window.__b=SPRC_B;');
assert.ok(ev('__b') < ev('SPRC_BUDGET'));
// A small pan: new pictures come in, none goes.
ev('for(let i=0;i<10;i++){cam.x+=4;__T+=16;draw(__T);}');
assert.ok(ev('SPRC.size') >= ev('__n'), 'the list only grew');
assert.equal(ev('SPRC_B'), ev('__bytes()'));
// A reset (a new pixel density) forgets the bytes with the pictures.
ev('DPR=1;__T+=16;draw(__T);');
assert.equal(ev('SPRC_B'), ev('__bytes()'));
assert.deepEqual(errors, []);
});

308
tests/map-2d.test.js Normal file
View file

@ -0,0 +1,308 @@
// The 2D map, for players who keep it (Settings › Map drawing › Always 2D, or no usable graphics card). The WebGL work
// changed it too: cities, labels and markers are painted once as pictures and reused (59-gl-sprites.js), and each
// tube's look is worked out once per day's routing (mapLinks(), 55-link-look.js). These tests hold the 2D map to what
// it drew before:
// - a frame drawn with the pictures kept from earlier states is, call for call, the frame painted from scratch: no
// picture is ever shown for a state it was not painted for (on the big network, and in seeded random games);
// - every tube's width, colour, dash and packets follow the formulas main's 2D map used, after every move and day;
// - the 2D map never asks for WebGL, never draws a picture it has no canvas for, and keeps one canvas per picture;
// - every picture starts with the pen main's map had when it drew the same thing straight on the map (round line
// ends, centred text), or its dashed rings and markers would come out differently.
// The page's clock is set by hand, so nothing depends on how fast the test runs. Comparing pixels with main needs a real
// browser, which npm test does not use: that was done by hand, in Chromium, for this change.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { load } = require('./harness');
const page = require('../scripts/lib/page');
const { openPage, playGame, rng } = require('../scripts/lib/route-fuzz');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
/* In the page: every canvas made from now on records what is drawn on it, and the map's own context records the
frame. A picture is known by what was painted on it (a hash of its calls), so a frame's calls say which picture went
where. WebGL is not there (getContext gives null for it), and every request for it is counted. */
const KIT = `window.__M2D=(()=>{
const N=v=>typeof v==='number'?String(Math.round(v*1000)/1000):v==null?String(v):typeof v==='function'?'fn':
v instanceof HTMLCanvasElement?v.__cid():Array.isArray(v)?'['+v.map(N).join(',')+']':typeof v==='object'?'obj':String(v);
const M=['arc','arcTo','beginPath','bezierCurveTo','clearRect','clip','closePath','drawImage','ellipse','fill','fillRect','fillText',
'lineTo','moveTo','quadraticCurveTo','rect','resetTransform','restore','rotate','roundRect','save','scale','setLineDash','setTransform',
'stroke','strokeRect','strokeText','transform','translate'];
// With each call that paints, the state of the context it uses (a picture does not care about the font, say).
const IMG=['globalAlpha','globalCompositeOperation'],FILL=[...IMG,'fillStyle'],LINE=[...IMG,'strokeStyle','lineWidth','lineDashOffset','lineJoin','lineCap'],
TXT=['font','textAlign','textBaseline'];
const PAINT={drawImage:IMG,clearRect:[],fill:FILL,fillRect:FILL,stroke:LINE,strokeRect:LINE,fillText:[...FILL,...TXT],strokeText:[...LINE,...TXT]};
const DEF={globalAlpha:1,fillStyle:'#000000',strokeStyle:'#000000',lineWidth:1,font:'10px sans-serif',lineDashOffset:0,lineJoin:'miter',lineCap:'butt',
textAlign:'start',textBaseline:'alphabetic',globalCompositeOperation:'source-over'};
function rec(c,keep){const Q={h:2166136261,n:0,log:keep?[]:null};
const add=s=>{for(let i=0;i<s.length;i++)Q.h=Math.imul(Q.h^s.charCodeAt(i),16777619)>>>0;Q.n++;if(Q.log)Q.log.push(s);};
for(const m of M)c[m]=function(...a){let s=m+'('+a.map(N).join(',')+')';for(const k of PAINT[m]||[])s+=' '+N(this[k]);add(s);};
Object.assign(c,DEF);c.__Q=Q;return c;}
const blank=()=>new Proxy({},{get(t,k){if(k in t)return t[k];if(k==='measureText')return s=>({width:String(s).length*7});
if(k==='createLinearGradient'||k==='createRadialGradient'||k==='createPattern')return ()=>({addColorStop(){}});
if(k==='getImageData')return ()=>({data:new Uint8ClampedArray(4)});if(k==='canvas')return null;return ()=>{};},set(t,k,v){t[k]=v;return true;}});
const asked=[];
HTMLCanvasElement.prototype.getContext=function(type){asked.push(type);if(type!=='2d')return null;return this.__ctx||(this.__ctx=rec(blank(),false));};
HTMLCanvasElement.prototype.__cid=function(){const q=this.__ctx&&this.__ctx.__Q;return q?'cv:'+q.h.toString(36)+'.'+q.n:'cv:?';};
rec(CTX0,true);
// A picture drawn in a 2D frame without a canvas of its own would simply not show.
let lost=0;const blit0=blit;blit=function(e,...a){if(!GLS.frame&&!e.cv)lost++;return blit0(e,...a);};
// One frame's calls on the map's canvas, from a known state of the context.
function frame(t){const Q=CTX0.__Q;Q.log.length=0;Q.h=2166136261;Q.n=0;Object.assign(CTX0,DEF);draw(t);return Q.log.slice();}
function inv(){let dup=0,bad=0;const seen=new Set();
for(const e of SPRC.values()){if(!e.cv){bad++;continue;}if(seen.has(e.cv))dup++;seen.add(e.cv);if(e.cv.width!==e.pw||e.cv.height!==e.ph)bad++;}
return {webgl:asked.filter(x=>x!=='2d').length,sprs:SPRS.size,glsFrame:GLS.frame,ctx0:ctx===CTX0,glShown:!document.getElementById('mapgl').hidden,
pad:!!GLS_PAD.cv,shared:dup,badCanvas:bad,lost};}
// Without the cache: every picture is painted again for every call, as if nothing were kept, even within a frame.
let nocache=false;const none={get(){},set(){},has:()=>false,size:0},sprMap0=sprMap;sprMap=function(){const m=sprMap0();return nocache?none:m;};
/* The same state drawn twice: with the pictures kept from every state before (kept), then painting every picture
again (fresh). The land picture is settled first, so both frames find it as it is. */
function pair(t){__T+=1000;if(S)worldLayer(cam.z);lost=0;
const kept=frame(t),had=SPRC.size;nocache=true;let fresh;try{fresh=frame(t);}finally{nocache=false;}
let d=-1;for(let i=0,n=Math.max(kept.length,fresh.length);i<n;i++)if(kept[i]!==fresh[i]){d=i;break;}
return {calls:fresh.length,had,diff:d<0?null:{at:d,kept:kept.slice(Math.max(0,d-2),d+2),fresh:fresh.slice(Math.max(0,d-2),d+2)},...inv()};}
// How main's 2D map worked out a tube's look, frame by frame (its drawFrame() before this change), word for word.
function ref(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);
const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)));
return {w,dash:cut?[8,8]:vx?[2,7]:bld?[10,8]:idle?[4,6]:[],col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),
pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0,cut,bld,dark,vx,cap,load,up:up&&up.map(x=>x.id)};}
// The kept looks (mapLinks) against groups, geometry and looks worked out again now, the way main did.
function looks(){if(!S||!R)return [];const ML=mapLinks(S.day),PI=pairIdx(),LG=linkGroups(),bad=[];
if(JSON.stringify(ML.LG.map(g=>g.map(l=>l.id)))!==JSON.stringify(LG.map(g=>g.map(l=>l.id))))return ['the tubes are not grouped as now'];
LG.forEach((g,i)=>{const gm=linkGeom(g[0],PI.get(edgeKey(g[0])));if(JSON.stringify(gm.pts)!==JSON.stringify(ML.GM[i].pts))bad.push('geometry of '+g[0].id);
const n=ML.looks[i],o=JSON.stringify(ref(g,S.day)),m=JSON.stringify({w:n.w0,dash:LDASH[n.dash],col:n.col,pk:n.pk,cut:n.cut,bld:n.bld,dark:n.dark,vx:n.vx,cap:n.cap,load:n.load,up:n.up&&n.up.map(x=>x.id)});
if(o!==m)bad.push(g[0].id+': main '+o+' kept '+m);});
return bad.slice(0,3);}
/* A view of the map: the camera on a city at a zoom, maybe a city or a tube selected, maybe a city under the
pointer, at clock t. u: numbers in [0,1) from the test's own seeded generator. */
function view(u){if(!S)return null;const pops=Object.keys(S.pops),at=pops.length&&u[0]<.7?pops[Math.floor(u[1]*pops.length)]:CITIES[Math.floor(u[1]*CITIES.length)].id,C=CITY[at];
cam.x=C.x+(u[2]-.5)*80;cam.y=C.y+(u[3]-.5)*60;cam.z=[.45,.7,1,1.6,3.2][Math.floor(u[4]*5)];
UI.sel=u[5]<.35?null:u[5]<.6?{type:'city',id:at}:S.links.length?{type:'link',id:S.links[Math.floor(u[6]*S.links.length)].id}:null;
UI.hover=u[7]<.3?at:null;return Math.floor(u[8]*20000);}
function check(u){const keep={x:cam.x,y:cam.y,z:cam.z,sel:UI.sel,hov:UI.hover};
try{const t=view(u);if(t===null)return null;const r=pair(t);r.looks=looks();r.view={at:UI.sel,z:cam.z,t};return r;}
finally{cam.x=keep.x;cam.y=keep.y;cam.z=keep.z;UI.sel=keep.sel;UI.hover=keep.hov;}}
return {frame,pair,inv,looks,check,view,asked};})();0`;
// What a check returned, as the problems it shows (none: an empty list).
function problems(r, where) {
if (!r) return [];
const out = [];
if (r.diff) out.push(`${where}: a kept picture differs from a fresh one at call ${r.diff.at}\n kept: ${r.diff.kept.join('\n ')}\n fresh: ${r.diff.fresh.join('\n ')}`);
for (const l of r.looks || []) out.push(`${where}: ${l}`);
if (r.webgl) out.push(`${where}: WebGL asked for ${r.webgl} times`);
if (r.lost) out.push(`${where}: ${r.lost} pictures drawn without a canvas`);
if (r.shared || r.badCanvas) out.push(`${where}: ${r.shared} pictures share a canvas, ${r.badCanvas} have none or one of the wrong size`);
if (r.pad) out.push(`${where}: the card's shared canvas was made`);
if (r.sprs || r.glsFrame || !r.ctx0 || r.glShown) out.push(`${where}: card state leaked into 2D ${JSON.stringify({ sprs: r.sprs, glsFrame: r.glsFrame, ctx0: r.ctx0, glShown: r.glShown })}`);
return out;
}
// A card that records what it is asked (jsdom has no WebGL), as in tests/webgl-zoom-sprites.test.js.
const GLSTUB = `window.__GLSTUB=(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
return (...a)=>{calls.push(k);return {};};}});
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
const fx=document.createElement('canvas').getContext('2d');
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx,line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})();0`;
function open() {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);`);
h.ev(KIT);
return h;
}
test('the 2D map draws the same frame from kept pictures as from fresh ones, whatever happens to a POP', () => {
const { ev, errors } = open();
const found = [];
assert.ok(ev('CW>300&&CH>300'), 'the map has a size');
// One city goes through every state its picture can show. After each change the map is looked at from the same
// views (every zoom, plain, under the pointer, selected), so a picture kept from an earlier state is found under its
// key whenever the key leaves out what changed.
const STEPS = [
'0',
'S.pops[S.home].down=S.day+3',
'S.pops[S.home].down=0;S.pops[S.home].routers=2',
'S.pops[S.home].gen=1',
'S.pops[S.home].rgen=1',
'S.pops[S.home].site2=S.pops[S.home].site2||{}',
'S.pops[S.home].ringcut=S.day+2',
"S.inc.push({id:'t-site',type:'site',ref:S.home,site:'b',until:S.day+5})",
'R.ddosHot=Object.assign({},R.ddosHot,{[S.home]:1})',
'UI.hotMap={[S.home]:{r:1,t:1,ix:1}}',
"S.myIx[S.home]=S.myIx[S.home]||{name:'Test-IX',members:[],next:S.day+4}",
'S.pops[S.home].routers=3;S.pops[S.home].rgen=0;S.pops[S.home].gen=0',
'delete R.ddosHot[S.home];UI.hotMap=null;S.pops[S.home].ringcut=0',
'S.pops[S.home].down=S.day+1',
// A city without a POP next to it: an incident there, then an exchange.
"S.inc.push({id:'t-x',type:'cut',ref:__OTHER,until:S.day+3})",
"S.myIx[__OTHER]={name:'Other-IX',members:[],next:S.day+4}",
];
// The other city: the nearest one without a POP.
ev("window.__OTHER=CITIES.filter(c=>!S.pops[c.id]&&!c.off).sort((a,b)=>Math.hypot(a.x-CITY[S.home].x,a.y-CITY[S.home].y)-Math.hypot(b.x-CITY[S.home].x,b.y-CITY[S.home].y))[0].id;0");
let checks = 0;
// u (see view()): centred on the home POP or on the other city, at zoom index z; nothing selected, the city under
// the pointer, or selected.
const VIEWS = [];
for (const city of ['pop', 'other']) for (let z = 0; z < 5; z++) for (const [sel, hov] of [[0.1, 0.9], [0.1, 0.1], [0.5, 0.9]]) VIEWS.push({ city, u: [city === 'pop' ? 0 : 0.9, 0, 0.5, 0.5, z / 5 + 0.01, sel, 0, hov, (z + 1) / 7] });
for (const step of STEPS) {
ev(step);
// Each change is looked at from the city it touches (both at the start).
const on = step === '0' ? null : step.includes('__OTHER') ? 'other' : 'pop';
VIEWS.forEach(({ city, u }, v) => {
if (on && city !== on) return;
const at = city === 'pop' ? 'Object.keys(S.pops).indexOf(S.home)/Object.keys(S.pops).length' : 'CITIES.findIndex(c=>c.id===__OTHER)/CITIES.length';
ev(`window.__U=${JSON.stringify(u)};__U[1]=${at}+1e-9;0`);
found.push(...problems(JSON.parse(ev('JSON.stringify(__M2D.check(__U))')), `after "${step}", view ${v} (${city})`));
checks++;
});
}
assert.ok(checks >= 250);
assert.deepEqual(found.slice(0, 5), []);
assert.deepEqual(errors, []);
});
test('the 2D map draws the same from kept pictures as from fresh ones, and tubes as main did, over random views of the big network', () => {
const { ev, errors } = open();
const r = rng(99), found = [];
for (let i = 0; i < 60; i++) {
// Now and then a day passes (failures and events on), so cuts, builds, floods and offers come and go.
if (i % 6 === 5) ev('S.nextFail=S.day;S.nextEvent=S.day;dayTick();compute();');
const u = Array.from({ length: 9 }, () => r());
found.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `view ${i} (day ${ev('S.day')})`));
}
assert.deepEqual(found.slice(0, 5), []);
assert.deepEqual(errors, []);
});
test('in seeded random games, after every move and day, the 2D map draws the same from kept pictures and tubes as main did', () => {
const file = path.join(os.tmpdir(), `tubes-map2d-${process.pid}.html`);
fs.writeFileSync(file, page.assemble().html);
try {
// A normal game, a sandbox, a scenario and a puzzle (the seeds of tests/route-fuzz.test.js). The big network is the
// test above: a whole game of it, routed again after every move on two pages, takes a minute.
for (const seed of [20, 23, 27, 26]) {
// Two pages of this checkout play the game in lockstep (scripts/lib/route-fuzz.js): drawing the map on both, between
// moves, must not make them part (the 2D map must not change the game).
const P = { base: openPage(file, 'a'), head: openPage(file, 'b') };
for (const p of [P.base, P.head]) p.ev(`window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);${KIT}`);
const r = rng(seed * 7919), found = [];
let checks = 0;
const g = playGame(P, seed, { moves: 40, maxDays: 4, onMove: () => {
const u = Array.from({ length: 9 }, () => r());
for (const p of [P.base, P.head]) {
const out = JSON.parse(p.ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`));
if (out) checks++;
found.push(...problems(out, `seed ${seed}, page ${p.label}`));
}
} });
assert.equal(g.div, null, `seed ${seed}: the two pages parted: ${JSON.stringify(g.div && { where: g.div.where, last: g.div.last })}`);
assert.ok(checks >= 20, `seed ${seed}: the map was checked (${checks})`);
assert.deepEqual(found.slice(0, 5), [], `seed ${seed}`);
assert.deepEqual(g.errors, [], `seed ${seed}`);
}
} finally { fs.rmSync(file, { force: true }); }
});
test('a 2D map without WebGL2 never asks for it again, and its pictures each keep their own canvas', () => {
const h = load({ seed: 777 });
// Auto mode, in a browser where WebGL2 is not there.
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`);
h.ev(KIT);
h.ev('mapGl(true,false);draw(__T);');
const first = JSON.parse(h.ev('JSON.stringify({asked:__M2D.asked.filter(x=>x!=="2d").length,gl:!!GLX.gl,glOn:glOn()})'));
assert.equal(first.gl, false);
assert.equal(first.glOn, false, 'auto mode draws in 2D');
for (let i = 0; i < 20; i++) h.ev(`cam.z=${0.5 + i * 0.15};__T+=16;draw(__T);`);
const inv = JSON.parse(h.ev('JSON.stringify(__M2D.inv())'));
assert.ok(inv.webgl <= first.asked, `WebGL was asked for again (${inv.webgl} after ${first.asked})`);
assert.deepEqual(problems({ ...inv, webgl: 0 }, 'zoom'), []);
assert.ok(h.ev('SPRC.size') > 50, 'the pictures are kept');
assert.deepEqual(h.errors, []);
});
test('the 2D map after the card is given up, or switched off, draws as a 2D map that never had one', () => {
const { ev, errors } = open();
// A card (a recording stand-in) draws a few frames and fills its own pictures.
ev(GLSTUB);
const views = (tag) => {
const out = [];
for (let v = 0; v < 8; v++) {
const u = [0.2, v / 8, 0.5, 0.5, (v % 5) / 5 + 0.01, v / 8, 0.3, v % 2 ? 0.1 : 0.9, v / 8];
out.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `${tag}, view ${v}`));
}
return out;
};
// Switched off in the settings, with the card's pictures still kept.
for (let i = 0; i < 6; i++) ev(`cam.z=${0.5 + i * 0.4};__T+=16;draw(__T);`);
assert.ok(ev('SPRS.size') > 20, 'the card painted its pictures');
ev('mapGl(false)');
// pad and sprs: the card's own, left from its frames; what matters is that the 2D frames never use them.
const off = views('switched off').filter((p) => !/card's shared canvas|card state leaked/.test(p) || /ctx0":false|glShown":true|glsFrame":true/.test(p));
assert.deepEqual(off.slice(0, 5), []);
// Back on, then the card fails: the session's map stays 2D.
ev('mapGl(true);__T+=16;draw(__T);glKill(new Error("test"));');
assert.equal(ev('SPRS.size'), 0, 'the card’s pictures are forgotten');
const dead = views('given up').filter((p) => !/card's shared canvas/.test(p));
assert.deepEqual(dead.slice(0, 5), []);
assert.deepEqual(errors, []);
});
test('the 2D map paints its pictures again for a new pixel density', () => {
const { ev, errors } = open();
ev('__T+=16;draw(__T);');
assert.ok(ev('SPRC.size') > 20);
ev('DPR=2;__T+=16;draw(__T);');
const bad = JSON.parse(ev('JSON.stringify([...SPRC.values()].filter(e=>e.pw!==Math.ceil(e.w*2)||e.ph!==Math.ceil(e.h*2)).length)'));
assert.equal(bad, 0, 'every picture is at the new density');
const r = JSON.parse(ev('JSON.stringify(__M2D.check([0,0,0.5,0.5,0.5,0.1,0,0.9,0.3]))'));
assert.deepEqual(problems(r, 'at 2×'), []);
assert.deepEqual(errors, []);
});
test('money pop-ups on the 2D map fade out as before', () => {
const { ev, errors } = open();
const C = 'CITY[S.home]';
ev(`cam.x=${C}.x;cam.y=${C}.y;cam.z=1;__T+=16;FLOATS.push({x:${C}.x,y:${C}.y,text:'+$1,234',col:'#16A866',t:__T});`);
// At 0, 40% and 80% of its life: drawn at opacity 1-a².
const alphas = [];
for (const a of [0, 0.4, 0.8]) {
const log = JSON.parse(ev(`JSON.stringify(__M2D.frame(FLOATS[FLOATS.length-1].t+${a * 1600}))`));
const last = log.filter((s) => s.startsWith('drawImage(')).pop();
alphas.push(+last.split(' ')[1]);
}
assert.deepEqual(alphas, [1, 0.84, 0.36]);
ev(`__M2D.frame(FLOATS[FLOATS.length-1].t+1700)`);
assert.equal(ev('FLOATS.length'), 0, 'gone after its life');
// The same text in two colours at once: two pictures, each in its own colour.
ev(`FLOATS.push({x:${C}.x,y:${C}.y,text:'+$500',col:'#16A866',t:5000},{x:${C}.x+40,y:${C}.y,text:'+$500',col:'#FF4D5E',t:5000});`);
const r = JSON.parse(ev('JSON.stringify(__M2D.pair(5400))'));
assert.deepEqual(problems(r, 'two pop-ups'), []);
assert.deepEqual(errors, []);
});
test('every picture starts with the pen the map had when it drew them itself: round line ends and corners, centred text', () => {
const { ev, errors } = open();
// Drawn straight on the map, main's dashed rings, cones and "zzz" took the state the tubes and labels left there.
let n = 0;
const pen = (spoil) => JSON.parse(ev(`(()=>{let o;spriteEntry('t-pen|${n++}',10,10,5,5,g=>{o={cap:g.lineCap,join:g.lineJoin,align:g.textAlign,base:g.textBaseline};
${spoil ? "g.lineCap='butt';g.lineJoin='miter';g.textAlign='start';g.textBaseline='alphabetic';" : ''}});return JSON.stringify(o);})()`));
const want = { cap: 'round', join: 'round', align: 'center', base: 'middle' };
assert.deepEqual(pen(true), want, 'a 2D picture');
assert.deepEqual(pen(false), want, 'the next 2D picture');
// On the card one canvas is reused for every picture: each starts from that pen again, whatever the last one did.
ev(GLSTUB);
ev('GLS.frame=true;');
try {
assert.deepEqual(pen(true), want, 'a picture on the card');
assert.deepEqual(pen(false), want, 'the next picture on the card, on the same canvas');
assert.ok(ev('!!GLS_PAD.cv&&SPRS.size>=2'), 'the card’s pictures went through its shared canvas');
} finally { ev('GLS.frame=false;'); }
assert.deepEqual(errors, []);
});

View file

@ -1010,7 +1010,8 @@ test('Down Under: routers upside down, BrisVegas, Next-Door-DC and everything tr
assert.equal(ev("S.log.filter(e=>/Router installed/.test(e.t)).length"), 2, 'one note per Australian POP');
ev("ACT.buildPop({city:'lon'})");
assert.equal(ev("S.log.filter(e=>/Router installed/.test(e.t)).length"), 2, 'London routers stay the right way up');
const turns = c => ev(`(()=>{let n=0;const r=ctx.rotate;ctx.rotate=a=>{if(Math.abs(a-Math.PI)<1e-9)n++;return r.call(ctx,a);};try{const C=CITY['${c}'];drawCity(C,100,100,1,0);}finally{ctx.rotate=r;}return n;})()`);
// The picture of a city is painted once per state (citySprite), so the turn is checked on its static part.
const turns = c => ev(`(()=>{let n=0;const r=ctx.rotate;ctx.rotate=a=>{if(Math.abs(a-Math.PI)<1e-9)n++;return r.call(ctx,a);};try{const C=CITY['${c}'],t=cTier(C.id);cityStatic(C,S.pops[C.id],t,1,1,{sel:0,dd:0,gl:-1},{down:false,feed:false,sel:false,inc:false,ixDraw:false,ixHot:false});}finally{ctx.rotate=r;}return n;})()`);
assert.equal(turns('syd'), 1, 'Sydney: upside down');
assert.equal(turns('lon'), 0, 'London: the right way up');
// BrisVegas, Megapork's home town, and the data centres

View file

@ -109,9 +109,9 @@ test('the map keeps fiber capacities for one frame only, and skips links above o
const cap = ev("dfCap(S.links.find(l=>l.id==='dfT'))");
ev("S.links.find(l=>l.id==='dfT').ch.push('zr4');draw(0)");
assert.equal(ev("dfCap(S.links.find(l=>l.id==='dfT'))"), 2 * cap, 'a new channel counts on the next frame');
ev("ctx.fillText=()=>{throw new Error('boom')}");
ev("window.__ds=drawShips;drawShips=()=>{throw new Error('boom')}");
assert.throws(() => ev('draw(0)'));
ev('delete ctx.fillText');
ev('drawShips=window.__ds');
assert.equal(ev('DFC'), null, 'not even after a frame that failed');
// The whole network far above the screen: the links cost nothing, as if there were none.
const calls = (body) => ev(`(()=>{cam.x=CITY.fra.x;cam.y=CITY.fra.y+${'2000'};cam.z=2;${body};const n=ctx.calls.n;draw(0);return ctx.calls.n-n;})()`);
@ -125,7 +125,7 @@ test('a map with more than MAP_BUSY lines on screen leaves out link labels and f
const { ev, errors } = load();
bigNet(ev);
// Spy on the two things that go: the dotted line on lit fiber and the link labels.
ev("window.__dots=0;window.__labels=[];ctx.setLineDash=d=>{if(d.length===2&&d[0]===1&&d[1]===6)__dots++;};ctx.fillText=t=>{if(/ DF$/.test(t))__labels.push(t);}");
ev("window.__dots=0;window.__labels=[];ctx.setLineDash=d=>{if(d.length===2&&d[0]===1&&d[1]===6)__dots++;};const __pill=pill;pill=(t,...a)=>{if(/ DF$/.test(t))__labels.push(t);return __pill(t,...a);}");
const frame = () => ev("__dots=0;__labels=[];draw(0);JSON.stringify([__dots,__labels.length])");
const view = "cam.x=(CITY.fra.x+CITY.lon.x)/2;cam.y=(CITY.fra.y+CITY.lon.y)/2;cam.z=1.6;";
const lines = () => ev("(()=>{const PI=pairIdx();return linesOnScreen(linkGroups().map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),visibleKs());})()");

120
tests/webgl-coast.test.js Normal file
View file

@ -0,0 +1,120 @@
// The land on the card per zoom level (src/game/96-map/57-webgl-background.js): zoomed out, the coastlines are
// simplified so that no point moves more than COAST_TOL px on screen at that level, which takes most of the card's
// vertices away. The coastlines themselves (COAST, onLand()) and the 2D map stay as they were.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h;
}
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
return (...a)=>{calls.push([k,...a]);return {};};}});
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
test('a simplified coastline never strays more than the tolerance from the full one', () => {
const { ev, errors } = open();
const r = JSON.parse(ev(`(()=>{const out=[];let worst=0,rings=0,kept=0,all=0;
for(const lv of [-2,-1,0,1,3]){const tol=COAST_TOL/Math.pow(2,lv);
COAST.forEach((ring,ri)=>{if(ring.length<3)return;const P=coastPts(ri),Q=coastSimplify(P,tol),at=new Map(P.map((p,i)=>[p,i]));rings++;kept+=Q.length;all+=P.length;
if(Q[0]!==P[0]||Q[Q.length-1]!==P[P.length-1])out.push('ends '+ri);
for(let j=0;j+1<Q.length;j++){const a=at.get(Q[j]),b=at.get(Q[j+1]);if(!(b>a))out.push('order '+ri);
const 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;
for(let i=a+1;i<b;i++){let t=((P[i][0]-ax)*dx+(P[i][1]-ay)*dy)/L;t=Math.max(0,Math.min(1,t));const d=Math.hypot(ax+t*dx-P[i][0],ay+t*dy-P[i][1])/tol;if(d>worst)worst=d;}}});}
return JSON.stringify({bad:out.slice(0,5),worst,rings,share:kept/all});})()`));
assert.deepEqual(r.bad, [], 'each ring keeps its ends and its order');
assert.ok(r.worst <= 1 + 1e-9, `no point further than the tolerance (worst ${r.worst.toFixed(3)} of it)`);
assert.ok(r.rings > 50);
assert.ok(r.share < 0.6, `points are left out (${(r.share * 100).toFixed(0)} % kept)`);
assert.deepEqual(errors, []);
});
test('zoomed out the land has a few times fewer segments, and the closer the zoom the more it keeps', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{const full=glLandGeo(GLX.gl,false),n=lv=>glLandGeo(GLX.gl,false,lv).nSeg;
return JSON.stringify({full:full.nSeg,fullFan:full.nFan,l_1:n(-1),l0:n(0),l1:n(1),l3:n(3),far:glLandGeo(GLX.gl,true,-1).nSeg,once:glLandGeo(GLX.gl,false,0)===glLandGeo(GLX.gl,false,0),
fan:glLandGeo(GLX.gl,false,-1).nFan});})()`));
assert.ok(r.l_1 * 3 < r.full, `zoom 0.5–1: ${r.l_1} segments, ${r.full} in full`);
assert.ok(r.l_1 < r.l0 && r.l0 < r.l1 && r.l1 <= r.l3 && r.l3 <= r.full, JSON.stringify(r));
assert.ok(r.far < r.l_1, 'the far view still leaves out the islets');
assert.ok(r.fan * 3 < r.fullFan, 'the fill’s fan shrinks as much');
assert.equal(r.once, true, 'each level is built once');
assert.deepEqual(errors, []);
});
test('the zoom level takes the finer level at once and keeps it a little while zooming out', () => {
const { ev, errors } = open();
const lv = JSON.parse(ev(`(()=>{delete GLX.coastLv;return JSON.stringify([1.5,2.1,1.95,1.85,1.8,0.9,0.95,0.4].map(coastLevel));})()`));
assert.deepEqual(lv, [0, 1, 1, 1, 0, -1, -1, -2]);
assert.deepEqual(errors, []);
});
test('each frame on the card fills the land from its zoom level’s geometry; the coastlines and the 2D map stay as they were', () => {
const { ev, errors } = open();
const coast = ev('JSON.stringify(COAST)');
ev(STUB);
const fans = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;delete GLX.coastLv;const o=[];
for(const z of [0.6,1.4,3.2]){cam.z=z;GLX.gl.calls.length=0;draw(1000);const want=glLandGeo(GLX.gl,lodFar(),coastLevel(z)).nFan;
o.push(GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').every(c=>c[3]===want));}return JSON.stringify(o);})()`));
assert.deepEqual(fans, [true, true, true]);
assert.equal(ev('JSON.stringify(COAST)'), coast, 'COAST is never changed (onLand() reads it)');
let built = 0;
ev(`mapGl(false);window.__lg=glLandGeo;glLandGeo=function(){__built++;return __lg.apply(this,arguments);};window.__built=0;cam.z=0.6;draw(1016);cam.z=3.2;draw(1032);`);
built = ev('__built');
assert.equal(built, 0, 'the 2D map does not use it');
assert.deepEqual(errors, []);
});
/* Where two coastlines overlap, the land stays land, as the 2D map fills each coast on its own (nonzero). Timor is drawn
twice (COAST[58] and the finer COAST[154], with Dili): the card counted only odd or even coverings over all the coasts,
so the two cancelled out and most of the island was sea, its shadow too. The fan now winds every coast the same way
and the stencil counts windings. w(x,y) is the winding the card counts at a point: the fan's triangles that cover it,
+1 or -1 by the way they turn. */
const WIND = `window.__wind=(fan,x,y)=>{let w=0;const s=(ax,ay,bx,by)=>(bx-ax)*(y-ay)-(by-ay)*(x-ax);
for(let i=0;i<fan.length;i+=6){const [ax,ay,bx,by,cx,cy]=fan.slice(i,i+6),d1=s(ax,ay,bx,by),d2=s(bx,by,cx,cy),d3=s(cx,cy,ax,ay);
if(d1>0&&d2>0&&d3>0)w++;else if(d1<0&&d2<0&&d3<0)w--;}return w;};`;
test('two overlapping coastlines leave their overlap filled (Timor), at every zoom', () => {
const { ev, errors } = open();
ev(WIND);
const r = JSON.parse(ev(`(()=>{const pt=[1692,600],o={both:[58,154].map(i=>inPoly(...pt,coastPts(i)))};
for(const lv of [undefined,-1,0,1,2,3,4,5]){const tol=lv===undefined?0:COAST_TOL/Math.pow(2,lv),fan=[];
COAST.forEach((ring,ri)=>{if(ring.length<3)return;const P=coastSimplify(coastPts(ri),tol);if(P.length>=4)coastFan(P,fan);});
o['lv'+lv]=__wind(fan,...pt);}
return JSON.stringify(o);})()`));
assert.deepEqual(r.both, [true, true], 'the point is inside both of Timor’s coastlines');
for (const lv of [undefined, -1, 0, 1, 2, 3, 4, 5]) assert.equal(r['lv' + lv], 2, `level ${lv}: counted twice, so land (an odd/even count gave 0, sea)`);
assert.deepEqual(errors, []);
});
test('every coastline counts +1 inside, whichever way it was drawn', () => {
const { ev, errors } = open();
ev(WIND);
const r = JSON.parse(ev(`(()=>{const sq=(x,y,s,cw)=>{const p=[[x,y],[x+s,y],[x+s,y+s],[x,y+s]];return cw?p.reverse():p;};
const fan=[];coastFan(sq(0,0,10,false),fan);coastFan(sq(5,5,10,true),fan);
return JSON.stringify({a:__wind(fan,2,1),both:__wind(fan,8,6),b:__wind(fan,12,13),out:__wind(fan,20,20)});})()`));
assert.deepEqual(r, { a: 1, both: 2, b: 1, out: 0 }, 'one square turned each way: the overlap is 2, not 0');
assert.deepEqual(errors, []);
});
test('the card fills the land where the winding count is not zero, and leaves the stencil at zero', () => {
const { ev, errors } = open();
ev(STUB);
const c = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;GLX.gl.calls.length=0;draw(1000);
return JSON.stringify(GLX.gl.calls.filter(c=>/^stencil/.test(c[0])).map(c=>c.join(' ')));})()`));
assert.ok(c.includes('stencilOpSeparate FRONT KEEP KEEP INCR_WRAP') && c.includes('stencilOpSeparate BACK KEEP KEEP DECR_WRAP'), 'counts windings, +1 one way and -1 the other');
assert.ok(c.includes('stencilFunc NOTEQUAL 0 255'), 'fills where the count is not zero, on all 8 bits');
assert.ok(c.includes('stencilOp ZERO ZERO ZERO'), 'and sets it back to zero');
assert.ok(!c.some(s => /INVERT/.test(s)), 'no odd/even count left');
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,163 @@
// A WebGL context can be lost and given back: a driver reset, or on a phone sometimes just leaving the app. The map
// gave the card up for the session at the first loss, so a phone that went to another app came back to the slower 2D
// map until the page was reloaded. It now draws in 2D while the context is away, and builds everything on the card
// again when the browser gives it back (webglcontextrestored), up to GL_LOSSES times a session. Settings › Map drawing
// › Always 2D lets the context go the same way (WEBGL_lose_context), and Auto asks for it back, so a map drawn in 2D
// does not hold 64 MB of atlas on the card. Switching for the GPU benchmark (mapGl(on,false)) keeps the context.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
/* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's. It can be lost by the "browser"
(__browserLose(), __browserRestore()) or through WEBGL_lose_context (counted in __LOST and __RESTORE; without it when
window.__noExt). Events come at once, which the real ones do not: the code must not rely on either order. Textures
made are counted (__TEX), so a rebuild shows. */
const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__LOST=0;window.__RESTORE=0;window.__TEX=0;
let lost=false;const c=document.getElementById('mapgl'),fire=t=>c.dispatchEvent(new window.Event(t,{cancelable:true}));
window.__browserLose=()=>{lost=true;fire('webglcontextlost');};window.__browserRestore=()=>{lost=false;fire('webglcontextrestored');};
const ext={loseContext:()=>{__LOST++;if(lost)return;lost=true;fire('webglcontextlost');},restoreContext:()=>{__RESTORE++;if(!lost)return;lost=false;fire('webglcontextrestored');}};
const gl=new Proxy({},{get(t,k){
if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
if(k==='getExtension')return (n)=>n==='WEBGL_lose_context'?(window.__noExt?null:ext):{UNMASKED_RENDERER_WEBGL:'REN'};
if(k==='isContextLost')return ()=>lost;
if(k==='createTexture')return ()=>{__TEX++;return {};};
if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096;
if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
if(k==='getError')return ()=>0;
return ()=>({});}});
c.getContext=(t)=>t==='webgl2'?gl:null;})()`;
function open(storage) {
const h = load({ seed: 777, storage });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{};
const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`);
h.ev(GL);
return h;
}
const frame = (ev) => ev('__T+=16;draw(__T);JSON.stringify({gl:!!GLX.gl&&GLX.shown,dead:GLX.dead,lost:GLX.lost,sprs:SPRS.size,sprc:SPRC.size,err:!!UI.tickErr})');
test('a context the browser loses draws the map in 2D, then on the card again once it is back', () => {
const { ev, errors } = open();
assert.equal(JSON.parse(frame(ev)).gl, true, 'drawn on the card');
ev('UI.tickErr=false;__browserLose();');
let f = JSON.parse(frame(ev));
assert.deepEqual([f.gl, f.dead, f.lost, f.err], [false, false, true, false], 'in 2D while it is away, without a glitch');
assert.equal(f.sprs, 0, 'the card’s pictures are forgotten (its atlas went with the context)');
assert.ok(f.sprc > 0, 'the 2D map paints its own');
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
ev('window.__t0=__TEX;window.__built=0;const gb=glBuild;glBuild=function(){__built++;return gb.apply(this,arguments);};__browserRestore();');
f = JSON.parse(frame(ev));
assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'back on the card');
assert.ok(ev('__TEX-__t0') >= 2, 'the atlas and the tubes’ points are made again');
assert.equal(ev('__built'), 1, 'the tubes are built again');
assert.ok(f.sprs > 0, 'the pictures are sent again');
assert.equal(ev('GLX.losses'), 1);
assert.deepEqual(errors, []);
});
test(`a card lost more than GL_LOSSES times is given up for the session`, () => {
const { ev, errors } = open();
frame(ev);
const n = ev('GL_LOSSES');
for (let i = 0; i < n; i++) { ev('__browserLose()'); frame(ev); ev('__browserRestore()'); assert.equal(JSON.parse(frame(ev)).gl, true, `back after loss ${i + 1}`); }
ev('__browserLose()');
let f = JSON.parse(frame(ev));
assert.equal(f.dead, true, 'given up');
assert.match(ev('GLX.why'), /lost 3 times/);
assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did');
// A late restore does not bring it back.
ev('__browserRestore()');
f = JSON.parse(frame(ev));
assert.deepEqual([f.gl, f.dead], [false, true]);
assert.deepEqual(errors, []);
});
test('Always 2D lets the context go, Auto takes it back, and neither counts as a loss', () => {
const { ev, errors } = open();
frame(ev);
ev("ACT.mapSet({v:'2d'})");
assert.equal(ev('__LOST'), 1, 'the context is let go');
assert.equal(ev('GLX.gl===null&&GLS.tex===null&&SPRS.size===0'), true, 'nothing on the card is held');
let f = JSON.parse(frame(ev));
assert.deepEqual([f.gl, f.dead], [false, false]);
assert.equal(ev('localStorage.getItem("sot-map")'), '2d');
ev("ACT.mapSet({v:'auto'})");
assert.equal(ev('__RESTORE'), 1, 'asked back');
f = JSON.parse(frame(ev));
assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'on the card again');
assert.equal(ev('GLX.losses'), 0, 'the player’s choice is not a failure');
// Back and forth: still fine, still not counted.
for (let i = 0; i < 4; i++) { ev("ACT.mapSet({v:'2d'})"); frame(ev); ev("ACT.mapSet({v:'auto'})"); }
assert.equal(JSON.parse(frame(ev)).gl, true);
assert.equal(ev('GLX.losses'), 0);
assert.deepEqual(errors, []);
});
test('a context the browser gives back after the player chose Always 2D is let go again', () => {
const { ev, errors } = open();
frame(ev);
ev('__browserLose()');
ev("ACT.mapSet({v:'2d'})");
assert.equal(ev('__LOST'), 0, 'already lost: nothing to let go yet');
ev('__browserRestore()');
assert.equal(ev('__LOST'), 1, 'let go as soon as it is back');
assert.equal(JSON.parse(frame(ev)).gl, false);
ev("ACT.mapSet({v:'auto'})");
assert.equal(JSON.parse(frame(ev)).gl, true);
assert.deepEqual(errors, []);
});
test('the GPU benchmark switches maps without letting the context go', () => {
const { ev, errors } = open();
frame(ev);
ev('mapGl(false,false)');
assert.equal(JSON.parse(frame(ev)).gl, false);
ev('mapGl(true,false)');
assert.equal(JSON.parse(frame(ev)).gl, true);
assert.equal(ev('__LOST+__RESTORE'), 0);
assert.deepEqual(errors, []);
});
test('without WEBGL_lose_context, Always 2D keeps the context, as before', () => {
const { ev, errors } = open();
ev('window.__noExt=true');
frame(ev);
ev("ACT.mapSet({v:'2d'})");
assert.equal(JSON.parse(frame(ev)).gl, false);
assert.equal(ev('!!GLX.gl'), true, 'kept for later');
ev("ACT.mapSet({v:'auto'})");
assert.equal(JSON.parse(frame(ev)).gl, true);
assert.deepEqual(errors, []);
});
test('a game started with Always 2D never makes a context', () => {
const { ev, errors } = open({ 'sot-map': '2d' });
ev('window.__made=0;const gc=document.getElementById("mapgl").getContext;document.getElementById("mapgl").getContext=t=>{__made++;return gc(t);};');
frame(ev);
ev("ACT.settings({})");
assert.equal(ev('__made'), 0);
assert.deepEqual(errors, []);
});
// Settings said whether the card could draw the map by setting it up: opening them on the title screen or in a puzzle
// made the context and its 64 MB atlas for a map drawn in 2D. It now says what is known without asking the card.
test('opening Settings never makes a context, and still says when the card cannot', () => {
const { ev, errors } = open();
ev('window.WebGL2RenderingContext=function(){};window.__made=0;const c=document.getElementById("mapgl"),gc=c.getContext;c.getContext=t=>{__made++;return gc(t);};');
const note = () => ev("settingsHtml().includes(tr('settings.this_browser_cannot_so_the_map'))");
ev('const s=S;S=null;window.__S=s;');
assert.equal(note(), false, 'title screen: a card not tried yet counts as able');
ev('S=__S;');
assert.equal(note(), false);
assert.equal(ev('__made'), 0, 'no context made by Settings');
ev('glKill(new Error("no graphics card, only SwiftShader"))');
assert.equal(note(), true, 'a card given up: Settings says so');
ev('delete window.WebGL2RenderingContext;GLX.dead=false;');
assert.equal(note(), true, 'no WebGL2 in this browser: Settings says so');
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,89 @@
// A frame on the card makes little garbage (src/game/96-map/57-webgl-background.js, 59-gl-sprites.js, 80-cities.js):
// the keys of the pictures are kept per city and per label and built again only when the picture changes, and the
// waves and the clouds are written into arrays kept from frame to frame. What is drawn stays the same.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h;
}
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
return (...a)=>{calls.push([k,...a]);return {};};}});
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
// Counts the keys joined during one frame (Array#join with '|', as the picture keys are), but the ships' (a handful).
const JOINS = (body) => `(()=>{let n=0;const j=Array.prototype.join;Array.prototype.join=function(s){if(s==='|'&&this[0]!=='ship')n++;return j.apply(this,arguments);};
try{${body}}finally{Array.prototype.join=j;}return n;})()`;
for (const [view, z] of [['near', 1.4], ['far', 0.6]]) {
test(`an unchanged frame on the card joins no picture key again (${view} view)`, () => {
const { ev, errors } = open();
ev(STUB);
ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=${z};UI.sel=null;draw(1000);draw(1016);`);
const first = ev(JOINS(`SPRS.clear();CKEY.clear();PILLK.clear();FKEY.clear();QKEY.clear();draw(1032);`));
const again = ev(JOINS('draw(1048);'));
assert.ok(first > 20, `a first frame builds its keys (${first})`);
assert.equal(again, 0, 'the next one builds none');
assert.deepEqual(errors, []);
});
}
test('a city whose state changes gets a new picture, and its old one back after', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{const id=S.home,C=CITY[id],p=S.pops[id];cam.x=C.x;cam.y=C.y;cam.z=1.4;UI.sel=null;
const pic=()=>{draw(1000);return CKEY.get(id).k;};const a=pic();const was=p.down;p.down=S.day+3;const b=pic();p.down=was;const c=pic();
UI.sel={type:'city',id};const d=pic();UI.sel=null;
const before=CKEY.get(id).k,gen=p.gen;p.gen=!gen;const e=pic();p.gen=gen;
return JSON.stringify({a,b,c,d,e,before});})()`));
assert.notEqual(r.b, r.a, 'down: another picture');
assert.equal(r.c, r.a, 'back up: the same picture');
assert.notEqual(r.d, r.a, 'selected: another picture');
assert.notEqual(r.e, r.before, 'a generator: another picture');
assert.deepEqual(errors, []);
});
test('labels with the same text but another look are other pictures', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;const f='800 12px "Baloo 2", sans-serif';
pill('Lagos',f,50,19,9,'#FFFFFF','#1E2640','#1E2640',2,10,10,.5);pill('Lagos',f,50,19,9,'#FF4F9A','#FFFFFF','#1E2640',2,10,10,.5);pill('Lagos',f,50,19,9,'#FFFFFF','#1E2640','#1E2640',2,10,10,.5);
const n=GLS.n,L=PILLK.get('Lagos').length,u=new Set([0,1,2].map(i=>GLS.data[i*SPR_STRIDE+4]+','+GLS.data[i*SPR_STRIDE+5])).size;GLS.frame=false;GLS.n=0;ctx=CTX0;
return JSON.stringify({n,L,u});})()`));
assert.equal(r.n, 3);
assert.equal(r.L, 2, 'two looks kept for one text');
assert.equal(r.u, 2, 'two pictures in the atlas, the third label reuses the first');
assert.deepEqual(errors, []);
});
test('the waves and the clouds are what they were, written into arrays kept from frame to frame', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{const ks=[-1,0,1],now=12345,gl=GLX.gl;
glWaves(gl,now,ks);const wa=GLX.wa,ph0=now/900,want=[];let m=0,bad=0;
for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;for(const [x0,cx,cy,x1] of [[x-9+o,x-4.5+o,y-4,x+o],[x+o,x+4.5+o,y+4,x+9+o]]){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,o2=m*LINE_STRIDE;
if(wa[o2]!==Math.fround(px)||wa[o2+1]!==Math.fround(py)||wa[o2+2]!==Math.fround(qx)||wa[o2+3]!==Math.fround(qy))bad++;m++;px=qx;py=qy;}}}
glWaves(gl,now+16,ks);const sameW=GLX.wa===wa;
glClouds(gl,now,ks);const ca=GLX.ca,A=[];for(const k of ks)for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100+k*W,y=c.y;A.push(x,y,16*c.s,0, x+18*c.s,y-8*c.s,20*c.s,0, x+40*c.s,y,15*c.s,0);}
const sent=gl.calls.filter(c=>c[0]==='bufferData').pop()[2],cbad=A.filter((v,i)=>sent[i]!==Math.fround(v)).length;
glClouds(gl,now+16,ks);
return JSON.stringify({bad,m,sameW,cbad,clen:sent.length,alen:A.length,sameC:GLX.ca===ca});})()`));
assert.equal(r.bad, 0, `every wave segment where it was (${r.m} segments)`);
assert.equal(r.sameW, true);
assert.equal(r.clen, r.alen, 'one record per puff');
assert.equal(r.cbad, 0, 'every puff where it was');
assert.equal(r.sameC, true, 'the clouds’ array is kept');
assert.deepEqual(errors, []);
});

333
tests/webgl-map.test.js Normal file
View file

@ -0,0 +1,333 @@
// The WebGL map (src/game/96-map/56-webgl.js to 59-gl-sprites.js): jsdom has no WebGL, so these tests check what can be checked
// without a graphics card. A browser without WebGL2 keeps the 2D map; the instance data the card would draw says the
// same as the 2D map (points, colours, dashes, packets, painting order, selection); with a stand-in context the map
// sends its lines to the card and paints the rest on the overlay, and goes back to its own canvas afterwards.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h;
}
// A WebGL2 stand-in that records draws: enough for glBuild() and glFrame() to run.
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
return (...a)=>{calls.push([k,...a]);return {};};}});
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
test('without WebGL2 the map stays 2D, and asking for WebGL changes nothing', () => {
const { ev, errors } = open();
ev(`mapGl(true);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
assert.equal(ev('GLX.dead'), true, 'a context that cannot compile shaders is given up');
assert.equal(ev('glOn()'), false);
assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'the layer stays hidden');
assert.ok(ev('ctx===CTX0'), 'the map draws on its own canvas');
assert.ok(ev(`cv.getContext('2d').calls.n`) > 1000, 'the 2D map drew its lines');
assert.deepEqual(errors, []);
});
test('the instance data says what the 2D map draws: points, colours, dashes, packets and painting order', () => {
const { ev } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{const PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0]))));
const sel=LG[3][0].id,looks=LG.map(g=>linkLook(g,S.day)),{SEG,PK,PT}=glBuild(LG,GM,looks),H=glHalo(LG,GM,looks,sel);let si=0,ki=0,pi=0,hi=0,bad=[];const deps=[];
for(let gi=0;gi<LG.length;gi++){const gm=GM[gi],L=looks[gi],[r,g,b]=glColor(L.col),hot=LG[gi].some(x=>x.id===sel);
for(let j=0;j<gm.pts.length;j++){if(PT[pi*4]!==Math.fround(gm.pts[j][0])||PT[pi*4+2]!==Math.fround(gm.cum[j]))bad.push('pt '+gi);pi++;}
for(let j=0;j+1<gm.pts.length;j++){const o=si*12;
if(SEG[o]!==Math.fround(gm.pts[j][0])||SEG[o+3]!==Math.fround(gm.pts[j+1][1]))bad.push('seg '+gi);
if(SEG[o+6]!==L.dash||SEG[o+5]!==Math.fround(L.w0)||SEG[o+9]!==Math.fround(r)||SEG[o+11]!==Math.fround(b))bad.push('look '+gi);
if((SEG[o+7]&1)===1||((SEG[o+7]&2)===2)!==(L.df&&!L.bld&&!L.dark))bad.push('flags '+gi);
if(hot){const h=hi*12;for(let x=0;x<12;x++)if(H[h+x]!==(x===7?1:SEG[o+x]))bad.push('halo '+gi);hi++;}
if(j===0)deps.push(SEG[o+8]);si++;}
const n=!L.cut&&L.load>0.01?clamp(Math.round(2+L.u*10),2,12):0;for(let i=0;i<n;i++){if(PK[ki*8+3]!==n||PK[ki*8+4]!==i)bad.push('pk '+gi);ki++;}}
return JSON.stringify({bad:bad.slice(0,5),si,segs:SEG.length/12,ki,pks:PK.length/8,groups:LG.length,
order:deps.every((d,i)=>!i||d<deps[i-1]),inRange:deps.every(d=>d>0&&d<1),sel:hi>0&&hi===GLX.nHalo,moving:looks.filter(L=>!L.cut&&L.load>0.01).length});})()`));
assert.deepEqual(r.bad, []);
assert.equal(r.si, r.segs, 'one instance per segment');
assert.equal(r.ki, r.pks, 'one instance per packet');
assert.ok(r.groups > 50 && r.moving > 20, 'a big map with traffic');
assert.ok(r.order && r.inRange, 'later tubes are nearer, so they paint over earlier ones as in 2D');
assert.equal(r.sel, true, 'the selected tube, and only it, gets its halo: its own segments at its own depth');
});
test('with WebGL the lines go to the card, the rest to the overlay, and the map gets its canvas back', () => {
const { ev, errors } = open();
ev(`mapGl(false);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
const flat = ev(`cv.getContext('2d').calls.n`);
ev(STUB);
ev(`cv.getContext('2d').calls.n=0;document.getElementById('mapfx').getContext('2d').calls.n=0;draw(1000);`);
assert.equal(ev('glOn()'), true);
const main = ev(`cv.getContext('2d').calls.n`), over = ev(`document.getElementById('mapfx').getContext('2d').calls.n`);
assert.ok(main < flat / 2, `the map's own canvas only paints sea, land and cables (${main} calls, ${flat} in 2D)`);
assert.ok(over > 100, 'labels and cities go on the 2D overlay');
assert.ok(ev('ctx===CTX0'), 'draw() hands the 2D context back');
assert.equal(ev(`document.getElementById('mapgl').hidden`), false, 'the WebGL layer shows');
const draws = JSON.parse(ev(`JSON.stringify(GLX.gl.calls.filter(c=>c[0]==='drawArraysInstanced').map(c=>c[4]))`));
assert.ok(draws.includes(ev('GLX.nSeg')) && draws.includes(ev('GLX.nPk')), 'every segment and every packet in instanced draws');
// Nothing changed: the next frame reuses the buffers. A cut link changes routing, and the tubes are rebuilt.
// The tubes' own buffers (segments, packets, points) are what must not be sent again on an ordinary frame; the waves and clouds move every frame by design.
const uploads = () => ev(`GLX.gl.calls.filter(c=>c[0]==='bufferData'&&c[2]&&c[2].length===GLX.nSeg*12).length`);
const u0 = uploads(); ev('draw(1016)'); assert.equal(uploads(), u0, 'a frame alone uploads no tube data');
const id = ev(`(()=>{const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));l.cut=S.day+5;compute();draw(1032);return l.id;})()`);
assert.ok(uploads() > u0, 'a cut rebuilds the tubes');
assert.equal(ev(`linkLook(linkGroups().find(g=>g.some(x=>x.id===${JSON.stringify(id)})),S.day).dash`), 1, 'drawn dashed like a cut');
ev('mapGl(false);draw(1048)');
assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'switching back hides the layers');
assert.deepEqual(errors, []);
});
test('a label sits at the middle of its line whichever way the middle is found', () => {
const { ev } = open();
const d = ev(`(()=>{let m=0;const PI=pairIdx();for(const g of linkGroups()){const gm=linkGeom(g[0],PI.get(edgeKey(g[0]))),X=gm.pts.map(p=>(p[0]-cam.x)*cam.z+CW/2),Y=gm.pts.map(p=>(p[1]-cam.y)*cam.z+CH/2);
const a=polyAtXY(X,Y,gm.cum,.5),w=polyAt(gm.pts,gm.cum,.5),b=[(w[0]-cam.x)*cam.z+CW/2,(w[1]-cam.y)*cam.z+CH/2];m=Math.max(m,Math.hypot(a[0]-b[0],a[1]-b[1]));}return m;})()`);
assert.ok(d < 1e-6, `midpoints agree (${d})`);
});
test('the labels and cities stay on the 2D overlay; the card draws the background and the tubes', () => {
const { ev, errors } = open();
ev(STUB);
ev(`cv.getContext('2d').calls.n=0;document.getElementById('mapfx').getContext('2d').calls.n=0;draw(1000);`);
assert.ok(ev(`document.getElementById('mapfx').getContext('2d').calls.n`) > 100, 'labels and cities are painted on the 2D overlay');
assert.ok(ev(`GLX.gl.calls.filter(c=>c[0]==='drawArraysInstanced').length`) > 0, 'the tubes are still drawn on the card');
assert.equal(ev(`document.getElementById('mapfx').hidden`), false, 'the 2D overlay shows');
assert.deepEqual(errors, []);
});
test('the land is geometry on the card: one fan per coastline, its outlines, its hills; the far view leaves out islets', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{const all=glLandGeo(GLX.gl,false),far=glLandGeo(GLX.gl,true);
const pts=COAST.reduce((a,p)=>a+p.length,0);
GLX.gl.calls.length=0;cam.z=1.4;draw(1000);
const fans=GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').map(c=>c[3]);
const lv=glLandGeo(GLX.gl,false,coastLevel(1.4));
return JSON.stringify({nFan:all.nFan,nSeg:all.nSeg,farSeg:far.nSeg,pts,hills:all.nHill,again:glLandGeo(GLX.gl,false)===all,fans,lvFan:lv.nFan,
wl:GLX.gl.calls.some(c=>c[0]==='texImage2D'&&c[6]===WL.cv)});})()`));
assert.equal(r.nFan % 3, 0, 'whole triangles');
assert.equal(r.nSeg, r.pts * 4, 'each curve of the coast in four segments');
assert.ok(r.farSeg < r.nSeg, 'zoomed out, the islets are left out as in 2D');
assert.equal(r.hills, ev('HILLS.length'));
assert.ok(r.again, 'built once');
assert.ok(r.fans.length >= 2 && r.fans.every(n => n === r.lvFan), 'shadow and grass are filled each frame from the same fan (the zoom level’s)');
assert.equal(r.wl, false, 'no picture of the land is uploaded');
assert.deepEqual(errors, []);
});
test('the 2D layers are cleared only when something was painted on them', () => {
const { ev, errors } = open();
ev(STUB);
ev(`(()=>{const f=GLX.fx,c=CTX0,cr=(x)=>{const o=x.clearRect;x.__n=0;x.clearRect=function(){x.__n++;return o.apply(this,arguments);};};cr(f);cr(c);})()`);
ev('cam.z=1.4;draw(1000);draw(1016)');
assert.equal(ev('CTX0.__n'), 1, 'the empty map canvas under the card is cleared once');
ev('GLX.fxUsed=false;GLX.fx.__n=0;draw(1032)');
assert.equal(ev('GLX.fx.__n'), 0, 'an overlay nothing was painted on is left alone');
ev('GLX.fxUsed=true;draw(1048)');
assert.equal(ev('GLX.fx.__n'), 1, 'one that was painted on is cleared');
assert.equal(ev('GLX.fxUsed'), false);
assert.deepEqual(errors, []);
});
test('things that bob, pulse or float are pictures on the card, not shapes on the overlay', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{GLS.prog={p:{},u:{}};GLS.frame=true;GLS.n=0;const fx=document.getElementById('mapfx').getContext('2d'),n0=fx.calls.n,c0=CTX0.calls.n;ctx=fx;
drawCone(100,100,0);drawCone(100,100,500);drawBackhoe(200,100,0,true);shipSprite(300,100,1,1,'#FF4D5E',0,'sail');
ctx.globalAlpha=.5;textStamp('+$1,000','800 17px "Baloo 2", sans-serif',17,60,'#16A866','#fff',4,50,50);ctx.globalAlpha=1;
const n=GLS.n,size=SPRS.size,alpha=GLS.data[4*SPR_STRIDE+11];GLS.frame=false;GLS.n=0;ctx=CTX0;
return JSON.stringify({n,size,alpha,fx:fx.calls.n-n0,main:CTX0.calls.n-c0});})()`));
assert.equal(r.n, 5, 'one picture each');
assert.equal(r.fx, 0, 'nothing painted on the overlay');
assert.equal(r.alpha, 0.5, 'a fading floater keeps its fade');
assert.ok(r.size >= 4, 'a bobbing cone is the same picture at another place');
assert.deepEqual(errors, []);
});
test('a frame on the card is a handful of draws, whatever the size of the network', () => {
const { ev, errors } = open();
ev(STUB);
const draws = (body) => ev(`(()=>{${body};const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);GLX.gl.calls.length=0;draw(1016);
return GLX.gl.calls.filter(c=>/^draw(Arrays|ArraysInstanced)$/.test(c[0])).length;})()`);
const big = draws(''), links = ev('S.links.length');
ev('S.links.length=0;compute()');
const none = draws('');
assert.ok(links > 100, 'a big network');
assert.ok(big < 50, `${big} draws for ${links} links`);
assert.ok(big - none <= 8, `the tubes add their passes, not one draw per link (${none} without links, ${big} with)`);
assert.deepEqual(errors, []);
});
test('panning on the card repaints no land and sends no geometry again', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{let paints=0;const pw=paintWorld;paintWorld=function(){paints++;return pw.apply(this,arguments);};
const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);GLX.gl.calls.length=0;
for(let i=1;i<=30;i++){cam.x+=25;draw(1000+i*16);}
paintWorld=pw;const c=GLX.gl.calls,static_=c.filter(x=>x[0]==='bufferData'&&x[3]==='STATIC_DRAW').length;
return JSON.stringify({paints,tex:c.filter(x=>x[0]==='texImage2D').length,static_});})()`));
assert.equal(r.paints, 0, 'the land is never painted with the 2D canvas');
assert.equal(r.tex, 0, 'no picture of the land, no tube points uploaded again');
assert.equal(r.static_, 0, 'the land and the cables were built once');
assert.deepEqual(errors, []);
});
test('Settings › Map drawing: Auto uses the card, Always 2D keeps the 2D map and is remembered', () => {
const { ev, errors } = open();
ev(STUB);
ev('ACT.settings({})');
assert.match(ev(`document.getElementById('modal').innerHTML`), /data-act="mapSet"/, 'the setting is in Settings');
ev(`ACT.mapSet({v:'2d'});draw(1000)`);
assert.equal(ev(`localStorage.getItem('sot-map')`), '2d');
assert.equal(ev('glOn()'), false);
assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'the card is hidden');
ev(`ACT.mapSet({v:'sideways'})`);
assert.equal(ev(`localStorage.getItem('sot-map')`), '2d', 'a value it does not know changes nothing');
ev(`ACT.mapSet({v:'auto'});draw(1016)`);
assert.equal(ev(`localStorage.getItem('sot-map')`), null);
assert.equal(ev('glOn()'), true);
assert.equal(ev(`document.getElementById('mapgl').hidden`), false);
assert.deepEqual(errors, []);
});
test('a sprite record that makes the queue grow is kept, for pictures and for discs', () => {
const { ev, errors } = open();
// Pictures and discs alternate, so both cross a growth (2048, then 4096 records); each record says which one it is.
const bad = JSON.parse(ev(`(()=>{const e={up:true,u0:.1,v0:.2,u1:.3,v1:.4,cv:null};GLS.frame=true;GLS.n=0;GLS.data=new Float32Array(SPR_STRIDE*2048);
for(let i=0;i<4100;i++){ctx.globalAlpha=(i%7+1)/8;if(i%2)dot(i,i*2,3+i%5,'#FF4D5E',(i%3+1)/4);else blit(e,i,i*2,10+i%9,20+i%11);}
ctx.globalAlpha=1;const D=GLS.data,n=GLS.n,cap=D.length/SPR_STRIDE,bad=[];GLS.frame=false;GLS.n=0;
for(let i=0;i<n;i++){const o=i*SPR_STRIDE,want=i%2?[i,i*2,3+i%5,1,(i%3+1)/4]:[i,i*2,10+i%9,0,(i%7+1)/8];
const got=i%2?[D[o],D[o+1],D[o+2],D[o+12],D[o+11]]:[D[o],D[o+1],D[o+2],D[o+12],D[o+11]];
if(i%2===0&&(D[o+3]!==20+i%11||D[o+4]!==Math.fround(.1)||D[o+7]!==Math.fround(.4)))bad.push(i);
else if(i%2&&D[o+8]!==1)bad.push(i);
else if(want.some((v,j)=>Math.fround(v)!==got[j]))bad.push(i);}
return JSON.stringify({n,cap,bad:bad.slice(0,8),edges:[2047,2048,2049,4096,4097].filter(i=>bad.includes(i))});})()`));
assert.equal(bad.n, 4100);
assert.ok(bad.cap >= 4100, 'the queue grew past 4096 records');
assert.deepEqual(bad.edges, [], 'the records at each growth are where they were drawn');
assert.deepEqual(bad.bad, [], 'and so is every other record');
assert.deepEqual(errors, []);
});
test('a city under attack never reuses its picture without the attack ring, and gets it back after', () => {
const { ev, errors } = open();
const r = JSON.parse(ev(`(()=>{const id=Object.keys(S.pops).find(c=>!S.pops[c].down||S.pops[c].down<=S.day),C=CITY[id],p=S.pops[id],t=cTier(id);
const st={down:false,feed:false,sel:false,inc:false,ixDraw:false,ixHot:false,off:false,big:false};
const spr=now=>{const ph=cityPhase(C,p,false,now);return [ph.dd,citySprite(C,p,t,1,1,ph,st)];};
R.ddosHot={};const [d0,quiet]=spr(0);
R.ddosHot={[id]:1};const [d1,hit0]=spr(0),[d2,hit3]=spr(90);
R.ddosHot={};const [d3,after]=spr(0);
// Animations off: the map's clock stays at 0, so the attack is always at step 0.
R.ddosHot={[id]:1};const [d4,still]=spr(0);
return JSON.stringify({dd:[d0,d1,d2,d3,d4],sameAtZero:quiet===hit0,step:hit0===hit3,back:after===quiet,still:still===hit0});})()`));
assert.deepEqual(r.dd, [-1, 0, 3, -1, 0]);
assert.equal(r.sameAtZero, false, 'step 0 of an attack is not the picture without one');
assert.equal(r.step, false, 'the ring turns');
assert.equal(r.back, true, 'once over, the plain picture is back');
assert.equal(r.still, true, 'with animations off the attack keeps its own picture');
assert.deepEqual(errors, []);
});
test('leaving a game hides the card’s layers, and the next game shows them again', () => {
const { ev, errors } = open();
ev(STUB);
const shown = () => JSON.parse(ev(`JSON.stringify([GLX.shown,!document.getElementById('mapgl').hidden,!document.getElementById('mapfx').hidden])`));
ev('draw(1000)');
assert.deepEqual(shown(), [true, true, true], 'a game on the card');
ev('ACT.toTitle();draw(1016)');
assert.deepEqual(shown(), [false, false, false], 'back to the title: the old network is not left behind it');
assert.ok(ev('ctx===CTX0'));
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;compute();draw(1032)`);
assert.deepEqual(shown(), [true, true, true], 'the next game is on the card again');
ev(`slotBroke(UI.slot||'x');draw(1048)`);
assert.deepEqual(shown(), [false, false, false], 'a damaged save leaves the title with an empty map too');
assert.deepEqual(errors, []);
});
// Faults injected into the card at each step of a frame: WebGL is given up once, the same frame is drawn in 2D, the
// layers are hidden, and the next frames are 2D without another try or another error.
for (const [where, inject] of [
['the start of a frame', `GLX.gl.clear=()=>{throw new Error('boom')};`],
['an upload of the tubes', `GLX.key=[];GLX.gl.texImage2D=()=>{throw new Error('boom')};`],
['the pictures’ draw', `GLS.prog={p:{},u:{}};GLS.vao={};GLS.tex={};glsDraw=()=>{throw new Error('boom')};`],
['a picture going into the atlas', `GLS.prog={p:{},u:{}};GLS.vao={};GLS.tex={};SPRS.clear();GLX.gl.texSubImage2D=()=>{throw new Error('boom')};`],
]) {
test(`a fault in ${where} falls back to 2D once and for all`, () => {
const { ev, errors } = open();
ev(STUB);
ev(`draw(1000);${inject}window.__tries=0;const gb=glBegin;glBegin=function(){__tries++;return gb.apply(this,arguments);};
window.__warn=0;console.warn=function(){__warn++;};`);
const c0 = ev('CTX0.calls.n');
ev('draw(1016);draw(1032);draw(1048)');
assert.equal(ev('GLX.dead'), true, 'WebGL is given up');
assert.equal(ev('__tries'), 1, 'and not tried again every frame');
assert.equal(ev('__warn'), 1, 'said once');
assert.ok(ev('ctx===CTX0'), 'the 2D context is back');
assert.equal(ev('GLS.frame'), false);
assert.equal(ev('GLS.n'), 0);
assert.equal(ev(`document.getElementById('mapgl').hidden&&document.getElementById('mapfx').hidden`), true, 'the layers are hidden');
assert.ok(ev('CTX0.calls.n') - c0 > 1000, 'the 2D map is drawn, from the frame that failed on');
assert.deepEqual(errors, []);
});
}
test('an error outside the card still reaches the loop, and leaves the frame clean', () => {
const { ev, errors } = open();
ev(STUB);
ev(`draw(1000);window.__dc=drawCity;drawCity=function(){throw new Error('not the card');};`);
assert.throws(() => ev('draw(1016)'), /not the card/);
assert.equal(ev('GLX.dead'), false, 'WebGL stays on: the card did nothing wrong');
assert.ok(ev('ctx===CTX0'));
assert.equal(ev('GLS.frame'), false);
ev('drawCity=__dc;draw(1032)');
assert.equal(ev('GLX.shown'), true);
assert.deepEqual(errors, []);
});
test('selecting a tube sends its halo to the card, not the network again', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);const c=GLX.gl.calls,nSeg=GLX.nSeg;
const sent=()=>{const b=c.filter(x=>x[0]==='bufferData').map(x=>x[2]&&x[2].length||0),t=c.filter(x=>x[0]==='texImage2D').length;c.length=0;return {b,t};};
sent();const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));UI.sel={type:'link',id:l.id};draw(1016);const on=sent(),halo=GLX.nHalo;
UI.sel=null;draw(1032);const off=sent();
return JSON.stringify({nSeg,on,off,halo,haloDraw:GLX.nHalo});})()`));
const tubes = r.nSeg * 12;
assert.ok(r.halo > 0, 'the halo has the selected tube’s segments');
assert.ok(!r.on.b.includes(tubes) && r.on.t === 0, 'selecting sends no tube, packet or point again');
assert.ok(r.on.b.includes(r.halo * 12), 'only the halo goes up');
assert.ok(!r.off.b.includes(tubes) && r.off.t === 0, 'nor does unselecting');
assert.equal(r.haloDraw, 0, 'and the halo is gone');
assert.deepEqual(errors, []);
});
// A WebGL2 context that compiles everything and names its renderer: enough for glInit() to run to the end.
const FAKE_GL = (name) => `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};const c=document.getElementById('mapgl');c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){
if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
if(k==='getExtension')return ()=>({UNMASKED_RENDERER_WEBGL:'REN'});
if(k==='getParameter')return (p)=>p==='REN'?${JSON.stringify(name)}:p==='ACTIVE_UNIFORMS'?0:4096;
if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
return ()=>({});}});})()`;
test('a graphics card drawn by the processor keeps the 2D map; a real one gets the card', () => {
for (const [name, gl] of [['ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)', false],
['llvmpipe (LLVM 17.0.6, 256 bits)', false], ['Microsoft Basic Render Driver', false],
['ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 Direct3D11 vs_5_0 ps_5_0, D3D11)', true], ['Apple M2', true], ['Mali-G78', true]]) {
const { ev } = open();
ev(FAKE_GL(name));
ev('console.warn=()=>{}');
assert.equal(ev('glInit()'), gl, name);
assert.equal(ev('GLX.dead'), !gl, name);
assert.equal(ev('GLX.gpu'), name, 'the renderer is still named');
}
const { ev } = open();
ev(FAKE_GL('SwiftShader driver'));
ev('GLX.soft=true');
assert.equal(ev('glInit()'), true, 'the GPU benchmark can still measure it');
});

View file

@ -0,0 +1,168 @@
// A graphics card short of memory may refuse a texture or a buffer without throwing: the call only leaves
// OUT_OF_MEMORY for getError(), and the atlas then drew every picture as a black box while the map stayed on the card.
// The big uploads now read it (glMem(), src/game/96-map/56-webgl.js): the atlas tries 2048 px before giving up, and
// any other refusal gives the card up for 2D in the same frame, or for a picture within a second. getError() is never
// read on an ordinary frame, and at most once a second while pictures are sent (each read waits for the card).
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
/* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's, and that refuses memory as asked in
window.__FAIL: atlas (the texture sizes refused), land (the first static buffer after setup), tubes (the tubes'
points), sprites (every picture sent into the atlas). A refusal sets OUT_OF_MEMORY, read once by getError(); the
reads are counted. It also counts the pictures sent (__SUB), what is deleted (__DEL) and the context let go (__LOST). */
const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__GE=0;window.__ERR=0;window.__SUB=0;window.__DEL=[];window.__LOST=0;window.__LOSTEV=0;
const F=window.__FAIL;let setup=true,lost=false;const c=document.getElementById('mapgl');c.addEventListener('webglcontextlost',()=>{__LOSTEV++;});
c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){
if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
if(k==='getExtension')return (n)=>n==='WEBGL_lose_context'?{loseContext:()=>{__LOST++;lost=true;c.dispatchEvent(new window.Event('webglcontextlost'));}}:{UNMASKED_RENDERER_WEBGL:'REN'};
if(k==='isContextLost')return ()=>lost||!!window.__lostNow;
if(k==='deleteTexture'||k==='deleteBuffer')return (x)=>{__DEL.push(x);};
if(k==='texSubImage2D')return ()=>{__SUB++;if(F.sprites)__ERR='OUT_OF_MEMORY';};
if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096;
if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
if(k==='getError')return ()=>{__GE++;const e=__ERR;__ERR=0;return e;};
if(k==='texImage2D')return (...a)=>{if(a[2]==='RGBA'&&(F.atlas||[]).includes(a[3]))__ERR='OUT_OF_MEMORY';if(a[2]==='RGBA32F'&&F.tubes)__ERR='OUT_OF_MEMORY';};
if(k==='bufferData')return (...a)=>{if(a[2]==='STATIC_DRAW'&&F.land&&!setup){F.land=false;__ERR='OUT_OF_MEMORY';}};
if(k==='useProgram')return ()=>{setup=false;};
return ()=>({});}});})()`;
function open(fail) {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{};
window.__FAIL=${JSON.stringify(fail)};`);
h.ev(GL);
return h;
}
test('a card without memory for a 4096 px atlas gets a 2048 px one, and keeps the map', () => {
const { ev, errors } = open({ atlas: [4096] });
assert.equal(ev('glInit()'), true);
assert.equal(ev('GLS.size'), 2048);
assert.equal(ev('GLX.dead'), false);
assert.deepEqual(errors, []);
});
test('a card without memory for either atlas leaves the map in 2D', () => {
const { ev, errors } = open({ atlas: [4096, 2048] });
assert.equal(ev('glInit()'), false);
assert.equal(ev('GLX.dead'), true);
ev('__T+=16;draw(__T);');
assert.equal(ev('glOn()'), false, 'the map is drawn in 2D');
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
assert.deepEqual(errors, []);
});
for (const what of ['land', 'tubes']) {
test(`a card that refuses the ${what} without throwing gives the map to 2D in the same frame`, () => {
const { ev, errors } = open({ [what]: true });
assert.equal(ev('glInit()'), true);
ev('UI.tickErr=false;__T+=16;draw(__T);');
assert.equal(ev('GLX.dead'), true, 'the card is given up');
assert.equal(ev('glOn()'), false);
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
assert.equal(ev('ctx===CTX0&&!GLS.frame'), true);
assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player: the frame is drawn again in 2D');
// The next frames are plain 2D ones.
ev('__T+=16;draw(__T);__T+=16;draw(__T);');
assert.deepEqual(errors, []);
});
}
test('an ordinary frame never asks the card for its errors', () => {
const { ev, errors } = open({});
assert.equal(ev('glInit()'), true);
ev('__T+=16;draw(__T);');
assert.equal(ev('GLX.dead'), false);
assert.ok(ev('__GE') > 0, 'the first frame checked its uploads');
// Panning brings new cities into view, whose pictures are sent: they are checked at most once a second (each read
// waits for the card), the first time a second after the first frame's check.
const pan = JSON.parse(ev(`(()=>{let sent=0,reads=0,most=0,at=[];for(let i=0;i<120;i++){const s=__SUB,g=__GE;cam.x+=3;__T+=16;draw(__T);
if(__SUB>s)sent++;if(__GE>g){reads++;at.push(i);}most=Math.max(most,__GE-g);}return JSON.stringify({sent,reads,most,at});})()`));
assert.ok(pan.sent > 5, 'frames send pictures');
assert.ok(pan.reads >= 1 && pan.reads <= 2, `about two seconds of panning read the errors once or twice, not once per frame that sends (${JSON.stringify(pan)})`);
assert.ok(pan.most <= 4, 'one check reads at most four flags');
// The pan's last pictures are still to be checked: once, on the next frame a second on. Then a still map reads nothing.
ev('__GE=0;__T+=1100;draw(__T);');
assert.ok(ev('__GE') <= 4, 'the pictures left over are checked once');
ev('__GE=0;for(let i=0;i<10;i++){__T+=1100;draw(__T);}');
assert.equal(ev('__GE'), 0, 'a still map reads nothing');
assert.deepEqual(errors, []);
});
/* A picture the card refused without throwing (texSubImage2D only leaves OUT_OF_MEMORY) was kept as sent, and drawn
from an atlas that never got it. The frame now checks its new pictures before drawing them, and gives the map to 2D
in that same frame: no picture is kept as sent. */
test('a picture the card refuses without throwing gives the map to 2D in the same frame', () => {
const { ev, errors } = open({ sprites: true });
assert.equal(ev('glInit()'), true);
ev('UI.tickErr=false;const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;__T+=16;draw(__T);');
assert.ok(ev('__SUB') > 0, 'pictures were sent');
assert.equal(ev('GLX.dead'), true, 'the card is given up');
assert.equal(ev('SPRS.size'), 0, 'no picture is kept as sent to the card');
assert.equal(ev('glOn()'), false);
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
assert.ok(ev('SPRC.size') > 0, 'the same frame was drawn again in 2D, with its own pictures');
assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player');
ev('__T+=16;draw(__T);');
assert.deepEqual(errors, []);
});
// The card keeps an error until it is read: a picture refused between two checks is found by the next one.
test('a picture refused after the first check gives the map to 2D within a second', () => {
const { ev, errors } = open({});
assert.equal(ev('glInit()'), true);
ev('UI.tickErr=false;const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;__T+=16;draw(__T);');
assert.equal(ev('GLX.dead'), false);
ev('__FAIL.sprites=true;');
const n = ev('(()=>{let i=0;for(;i<120&&!GLX.dead;i++){cam.x+=5;__T+=16;draw(__T);}return i;})()');
assert.equal(ev('GLX.dead'), true, 'given up');
assert.ok(n * 16 <= 1000 + 32, `within a second (${n} frames)`);
assert.equal(ev('SPRS.size'), 0, 'no picture is kept as sent');
assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player');
assert.deepEqual(errors, []);
});
/* Given up for good while the context still lives (memory refused), the card kept the atlas (64 MB at 4096 px) and the
rest while the 2D map began painting its own pictures. glKill() now deletes the biggest and lets the context go. */
test('giving the card up for good frees what it holds and lets the context go, and the frame is drawn in 2D', () => {
const { ev, errors } = open({ tubes: true });
assert.equal(ev('glInit()'), true);
ev('window.__atlas=GLS.tex;window.__tubes=GLX.tex;window.__buf=GLS.buf;');
ev('UI.tickErr=false;__T+=16;draw(__T);');
assert.equal(ev('GLX.dead'), true);
assert.equal(ev('__DEL.includes(__atlas)&&__DEL.includes(__tubes)&&__DEL.includes(__buf)'), true, 'the atlas, the tubes’ points and the pictures’ buffer are deleted');
assert.equal(ev('__LOST'), 1, 'the context is let go');
assert.equal(ev('__LOSTEV'), 1, 'its loss event came once');
assert.equal(ev('GLS.tex===null&&GLS.buf===null&&GLX.tex===null&&GLX.gl===null&&GLX.ctx===null'), true, 'nothing on the card is referenced');
assert.equal(ev('GLX.why'), 'the graphics card is out of memory (the tubes)', 'the loss it caused does not replace the reason');
assert.equal(ev('!!UI.tickErr'), false, 'the frame was drawn again in 2D');
ev('__T+=16;draw(__T);');
assert.deepEqual(errors, []);
});
test('a setup that fails half-way lets its context go too', () => {
const { ev, errors } = open({ atlas: [4096, 2048] });
assert.equal(ev('glInit()'), false);
assert.equal(ev('__LOST'), 1);
assert.equal(ev('GLX.ctx'), null);
assert.deepEqual(errors, []);
});
// A context the browser lost may come back (tests/webgl-context-restore.test.js): it is waited for, not let go.
test('a context the browser lost is not let go a second time', () => {
const { ev, errors } = open({});
assert.equal(ev('glInit()'), true);
ev('__T+=16;draw(__T);');
ev('window.__lostNow=true;document.getElementById("mapgl").dispatchEvent(new window.Event("webglcontextlost",{cancelable:true}));');
assert.equal(ev('GLX.dead'), false, 'waiting for it to come back');
assert.equal(ev('GLX.lost&&!glOn()'), true, 'the 2D map draws meanwhile');
assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did');
ev('__T+=16;draw(__T);');
assert.deepEqual(errors, []);
});

153
tests/webgl-sprites.test.js Normal file
View file

@ -0,0 +1,153 @@
// The card's pictures (src/game/96-map/59-gl-sprites.js): painted on one reused canvas and sent to the atlas at once, so
// a long zoom does not leave the browser holding a canvas per picture (it lost the graphics context and fell back to 2D).
// The 2D map keeps a canvas per picture. jsdom has no WebGL: a stand-in context records what would go to the card.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
return h;
}
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
return (...a)=>{calls.push([k,...a]);return {};};}});
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;
// Counts the canvases the page makes from here on.
const ce=document.createElement.bind(document);window.__canvases=0;document.createElement=function(t){if(String(t).toLowerCase()==='canvas')__canvases++;return ce.apply(document,arguments);};
return gl;})()`;
// Frames over a zoom from far to near and back, as a player pinching would.
const ZOOM = `(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;for(let i=0;i<=40;i++){cam.z=0.5*Math.pow(9,(1-Math.cos(i/40*Math.PI*2))/2);draw(1000+i*16);}})()`;
test('on the card, pictures are painted on one canvas and each goes into the atlas as it is painted', () => {
const { ev, errors } = open();
ev(STUB);
ev(ZOOM);
const r = JSON.parse(ev(`(()=>{const subs=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D'),es=[...SPRS.values()];
return JSON.stringify({canvases:__canvases,subs:subs.length,sprites:es.length,mine:es.filter(e=>e.cv).length,
allUp:es.every(e=>e.up),rect:subs.every(c=>c.length===10&&c[9]===GLS_PAD.cv&&c[5]>0&&c[6]>0),
fit:subs.every(c=>c[5]<=GLS_PAD.cv.width&&c[6]<=GLS_PAD.cv.height),keys:es.length>0&&SPRC.size===0});})()`));
assert.ok(r.sprites > 50, `a zoom paints many pictures (${r.sprites})`);
assert.ok(r.canvases <= 1, `one canvas for all of them, not one each (${r.canvases} made)`);
assert.equal(r.mine, 0, 'no picture keeps a canvas of its own');
assert.equal(r.allUp, true, 'every picture is in the atlas');
assert.ok(r.subs >= r.sprites, 'each was sent once, when painted');
assert.equal(r.rect, true, 'only its corner of the pad, from the pad');
assert.equal(r.fit, true);
assert.equal(r.keys, true, 'kept apart from the 2D map’s pictures');
assert.deepEqual(errors, []);
});
// The card blends the texels around the point it reads: a picture drawn off whole pixels, or stretched while a zoom
// moves, read half a texel past its edge, and the map showed thin coloured lines around cities (its neighbour in the
// atlas, or a picture from before the last reset). So each picture goes in with a clear border, and never touches another.
test('on the card, every picture sits in the atlas in a clear border of its own', () => {
const { ev, errors } = open();
ev(STUB);
// What the pad is asked to do for each picture: cleared, clipped to the picture, painted inside the border.
ev(`(()=>{const P=glsPad(1,1),g=P.g;window.__pad=[];for(const k of ['clearRect','rect','setTransform'])g[k]=(...a)=>__pad.push([k,...a]);})()`);
ev(ZOOM);
const r = JSON.parse(ev(`(()=>{const A=GLS.size,G=GLS_GAP,es=[...SPRS.values()].filter(e=>e.up);
const R=es.map(e=>({x0:Math.round(e.u0*A),y0:Math.round(e.v0*A),x1:Math.round(e.u1*A),y1:Math.round(e.v1*A),e}));
const exact=R.every(q=>q.x1-q.x0===q.e.pw&&q.y1-q.y0===q.e.ph);
const inside=R.every(q=>q.x0>=G&&q.y0>=G&&q.x1+G<=A&&q.y1+G<=A);
let touch=0;for(let i=0;i<R.length;i++)for(let j=i+1;j<R.length;j++){const a=R[i],b=R[j];
if(a.x0<b.x1+2*G&&b.x0<a.x1+2*G&&a.y0<b.y1+2*G&&b.y0<a.y1+2*G)touch++;}
const subs=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D').slice(-es.length);
const sent=subs.every(c=>R.some(q=>c[3]===q.x0-G&&c[4]===q.y0-G&&c[5]===q.e.pw+2*G&&c[6]===q.e.ph+2*G));
// Each picture: clearRect(0,0,W,H), then rect(G,G,W-2G,H-2G) for the clip, then the transform that paints inside it.
const at=__pad.flatMap((c,i)=>c[0]==='clearRect'?[i]:[]),nx=(i,k)=>__pad[i+k]||[];
return JSON.stringify({n:es.length,exact,inside,touch,sent,G,
cleared:at.length>=es.length&&at.every(i=>nx(i,0)[1]===0&&nx(i,0)[2]===0),
clipped:at.every(i=>{const c=nx(i,0),q=nx(i,1);return q[0]==='rect'&&q[1]===G&&q[2]===G&&q[3]===c[3]-2*G&&q[4]===c[4]-2*G;}),
offset:at.every(i=>{const q=nx(i,2);return q[0]==='setTransform'&&q[5]===G&&q[6]===G;})});})()`));
assert.ok(r.n > 50, `a zoom paints many pictures (${r.n})`);
assert.ok(r.G >= 1, 'a border of at least one texel');
assert.equal(r.exact, true, 'the picture’s own texels are read, no more');
assert.equal(r.inside, true, 'with room for its border inside the atlas');
assert.equal(r.touch, 0, 'no two pictures (with their borders) overlap or touch');
assert.equal(r.sent, true, 'each was sent with its border');
assert.equal(r.cleared, true, 'the pad is cleared from its corner, border included');
assert.equal(r.clipped, true, 'painting is clipped to the picture, so the border stays clear');
assert.equal(r.offset, true, 'and starts inside the border');
assert.deepEqual(errors, []);
});
test('a picture with its own canvas goes into the atlas in a clear border too', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{const e=spriteEntry('own',20,10,10,5,g=>{g.fillRect(0,0,20,10);});
const P=glsPad(1,1),g=P.g,log=[];g.clearRect=(...a)=>log.push(['clear',...a]);g.drawImage=(cv,x,y)=>log.push(['draw',cv===e.cv,x,y]);
const ok=glsEnsure(e),A=GLS.size,G=GLS_GAP,s=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D').pop();
return JSON.stringify({cv:!!e.cv,ok,log,G,u0:e.u0*A,v0:e.v0*A,u1:e.u1*A,v1:e.v1*A,pw:e.pw,ph:e.ph,sent:s.slice(3,7),pad:s[9]===P.cv});})()`));
assert.equal(r.cv, true, 'painted outside a card frame, so with its own canvas');
assert.equal(r.ok, true);
assert.deepEqual(r.log, [['clear', 0, 0, r.pw + 2 * r.G, r.ph + 2 * r.G], ['draw', true, r.G, r.G]], 'copied into a cleared pad, inside the border');
assert.deepEqual([r.u0, r.v0, r.u1, r.v1], [r.G, r.G, r.G + r.pw, r.G + r.ph]);
assert.deepEqual(r.sent, [0, 0, r.pw + 2 * r.G, r.ph + 2 * r.G]);
assert.equal(r.pad, true);
assert.deepEqual(errors, []);
});
test('a full atlas starts again and the picture that did not fit goes into the new one at once', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.shy=GLS.size-4;GLS.shx=GLS.size-2;GLS.shh=4;
const before=SPRS.size;let draws=0;const gd=glsDraw;glsDraw=function(){draws++;};
const e=spriteEntry('big',40,40,20,20,g=>{g.fillRect(0,0,40,40);});blit(e,10,10,40,40);
glsDraw=gd;const r={up:e.up,u0:e.u0,v0:e.v0,kept:SPRS.get('big')===e,size:SPRS.size,n:GLS.n,cv:!!e.cv,shy:GLS.shy};GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify(r);})()`));
assert.equal(r.up, true, 'the picture is in the atlas');
assert.equal(r.u0, 1 / 4096, 'at the start of the new atlas, past its clear border'); assert.equal(r.v0, 1 / 4096);
assert.equal(r.kept, true, 'and kept under its key after the restart');
assert.equal(r.size, 1, 'the old pictures are gone');
assert.equal(r.n, 1, 'drawn this frame');
assert.equal(r.cv, false);
assert.deepEqual(errors, []);
});
test('the 2D map keeps a canvas per picture, and its pictures are not the card’s', () => {
const { ev, errors } = open();
ev(`mapGl(false);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
const r = JSON.parse(ev(`(()=>{const es=[...SPRC.entries()];return JSON.stringify({n:es.length,cv:SPRS.size===0&&es.every(([k,e])=>e.cv&&e.cv.width===e.pw&&e.cv.height===e.ph),up:es.some(([,e])=>e.up)});})()`));
assert.ok(r.n > 10);
assert.equal(r.cv, true, 'each with its own canvas, at its size');
assert.equal(r.up, false, 'nothing went to a card');
assert.deepEqual(errors, []);
});
test('giving the card up drops its pictures; the 2D map paints its own', () => {
const { ev, errors } = open();
ev(STUB);
ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
assert.ok(ev('SPRS.size') > 10);
ev(`window.__warn=0;console.warn=function(){__warn++;};glKill('test')`);
assert.equal(ev('SPRS.size'), 0, 'no picture without a canvas is left behind');
assert.equal(ev('GLS.shx+GLS.shy+GLS.shh'), 0, 'the atlas is forgotten');
ev('draw(1016)');
assert.ok(ev('SPRC.size') > 10);
assert.equal(ev(`[...SPRC.values()].every(e=>e.cv)`), true, 'the 2D map’s pictures have their canvas');
assert.ok(ev('ctx===CTX0'));
assert.deepEqual(errors, []);
});
test('a picture too big for the atlas keeps its own canvas and is painted on the overlay', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.size=64;const n0=GLX.fx.calls.n;
const e=spriteEntry('huge',200,30,100,15,g=>{g.fillRect(0,0,200,30);});blit(e,0,0,200,30);
const r={cv:!!e.cv,up:e.up,n:GLS.n,fx:GLX.fx.calls.n-n0};GLS.frame=false;GLS.n=0;ctx=CTX0;GLS.size=4096;return JSON.stringify(r);})()`));
assert.equal(r.cv, true);
assert.equal(r.up, false);
assert.equal(r.n, 0, 'not queued for the card');
assert.ok(r.fx >= 1, 'drawn on the overlay instead');
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,91 @@
// While the zoom moves, the card keeps the pictures of cities at the scale they had when it began (stretched by up to
// 1.25× either way) and paints them again at the right step once the zoom rests (src/game/96-map/59-gl-sprites.js,
// sprQ()). A pinch used to repaint every city at every 1/24 step of its scale. The 2D map is unchanged.
// The page's clock is set by hand, so whether the zoom "rests" never depends on how fast the test runs.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
function open() {
const h = load({ seed: 777 });
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`);
return h;
}
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
return (...a)=>{calls.push([k,...a]);return {};};}});
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
// One POP's city pictures painted during frames from zoom z0 to z1 (the clock moving 16 ms a frame), by scale.
const ZOOM = (z0, z1, n) => `(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const seen=new Set(),bad=[];
for(let i=0;i<=${n};i++){cam.z=${z0}+(${z1}-${z0})*i/${n};__T+=16;draw(__T);
for(const k of SPRS.keys()){const p=k.split('|');if(p[0]==='city'&&p[1]===id)seen.add(+p[3]);}
const k=cityScale(iconScale()),kq=[...SPRS.keys()].filter(x=>x.split('|')[0]==='city'&&x.split('|')[1]===id).map(x=>+x.split('|')[3]);
if(kq.length&&!kq.some(q=>Math.max(q/k,k/q)<=1.25*(1+.5/24/0.7)))bad.push(i);}
return JSON.stringify({steps:[...seen].sort(),bad});})()`;
test('on the card a zoom keeps each city’s picture for a while, and paints it at the right step once it rests', () => {
const { ev, errors } = open();
ev(STUB);
ev(`cam.z=0.6;draw(__T);__T+=1000;draw(__T)`);
const r = JSON.parse(ev(ZOOM(0.6, 1.6, 60)));
// Without the hold, every 1/24 step between the two scales gets a picture.
const plain = ev(`(()=>{const s=new Set();for(let i=0;i<=60;i++){cam.z=0.6+i/60;s.add(Math.round(cityScale(iconScale())*24)/24);}return s.size;})()`);
assert.ok(plain >= 10, `the zoom crosses many steps (${plain})`);
assert.ok(r.steps.length <= 4, `the city was painted at ${r.steps.length} scales during the zoom (${r.steps}), not ${plain}`);
assert.deepEqual(r.bad, [], 'a picture is never stretched more than 1.25× either way (and half a step)');
assert.equal(ev('zoomMoving()'), true);
ev('__T+=300;draw(__T)');
const rest = JSON.parse(ev(`(()=>{const id=S.home,want=Math.round(cityScale(iconScale())*24)/24;
return JSON.stringify({f:ZH.f,want,has:[...SPRS.keys()].some(k=>{const p=k.split('|');return p[0]==='city'&&p[1]===id&&+p[3]===want;}),moving:zoomMoving()});})()`));
assert.equal(rest.moving, false);
assert.equal(rest.f, 1, 'at rest nothing is stretched');
assert.equal(rest.has, true, 'the city is painted again at its own step');
assert.deepEqual(errors, []);
});
test('the 2D map paints cities at their own step on every frame of a zoom, as before', () => {
const { ev, errors } = open();
ev(`mapGl(false);cam.z=0.8;draw(__T);`);
const r = JSON.parse(ev(`(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const bad=[];
for(let i=0;i<=30;i++){cam.z=0.8+i/30;__T+=16;SPRC.clear();draw(__T);const want=Math.round(cityScale(iconScale())*24)/24;
if(ZH.f!==1||![...SPRC.keys()].some(k=>{const p=k.split('|');return p[0]==='city'&&p[1]===id&&+p[3]===want;}))bad.push(i);}
return JSON.stringify({bad});})()`));
assert.deepEqual(r.bad, []);
assert.deepEqual(errors, []);
});
test('a still map is drawn again when the zoom comes to rest, so the stretched pictures do not stay', () => {
const { ev, errors } = open();
ev(STUB);
// Animations off: the loop skips frames while nothing changes.
ev(`cam.z=1;draw(__T);mapStill(0,__T);UI.drawnAt=__T;cam.z=1.3;__T+=16;mapStill(0,__T);draw(__T);UI.drawnAt=__T;`);
ev(`__T+=16`);
assert.equal(ev('mapStill(0,__T)'), true, 'nothing moved since the last frame');
ev(`__T+=300`);
assert.equal(ev('mapStill(0,__T)'), false, 'the zoom has rested: one more frame');
ev(`draw(__T);UI.drawnAt=__T;__T+=16`);
assert.equal(ev('ZH.f'), 1);
assert.equal(ev('mapStill(0,__T)'), true, 'and then the map stays still again');
assert.deepEqual(errors, []);
});
test('pictures that keep their size whatever the zoom (far-view cities, cones, diggers) are never held or stretched', () => {
const { ev, errors } = open();
ev(STUB);
const r = JSON.parse(ev(`(()=>{cam.z=1;draw(__T);__T+=1000;cam.z=1;draw(__T);cam.z=1.4;__T+=16;draw(__T);GLS.frame=true;GLS.n=0;ctx=GLX.fx;
const f=ZH.f;drawCone(100,100,0);drawBackhoe(200,100,0,false);const D=GLS.data,o=[D[2],D[3],D[SPR_STRIDE+2],D[SPR_STRIDE+3]];
const keys=[...SPRS.keys()].filter(k=>['cone','hoe'].includes(k.split('|')[0]));GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify({f,o,keys});})()`));
assert.notEqual(r.f, 1, 'the zoom is moving and city pictures are held');
assert.deepEqual(r.o, [26, 28, 38, 32], 'drawn at their own size');
assert.ok(r.keys.length >= 2 && r.keys.every(k => k.endsWith('|1')), 'painted at scale 1: ' + r.keys);
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,36 @@
// The 2D map's land picture (src/game/96-map/70-world-layer.js) is a software canvas (willReadFrequently) only in
// Firefox on Android, which garbled big paths on its graphics card (#43). Firefox on a computer had it too, and sent
// the whole picture to the card again on every frame: measured in Firefox on Windows, full screen 2560x1440, zoomed in
// the 2D map ran at a third of its speed (zoom 3.2 on the big network: 26 fps, 78 without it).
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
test('only Firefox on Android gets the land as a software canvas', () => {
const { ev } = load({ seed: 777 });
const soft = (ua) => ev(`softCanvas(${JSON.stringify(ua)})`);
// Firefox on Android, phone and tablet.
assert.equal(soft('Mozilla/5.0 (Android 14; Mobile; rv:132.0) Gecko/132.0 Firefox/132.0'), true);
assert.equal(soft('Mozilla/5.0 (Android 13; Tablet; rv:128.0) Gecko/128.0 Firefox/128.0'), true);
// Firefox on a computer, and the other browsers.
assert.equal(soft('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0'), false);
assert.equal(soft('Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0'), false);
assert.equal(soft('Mozilla/5.0 (Macintosh; Intel Mac OS X 14.5; rv:131.0) Gecko/20100101 Firefox/131.0'), false);
assert.equal(soft('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36'), false);
assert.equal(soft('Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/130.0 Mobile/15E148 Safari/605.1.15'), false);
});
test('elsewhere the land picture is an ordinary canvas, which the browser may keep on the graphics card', () => {
const { ev, errors } = load({ seed: 777 });
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();mapGl(false,false);
window.__opts=[];const gc=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(t,o){__opts.push(o||null);return gc.call(this,t,o);};
WL.cv=null;WL.key=null;cam.z=1.6;worldLayer(cam.z);`);
assert.equal(ev('SOFT_CANVAS'), false);
assert.ok(ev('!!WL.cv'), 'the land was painted');
assert.equal(ev('__opts.some(o=>o&&o.willReadFrequently)'), false);
assert.deepEqual(errors, []);
});