From 7f4fdf6043d0de58b6b6074e3df195c59ac14d9e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 5 Nov 2026 10:31:19 +0100 Subject: [PATCH] WebGL map: join each line's segments, and draw a link being dragged out under the cities A see-through line on the card was one round-ended quad per segment, so where two met it was blended twice: the selected tube's halo showed a darker blob at every point, and the cables a notch at every corner. Each segment now knows its neighbours' directions and keeps only its side of the corner's bisector, as the 2D canvas strokes a path once. The link being dragged out was painted on the overlay, above the cities and their labels; it now goes to the card, under them, as in 2D, and its price label is a picture like the others. Auto after Always 2D, when the browser will not give the context back, gives the card up instead of waiting for it all session. Firefox reads the card's name from RENDERER, without the extension it warns about. --- src/game/96-map/55-link-look.js | 5 +- src/game/96-map/56-webgl.js | 9 +- src/game/96-map/57-webgl-background.js | 17 ++-- src/game/96-map/58-webgl-links.js | 50 ++++++++--- src/game/96-map/60-draw.js | 8 +- tests/map-2d.test.js | 2 +- tests/webgl-coast.test.js | 2 +- tests/webgl-context-restore.test.js | 12 +++ tests/webgl-frame-garbage.test.js | 2 +- tests/webgl-line-joins.test.js | 115 +++++++++++++++++++++++++ tests/webgl-map.test.js | 14 +-- tests/webgl-sprites.test.js | 2 +- tests/webgl-zoom-sprites.test.js | 2 +- 13 files changed, 201 insertions(+), 39 deletions(-) create mode 100644 tests/webgl-line-joins.test.js diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js index 8ca98b6..32c636c 100644 --- a/src/game/96-map/55-link-look.js +++ b/src/game/96-map/55-link-look.js @@ -1,7 +1,8 @@ /* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in 58-webgl-links.js), so they cannot drift apart. */ -// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable. -const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5]]; +// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable, +// 7 a link being dragged out. +const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12]]; // A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; const cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js index 7f4196d..0fe11a7 100644 --- a/src/game/96-map/56-webgl.js +++ b/src/game/96-map/56-webgl.js @@ -19,7 +19,9 @@ const glCan=()=>!GLX.dead&&typeof WebGL2RenderingContext!=='undefined'; // Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not. // Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back. function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){} - if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}} + if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false; + // A context the browser will not give back would leave the map waiting for it all session: give the card up instead. + try{GLX.lose.restoreContext();}catch(e){if(GLX.ctx&&GLX.ctx.isContextLost&&GLX.ctx.isContextLost()===false)GLX.lost=false;else glKill(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. @@ -72,7 +74,8 @@ function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false; 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){} + // Firefox names the card in RENDERER and warns that the extension is going away; other browsers need it. + try{const x=/Firefox\//.test(navigator.userAgent)?null: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. @@ -83,7 +86,7 @@ function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false; const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype; if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}} const V=s=>glVao(gl,s); - Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;} + Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4,4]),hv:V([4,4,4,4]),pv:V([4,4]),cb:V([4,4,4,4]),wv:V([4,4,4,4]),dv:V([4,4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;} catch(e){glKill(e);return false;}} // Colours as [r,g,b,a] from '#rrggbb', '#rgb' or 'rgba(r,g,b,a)', kept by string. const GLCOL=new Map(); diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js index 5055126..c245aee 100644 --- a/src/game/96-map/57-webgl-background.js +++ b/src/game/96-map/57-webgl-background.js @@ -53,11 +53,12 @@ function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@' COAST.forEach((ring,ri)=>{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return; const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return; coastFan(P,fan); - // Round ends make the joins round, as lineJoin='round' does; both lines are opaque, so the overlaps do not show. - for(let i=0;i+1new Float32Array(a); - G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE, + G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE, hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length}; glMem(gl,'the land');return GLX.land[key]=G;} // Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map. @@ -84,10 +85,11 @@ function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z)); // written into the same array every frame (no garbage for the collector to pick up while you play). const WAVE_COL=glColor('rgba(255,255,255,.45)'); function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0; - for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3; + for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3,m0=m; // Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame). for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y; - for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}} + for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}} + glJoin(A,m0,m,false);} gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);} // The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack. function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)return; @@ -103,8 +105,9 @@ function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)retu function glCables(gl,ks,selC,ar){const key=[selC,ar]; if(!GLX.ckey||key.some((v,i)=>v!==GLX.ckey[i])){const A=[]; for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue; - const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0; - for(let j=0;j+12; + for(let i=i0;ii0?i-1:closed?i1-1:-1,n=i+1=0){const q=p*LINE_STRIDE;A[o+12]=A[q+2]-A[q];A[o+13]=A[q+3]-A[q+1];}else A[o+12]=A[o+13]=0; + if(n>=0){const q=n*LINE_STRIDE;A[o+14]=A[q+2]-A[q];A[o+15]=A[q+3]-A[q+1];}else A[o+14]=A[o+15]=0;}} /* One instance per segment, a quad around it; the fragment keeps what lies within half the line width of the segment - (or of a dash of it, both with round ends), which also gives round joins and caps. */ -const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC; + (or of a dash of it, both with round ends), which also gives round joins and caps. Where two segments of a line + meet, their round ends overlap: each keeps only its side of the corner's bisector, so a see-through line (the + halo, the cables, the waves, the fiber's dots) is blended once there, as the 2D canvas strokes a path once. */ +const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC;layout(location=3) in vec4 aN; uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uBusy;uniform int uPass; -out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol;flat out vec2 vDash; +out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol,vK;flat out vec2 vDash,vEnd; +// The corner's bisector between directions u and v, in the segment's own frame (t along it, n across), and whether there is one. +vec3 cut(vec2 u,vec2 v,vec2 t,vec2 n){vec2 m=u+v;float l=length(m);if(length(u)<.5||length(v)<.5||l<1e-3)return vec3(0.);m/=l;return vec3(dot(t,m),dot(n,m),1.);} vec2 dashOf(int k){${LDASH.map((d,i)=>d.length?`if(k==${i})return vec2(${d[0]}.,${d[1]}.);`:'').join('')}return vec2(0.);} void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h; float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false; @@ -29,10 +39,16 @@ void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCa vec2 d=b-a;float L=length(d);vec2 t=L>1e-4?d/L:vec2(1.,0.),n=vec2(-t.y,t.x);float m=hw+1./uDpr; float sx=(gl_VertexID&1)==0?-m:L+m,sy=(gl_VertexID&2)==0?-m:m; vLoc=vec2(sx,sy);vLen=L;vS0=aP.x*uCam.z;vHalf=hw;vCol=col;vDash=dash;vButt=uPass==${LP.plain}&&(fl&${LINE_ROUND})==0?1.:0.; + float lp=length(aN.xy),ln=length(aN.zw);vec3 c0=L>1e-4&&lp>1e-9?cut(aN.xy/lp,t,t,n):vec3(0.),c1=L>1e-4&&ln>1e-9?cut(t,aN.zw/ln,t,n):vec3(0.); + vK=vec4(c0.xy,c1.xy);vEnd=vec2(c0.z,c1.z); gl_Position=clip(a+t*sx+n*sy,uView,(uPass==${LP.plain}?.9998:aC.x)*2.-1.);}`; -const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol;flat in vec2 vDash;uniform float uDpr;out vec4 o; +const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol,vK;flat in vec2 vDash,vEnd;uniform float uDpr;out vec4 o; void main(){float x=vLoc.x,y=vLoc.y,d; - if(vButt>.5&&(x<0.||x>vLen))discard; + // A corner: the side of the bisector that belongs to the neighbour is the neighbour's to paint. + if(vEnd.x>.5&&x*vK.x+y*vK.y<0.)discard; + if(vEnd.y>.5&&(x-vLen)*vK.z+y*vK.w>0.)discard; + // Flat ends only where the line really ends; its corners are joined. + if(vButt>.5&&((vEnd.x<.5&&x<0.)||(vEnd.y<.5&&x>vLen)))discard; if(vDash.x<=0.){float c=clamp(x,0.,vLen);d=length(vec2(x-c,y));} else{float P=vDash.x+vDash.y,g=vS0+x,k=floor(g/P);d=1e9; for(int i=-1;i<=1;i++){float a0=(k+float(i))*P,lo=max(a0,vS0),hi=min(a0+vDash.x,vS0+vLen);if(lo<=hi){float c=clamp(g,lo,hi);d=min(d,length(vec2(g-c,y)));}}} @@ -67,7 +83,8 @@ function glBuild(LG,GM,looks){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0; for(let gi=0;gix.id===selId))continue;const L=looks[gi],{pts,cum,len}=GM[gi],dep=glDepth(gi,N),col=glColor(L.col); - for(let j=0;j+1(x-CW/2)/z+cam.x,my=y=>(y-CH/2)/z+cam.y; + glSegAt(A,0,mx(ax),my(ay),mx(tx),my(ty),0,7,7,LINE_ROUND,1,DRAG_INK); + glSegAt(A,1,mx(ax),my(ay),mx(tx),my(ty),-now/30/z,4,7,LINE_ROUND,1,DRAG_PINK); + gl.bindBuffer(gl.ARRAY_BUFFER,GLX.dv.b);gl.bufferData(gl.ARRAY_BUFFER,A,gl.DYNAMIC_DRAW); + gl.disable(gl.DEPTH_TEST);glLines(gl,GLX.dv.v,2,[0]);gl.bindVertexArray(null);} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 6709e30..3d8b80a 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -86,12 +86,14 @@ function drawFrame(now){ if(UI.snap){const sv=UI.snap;tx=sv.sx;ty=sv.sy;} let [ax,ay]=toS(A.x,A.y,0);if(UI.snap){const B=CITY[UI.snap.id];const bxw=A.x+wrapDx(A.x,B.x);[tx,ty]=toS(bxw,B.y,0);}else{/* nearest copy of origin to cursor */for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k);if(Math.abs(px-tx)x.id===UI.sel.id);const rec=sl&&R.ef[edgeKey(sl)];if(rec){UI.feed=new Set(Object.keys(rec.eg).map(k=>R.egDesc[k].city));UI.dest=new Set(Object.keys(rec.dst));}} diff --git a/tests/map-2d.test.js b/tests/map-2d.test.js index 450ad59..51cab17 100644 --- a/tests/map-2d.test.js +++ b/tests/map-2d.test.js @@ -106,7 +106,7 @@ const GLSTUB = `window.__GLSTUB=(()=>{const calls=[];const gl=new Proxy({calls}, 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'}); + 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(),dv: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() { diff --git a/tests/webgl-coast.test.js b/tests/webgl-coast.test.js index f0ba261..0438e6b 100644 --- a/tests/webgl-coast.test.js +++ b/tests/webgl-coast.test.js @@ -19,7 +19,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in 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;})()`; + 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(),dv: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(); diff --git a/tests/webgl-context-restore.test.js b/tests/webgl-context-restore.test.js index ea46ea2..bb3a2c3 100644 --- a/tests/webgl-context-restore.test.js +++ b/tests/webgl-context-restore.test.js @@ -161,3 +161,15 @@ test('opening Settings never makes a context, and still says when the card canno assert.equal(note(), true, 'no WebGL2 in this browser: Settings says so'); assert.deepEqual(errors, []); }); + +test('Auto after Always 2D, when the browser will not give the context back, gives the card up instead of waiting all session', () => { + const { ev, errors } = open(); + assert.equal(JSON.parse(frame(ev)).gl, true); + ev(`ACT.mapSet({v:'2d'});`); + assert.equal(ev('GLX.sleep&&GLX.lost'), true, 'Always 2D let the context go'); + ev(`GLX.lose.restoreContext=()=>{throw new Error('not now');};ACT.mapSet({v:'auto'});`); + const f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead, f.lost], [false, true, true], 'given up for 2D, with a reason'); + assert.match(ev('diagMap()'), /map: 2D \(not now\)/, 'Diagnostic info says why, not "waiting for it back"'); + assert.deepEqual(errors, []); +}); diff --git a/tests/webgl-frame-garbage.test.js b/tests/webgl-frame-garbage.test.js index a672b14..9c68e4f 100644 --- a/tests/webgl-frame-garbage.test.js +++ b/tests/webgl-frame-garbage.test.js @@ -19,7 +19,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in 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'}); + 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(),dv: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). diff --git a/tests/webgl-line-joins.test.js b/tests/webgl-line-joins.test.js new file mode 100644 index 0000000..47b54d7 --- /dev/null +++ b/tests/webgl-line-joins.test.js @@ -0,0 +1,115 @@ +// Lines on the card are one instance per segment. Where two segments of a line meet, each keeps only its side of the +// corner (glJoin() tells it which way its neighbours run), so a see-through line is blended once there, as the 2D +// canvas strokes a path once: the selected tube's halo, the cables, the waves, the fiber's dots. Also: the link being +// dragged out is drawn on the card, under the cities as in 2D, not on the overlay above them. +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(),dv: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;})()`; + +// For records A of segments: which neighbour directions are wrong. A segment whose start is where the previous one +// ended must point back along it; one that starts a line (or ends one) must say it has no neighbour there. +const CHECK = `const joins=(A,n,lines)=>{const S=LINE_STRIDE,bad=[];let joined=0; + for(let i=0;iMath.abs(a-b)<=1e-3*Math.max(1,Math.abs(b));if(!near(A[o+12],pv[0])||!near(A[o+13],pv[1])||!near(A[o+14],nx[0])||!near(A[o+15],nx[1]))bad.push(i);if(!first)joined++;} + return {bad:bad.slice(0,5),joined,n};};`; + +test('the tubes and the selected one’s halo are joined segment to segment, and only within a tube', () => { + const { ev, errors } = open(); + ev(STUB); + const r = JSON.parse(ev(`(()=>{${CHECK}const ML=mapLinks(S.day),{SEG}=glBuild(ML.LG,ML.GM,ML.looks),starts=new Set();let si=0; + for(const gm of ML.GM){starts.add(si);si+=gm.pts.length-1;} + const gi=ML.GM.findIndex(gm=>gm.pts.length>4),H=glHalo(ML.LG,ML.GM,ML.looks,ML.LG[gi][0].id); + return JSON.stringify({tubes:joins(SEG,si,starts),halo:joins(H,H.length/LINE_STRIDE,new Set([0]))});})()`)); + assert.deepEqual(r.tubes.bad, [], 'every tube segment knows its neighbours, and no tube runs into the next'); + assert.ok(r.tubes.joined > r.tubes.n / 2, `most segments have a neighbour before them (${r.tubes.joined} of ${r.tubes.n})`); + assert.deepEqual(r.halo.bad, []); + assert.ok(r.halo.joined >= 3, 'the halo is one joined line'); + assert.deepEqual(errors, []); +}); + +test('coastlines close on themselves; cables and waves are joined along each line', () => { + const { ev, errors } = open(); + ev(STUB); + // A closed ring: the first segment's neighbour before it is the last one. + const ring = JSON.parse(ev(`(()=>{const A=[];const P=[[0,0],[10,0],[10,10],[0,10],[0,0]];for(let i=0;i+1{GLX.land={};const gl=GLX.gl;gl.calls.length=0;glLandGeo(gl,false,0); + const sent=gl.calls.filter(c=>c[0]==='bufferData'&&c[2]&&c[2].length%LINE_STRIDE===0&&c[2].length>LINE_STRIDE*10).map(c=>c[2]); + const A=sent[0];let open=0;for(let i=0;i 1000, 'the coastlines went to the card'); + assert.equal(land.open, 0, 'every coastline is a closed ring'); + const r = JSON.parse(ev(`(()=>{${CHECK}const gl=GLX.gl;GLX.ckey=null;glCables(gl,[0],null,false); + const F=gl.calls.filter(c=>c[0]==='bufferData').pop()[2],cs=new Set();let ci=0;for(const cp of CABLE_PAIRS){cs.add(ci);ci+=cp.pts.length-1;}const cab=joins(F,F.length/LINE_STRIDE,cs); + glWaves(gl,1234,[0]);const starts=new Set();for(let i=0;i 100, `cables have corners (${r.cab.joined})`); + assert.deepEqual(r.wav.bad, [], 'each wave is one line of eight segments'); + assert.deepEqual(errors, []); +}); + +test('the line shader takes the neighbours and splits each corner along its bisector', () => { + const { ev } = open(); + const vs = ev('GL_LINE_VS'), fs_ = ev('GL_LINE_FS'); + assert.match(vs, /layout\(location=3\) in vec4 aN/); + assert.match(fs_, /vEnd\.x>\.5&&x\*vK\.x\+y\*vK\.y<0\./); + assert.match(fs_, /vEnd\.y>\.5&&\(x-vLen\)\*vK\.z\+y\*vK\.w>0\./); + // The rule itself: at a corner, every point is painted by exactly one of the two segments that meet there. + const r = JSON.parse(ev(`(()=>{const norm=v=>{const l=Math.hypot(v[0],v[1]);return [v[0]/l,v[1]/l];},dot=(a,b)=>a[0]*b[0]+a[1]*b[1]; + let both=0,none=0,n=0; + for(const deg of [5,30,60,90,135,170]){const r=deg*Math.PI/180,J=[0,0],tA=[1,0],tB=[Math.cos(r),Math.sin(r)],m=norm([tA[0]+tB[0],tA[1]+tB[1]]); + for(let x=-12;x<=12;x+=0.37)for(let y=-12;y<=12;y+=0.41){const P=[x,y]; + // In capsule A (ending at J) or B (starting at J), half-width 6. + const inA=Math.hypot(x>0?x:x<-20?x+20:0,y)<=6, + pb=dot(P,tB),qb=Math.max(0,Math.min(20,pb)),inB=Math.hypot(x-qb*tB[0],y-qb*tB[1])<=6; + if(!inA&&!inB)continue;n++;const ownA=inA&&dot(P,m)<=0,ownB=inB&&dot(P,m)>=0;if(ownA&&ownB&&dot(P,m)!==0)both++;if(!ownA&&!ownB)none++;}} + return JSON.stringify({n,both,none});})()`)); + assert.ok(r.n > 1000); + assert.equal(r.both, 0, 'no point is painted twice'); + assert.equal(r.none, 0, 'no point of the joined line is left out'); +}); + +test('the link being dragged out goes to the card, under the cities, and its price label is a picture', () => { + const { ev, errors } = open(); + ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`); + ev(STUB); + ev(`(()=>{const fx=GLX.fx;fx.__st=0;fx.stroke=function(){fx.__st++;};})()`); + ev(`UI.drag=null;draw(1000);`); + const base = ev('GLX.fx.__st'); + ev(`(()=>{const h=CITY[S.home],[x,y]=toS(h.x,h.y,0);UI.drag={mode:'link',from:S.home,cx:x+120,cy:y+40};UI.snap=null;GLX.gl.calls.length=0;GLX.fx.__st=0;draw(1000);})()`); + assert.equal(ev('GLX.fx.__st'), base, 'nothing more is stroked on the overlay above the cities'); + const r = JSON.parse(ev(`(()=>{const c=GLX.gl.calls,i=c.findIndex(x=>x[0]==='bufferData'&&x[2]===GLX.da), + d=c.findIndex((x,j)=>j>i&&x[0]==='drawArraysInstanced'&&x[4]===2),A=GLX.da,S=LINE_STRIDE; + return JSON.stringify({sent:i>=0,drawn:d>i,dash:[A[6],A[S+6]],w:[A[5],A[S+5]],off:[A[4],A[S+4]],z:cam.z,dash7:LDASH[7]});})()`)); + assert.ok(r.sent && r.drawn, 'the two dotted lines go to the card in one draw'); + assert.deepEqual(r.dash, [7, 7]); assert.deepEqual(r.dash7, [2, 12]); + assert.deepEqual(r.w, [7, 4], 'the dark line under the pink one, as in 2D'); + assert.equal(r.off[0], 0); assert.ok(Math.abs(r.off[1] - (-1000 / 30 / r.z)) < 1e-3, 'the pink dots run along the line as in 2D'); + // Snapped to a city, the price shows on a pill picture with the cities' pictures, not on the overlay. + const label = ev(`(()=>{const h=S.home,b=CITIES.find(c=>c.id!==h&&!isSub(h,c.id)).id,[x,y]=toS(CITY[b].x,CITY[b].y,0);UI.snap={id:b,sx:x,sy:y};GLX.fx.__st=0;draw(1016); + return [...SPRS.keys()].some(k=>k.startsWith('pill|')&&k.includes(' km'));})()`); + assert.equal(label, true); + assert.equal(ev('GLX.fx.__st'), base); + assert.deepEqual(errors, []); +}); diff --git a/tests/webgl-map.test.js b/tests/webgl-map.test.js index 7d41a6e..c61544b 100644 --- a/tests/webgl-map.test.js +++ b/tests/webgl-map.test.js @@ -21,7 +21,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in 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;})()`; + 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(),dv: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(); @@ -41,14 +41,14 @@ test('the instance data says what the 2D map draws: points, colours, dashes, pac 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;gix.id===sel); for(let j=0;j1e-3*Math.max(1,Math.abs(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!i||dd>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'); @@ -74,7 +74,7 @@ test('with WebGL the lines go to the card, the rest to the overlay, and the map 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 uploads = () => ev(`GLX.gl.calls.filter(c=>c[0]==='bufferData'&&c[2]&&c[2].length===GLX.nSeg*LINE_STRIDE).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'); @@ -298,10 +298,10 @@ test('selecting a tube sends its halo to the card, not the network again', () => 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; + const tubes = r.nSeg * ev('LINE_STRIDE'); 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.on.b.includes(r.halo * ev('LINE_STRIDE')), '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, []); diff --git a/tests/webgl-sprites.test.js b/tests/webgl-sprites.test.js index 95d4874..b8122d6 100644 --- a/tests/webgl-sprites.test.js +++ b/tests/webgl-sprites.test.js @@ -19,7 +19,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in 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'}); + 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(),dv: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);}; diff --git a/tests/webgl-zoom-sprites.test.js b/tests/webgl-zoom-sprites.test.js index ae35c7f..59be188 100644 --- a/tests/webgl-zoom-sprites.test.js +++ b/tests/webgl-zoom-sprites.test.js @@ -21,7 +21,7 @@ const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in 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'}); + 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(),dv: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.