WebGL map: take a lost context back, and let it go for Always 2D
The first loss of the WebGL context gave the card up for the session. A context can come back (a driver reset; on a phone, sometimes just leaving the app), so a phone that went to another app came back to the slower 2D map until the page was reloaded. Always 2D, chosen in Settings, kept the context and its 64 MB atlas for a map drawn in 2D. A loss now leaves the 2D map drawing while the context is away (glLost(): the event is cancelled so the browser may give it back), and everything on the card is built again on the same context when it comes back (glRestored(), glForget(): glInit() runs as for the first frame). A card lost more than GL_LOSSES (2) times is given up for the session, so a card that keeps failing does not keep the map switching. Always 2D lets the context go through WEBGL_lose_context and Auto asks for it back, the same path, never counted as a loss; a context the browser gives back after the player chose Always 2D is let go again. Without the extension, and for the GPU benchmark's switches (mapGl(on,false)), the context is kept as before. The listeners and the overlay's wrappers are set once. Diagnostic info says when the map waits for a lost context. Tests: webgl-context-restore (7), and the loss test of webgl-out-of-memory now waits for the context instead of giving it up.
This commit is contained in:
parent
57546ea18e
commit
351b3aa522
5 changed files with 177 additions and 12 deletions
|
|
@ -5,29 +5,46 @@
|
|||
Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and
|
||||
packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for
|
||||
the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used.
|
||||
Puzzles, and any browser without WebGL2 or whose context fails or is lost, keep the 2D map. So does WebGL drawn by
|
||||
Puzzles, and any browser without WebGL2 or whose context fails, keep the 2D map; a lost context, until it is back. So does WebGL drawn by
|
||||
the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs
|
||||
microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */
|
||||
const GLX={want:true,dead:false,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''};
|
||||
const GLX={want:true,dead:false,lost:false,sleep:false,losses:0,lose:null,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''};
|
||||
try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){}
|
||||
// Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark).
|
||||
const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i;
|
||||
const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit();
|
||||
// Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not.
|
||||
// Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back.
|
||||
function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){}
|
||||
if(!on)glShow(false);GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;}
|
||||
if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}}
|
||||
GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;}
|
||||
function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;}
|
||||
// Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame.
|
||||
function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;}
|
||||
function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true;
|
||||
const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);}
|
||||
/* The card given up for good (not Always 2D, which keeps it for later) still held what was sent to it, the atlas alone
|
||||
/* The card given up for good (not Always 2D: glSleep()) still held what was sent to it, the atlas alone
|
||||
64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go
|
||||
(WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps
|
||||
the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */
|
||||
function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf);
|
||||
const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){}
|
||||
GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;}
|
||||
/* A lost context comes back. The browser may lose it (a driver reset; on a phone, sometimes just leaving the app) and
|
||||
give it back (webglcontextrestored): the 2D map draws meanwhile, and everything on the card is built again on the
|
||||
same context, as for the first frame. A card lost more than GL_LOSSES times is given up for the session, so a card
|
||||
that keeps failing does not keep the map switching. Always 2D lets the context go the same way (WEBGL_lose_context)
|
||||
and Auto asks for it back, so 64 MB of atlas and the rest are not held for a map that is not drawn. */
|
||||
const GL_LOSSES=2;
|
||||
// Forgets what was on the card (the context itself is kept): glInit() builds it all again.
|
||||
function glForget(){GLX.gl=null;spritesDrop();GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;Object.assign(GLX,{tex:null,land:{},ckey:null,key:[]});glShow(false);UI.drawnAt=0;}
|
||||
function glLost(e){if(GLX.dead)return;e.preventDefault();if(GLX.lost)return; // let go by Always 2D (glSleep())
|
||||
if(++GLX.losses>GL_LOSSES){glKill('the graphics context was lost '+GLX.losses+' times');return;}
|
||||
GLX.lost=true;glForget();}
|
||||
function glRestored(){if(GLX.dead)return;GLX.lost=false;glForget();if(!GLX.want)glSleep();}
|
||||
// Always 2D: lets the context go, unless the browser has it already (its restore then finds Always 2D and lets it go).
|
||||
function glSleep(){const L=GLX.lose;if(!GLX.ctx||GLX.dead||!L||typeof L.restoreContext!=='function')return;
|
||||
if(GLX.lost){GLX.sleep=true;return;}glForget();GLX.sleep=GLX.lost=true;try{L.loseContext();}catch(e){GLX.sleep=GLX.lost=false;}}
|
||||
/* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for
|
||||
getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big
|
||||
uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never
|
||||
|
|
@ -47,21 +64,21 @@ function glVao(gl,sizes,div=1,data=null){const v=gl.createVertexArray(),b=gl.cre
|
|||
gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
|
||||
let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;});
|
||||
gl.bindVertexArray(null);return {v,b};}
|
||||
function glInit(){if(GLX.gl)return true;if(GLX.dead)return false;
|
||||
function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false;
|
||||
try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers');
|
||||
const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'});
|
||||
if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl;
|
||||
if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}}
|
||||
try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){}
|
||||
if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu);
|
||||
const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)};
|
||||
// The tubes' points for the packets: floats read with texelFetch, never filtered.
|
||||
const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST);
|
||||
c.addEventListener('webglcontextlost',e=>{e.preventDefault();if(GLX.dead)return;glKill('the graphics context was lost');UI.drawnAt=0;});
|
||||
glsInit(gl);
|
||||
// The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every
|
||||
// frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself.
|
||||
const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype;
|
||||
for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}
|
||||
if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}}
|
||||
const V=s=>glVao(gl,s);
|
||||
Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;}
|
||||
catch(e){glKill(e);return false;}}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ function diagFrame(now){const D=DIAG;if(D.last)D.fr.push(now-D.last);D.last=now;
|
|||
if(D.fr.length>600)D.fr.splice(0,300);if(D.dr.length>600)D.dr.splice(0,300);}
|
||||
// What draws the map, and why it is the 2D canvas when it is.
|
||||
function diagMap(){if(!S)return 'map: none (title screen)';if(pzOn())return 'map: 2D (puzzle)';if(!GLX.want)return 'map: 2D (Always 2D)';
|
||||
if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';}
|
||||
if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';if(GLX.lost)return 'map: 2D (graphics context lost, waiting for it back)';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';}
|
||||
// Frames since the last readout: per second, the 95th percentile and the slowest, and draw()'s mean.
|
||||
function diagPerf(){const f=DIAG.fr.splice(0),d=DIAG.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0),
|
||||
q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-',gl=GLX.shown&&!GLX.dead;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue