WebGL map: give the card up for 2D when it runs out of memory without saying so

A card short of memory may refuse a texture or a buffer without throwing: the call only leaves OUT_OF_MEMORY for
getError(), which nothing read. Refused, the 64 MB atlas drew every city, label and marker as a black box while the
map stayed on the card (seen in Chromium by refusing it).

The big uploads now read it (glMem()): the atlas, the land for each zoom level, the tubes once a day, the cables.
The atlas tries 2048 px (16 MB) before giving up; any other refusal is the card's error, so draw() gives WebGL up
for the session and draws the same frame again in 2D. getError() is never read on an ordinary frame: each read waits
for the card.

tests/webgl-out-of-memory.test.js: a 4096 px atlas refused gives a 2048 px one; both refused, or the land or the
tubes refused, leave the map in 2D in that frame with no glitch for the player; panning reads no error.
This commit is contained in:
Antoine 2026-11-04 19:08:42 +01:00
parent fb76a1e6fd
commit 52c8aaffd6
No known key found for this signature in database
GPG key ID: 728FF1CE15732B05
5 changed files with 99 additions and 8 deletions

View file

@ -20,6 +20,12 @@ function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=docume
// Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame. // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame.
function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;} function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;}
function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);} function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);}
/* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for
getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big
uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never
every frame: each read waits for the card. Up to four flags are read, as one call returns only one. */
function glMem(gl,what){for(let i=0;i<4;i++){const e=gl.getError();if(!e||e===gl.CONTEXT_LOST_WEBGL)return;
if(e===gl.OUT_OF_MEMORY)throw glErr(new Error('the graphics card is out of memory ('+what+')'));}}
const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n'; const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n';
// Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing). // Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing).
const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n'; const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n';

View file

@ -50,8 +50,9 @@ function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@'
for(let i=0;i+1<P.length;i++){glSeg(sand,P[i],P[i+1],0,10,0,LINE_ROUND,SAND);glSeg(edge,P[i],P[i+1],0,2.5,0,LINE_ROUND,EDGE);}}); for(let i=0;i+1<P.length;i++){glSeg(sand,P[i],P[i+1],0,10,0,LINE_ROUND,SAND);glSeg(edge,P[i],P[i+1],0,2.5,0,LINE_ROUND,EDGE);}});
const hills=[],shine=[];for(const [x,y,r] of HILLS){hills.push(x,y,r*1.4,r*.8);shine.push(x-r*.3,y-r*.25,r*.6,r*.3);} const hills=[],shine=[];for(const [x,y,r] of HILLS){hills.push(x,y,r*1.4,r*.8);shine.push(x-r*.3,y-r*.25,r*.6,r*.3);}
const F=a=>new Float32Array(a); const F=a=>new Float32Array(a);
return GLX.land[key]={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE, G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE,
hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};} hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};
glMem(gl,'the land');return GLX.land[key]=G;}
// Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map. // Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map.
function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST); function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST);
gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan); gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan);
@ -94,7 +95,7 @@ function glCables(gl,ks,selC,ar){const key=[selC,ar];
for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue; for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;
const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0; const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0;
for(let j=0;j+1<cp.pts.length;j++){const p=cp.pts[j],q=cp.pts[j+1];glSeg(A,p,q,cum,hot?3:1.6,C.age==='old'?6:0,0,col);cum+=Math.hypot(q[0]-p[0],q[1]-p[1]);}} for(let j=0;j+1<cp.pts.length;j++){const p=cp.pts[j],q=cp.pts[j+1];glSeg(A,p,q,cum,hot?3:1.6,C.age==='old'?6:0,0,col);cum+=Math.hypot(q[0]-p[0],q[1]-p[1]);}}
const F=new Float32Array(A);gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cb.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.STATIC_DRAW);GLX.cn=F.length/LINE_STRIDE;GLX.ckey=key;} const F=new Float32Array(A);gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cb.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.STATIC_DRAW);glMem(gl,'the cables');GLX.cn=F.length/LINE_STRIDE;GLX.ckey=key;}
if(GLX.cn)glLines(gl,GLX.cb.v,GLX.cn,ks);} if(GLX.cn)glLines(gl,GLX.cb.v,GLX.cn,ks);}
// Starts a frame on the card: clears it and paints the background. The tubes come next (glFrame()), then the pictures // Starts a frame on the card: clears it and paints the background. The tubes come next (glFrame()), then the pictures
// (glsFrameEnd()); draw() paints anything else on the overlay, which becomes ctx until the frame ends. // (glsFrameEnd()); draw() paints anything else on the overlay, which becomes ctx until the frame ends.

View file

@ -71,7 +71,7 @@ function glBuild(LG,GM,looks){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0;
for(let i=0;i<L.pk;i++){const o=ki*8;PK[o]=p0;PK[o+1]=pts.length;PK[o+2]=len;PK[o+3]=L.pk;PK[o+4]=i;PK[o+5]=L.w0;PK[o+6]=dep;ki++;}} for(let i=0;i<L.pk;i++){const o=ki*8;PK[o]=p0;PK[o+1]=pts.length;PK[o+2]=len;PK[o+3]=L.pk;PK[o+4]=i;PK[o+5]=L.w0;PK[o+6]=dep;ki++;}}
gl.bindBuffer(gl.ARRAY_BUFFER,GLX.lv.b);gl.bufferData(gl.ARRAY_BUFFER,SEG,gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER,GLX.lv.b);gl.bufferData(gl.ARRAY_BUFFER,SEG,gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER,GLX.pv.b);gl.bufferData(gl.ARRAY_BUFFER,PK,gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER,GLX.pv.b);gl.bufferData(gl.ARRAY_BUFFER,PK,gl.DYNAMIC_DRAW);
gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA32F,GL_PTS_W,TH,0,gl.RGBA,gl.FLOAT,PT); gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA32F,GL_PTS_W,TH,0,gl.RGBA,gl.FLOAT,PT);glMem(gl,'the tubes');
Object.assign(GLX,{nSeg:ns,nPk:nk});return {SEG,PK,PT};} Object.assign(GLX,{nSeg:ns,nPk:nk});return {SEG,PK,PT};}
// The selected tube's halo: its segments again, at its own depth (so later tubes still cover it), and nothing else. // The selected tube's halo: its segments again, at its own depth (so later tubes still cover it), and nothing else.
function glHalo(LG,GM,looks,selId){const gl=GLX.gl,N=LG.length,A=[]; function glHalo(LG,GM,looks,selId){const gl=GLX.gl,N=LG.length,A=[];

View file

@ -18,10 +18,12 @@ const SPR_FS=GL_HEAD+`uniform sampler2D uTex;uniform float uDpr;in vec2 vUV,vQ;i
void main(){if(vK>.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);} void main(){if(vK>.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);}
else o=texture(uTex,vUV)*vC.a;}`; else o=texture(uTex,vUV)*vC.a;}`;
function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b; function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b;
// 4096 px square (64 MB), or what the card allows if that is less (some phones). // 4096 px square (64 MB), or what the card allows if that is less (some phones). A card that has not the memory for
GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096); // it gets 2048 (16 MB: more resets of the atlas, the same map); without even that, the map stays 2D (glMem).
GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex); GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);glMem(gl,'setup');
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null); for(GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096);;GLS.size>>=1){
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null);
try{glMem(gl,'the pictures');break;}catch(e){if(GLS.size<=2048)throw e;}}
for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR); for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR);
for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE); for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE);
GLS.shx=GLS.shy=GLS.shh=0;} GLS.shx=GLS.shy=GLS.shh=0;}

View file

@ -0,0 +1,82 @@
// 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. getError() is never read on an ordinary frame (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). A refusal sets OUT_OF_MEMORY, read once by getError(); the reads are counted. */
const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__GE=0;window.__ERR=0;
const F=window.__FAIL;let setup=true;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'?'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');
ev('__GE=0;for(let i=0;i<30;i++){cam.x+=3;__T+=16;draw(__T);}');
assert.equal(ev('__GE'), 0, 'panning sends nothing big, so nothing is read');
assert.deepEqual(errors, []);
});