Merge #281: draw the map with WebGL2 by default, 2D as fallback
This commit is contained in:
commit
13768c61cb
50 changed files with 2690 additions and 118 deletions
|
|
@ -22,6 +22,7 @@ const ACT={
|
|||
toast(B.equity?tr('interface.you_bought_out_bank_they_flew',{bank:esc(B.name)}):tr('interface.loan_from_bank_repaid_early',{bank:esc(B.name)}),'good');after();renderBank();},
|
||||
leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=lvl()>=3?'roadm':'lite';openLinkModal(a,b);},
|
||||
dashLink:({id})=>{$('dash').hidden=true;selectLink(id);focusLink(id);},
|
||||
mapSet:({v})=>{if(!['auto','2d'].includes(v))return;mapGl(v==='auto');refreshSettings();},
|
||||
animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();},
|
||||
soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();},
|
||||
langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();},
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ Object.assign(ACT,{
|
|||
settings:()=>{UI.setOpen=true;openModal(settingsHtml());},
|
||||
settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();},
|
||||
prefSet:({v})=>{const [k,b]=String(v).split(':');if(!own(PREF_DEF,k))return;setPref(k,b==='1');sfx('click');refreshSettings();},
|
||||
vpSet:({v})=>{vpOn(v==='on');refreshSettings();},
|
||||
vpSet:({v})=>{diagOn(v==='on');refreshSettings();},
|
||||
resetAsk:()=>openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_a_new_network')}</h2><p class="tagline">${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(S?S.name:tr('common.your_network'))})}</p><div class="btns">${btn(tr('game_and_settings.delete_and_start_over'),'newgame',{},'red big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`),
|
||||
whatsNewShow:()=>whatsNew(true,true),
|
||||
updateNow:()=>{save(true);location.reload();},
|
||||
|
|
|
|||
|
|
@ -58,6 +58,6 @@ Object.assign(ACT,{
|
|||
// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's
|
||||
// routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone.
|
||||
// This file is the last of the actions, so every one is here to wrap.
|
||||
const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']);
|
||||
const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']);
|
||||
const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']);
|
||||
for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
/* ================= CANVAS ================= */
|
||||
const cv=$('map'),ctx=cv.getContext('2d');
|
||||
// ctx is the 2D context draw() paints with: the map's own (CTX0), or with WebGL on the overlay above the card (56-webgl.js).
|
||||
const cv=$('map'),CTX0=cv.getContext('2d');let ctx=CTX0;
|
||||
const cam={x:1050,y:330,z:0.8};
|
||||
let CW=0,CH=0,DPR=1;
|
||||
/* Installed on an iPhone home screen with a translucent status bar, iOS can report a viewport one status bar
|
||||
|
|
@ -13,15 +14,5 @@ function fixStandaloneHeight(){const R0=document.documentElement;
|
|||
R0.classList.toggle('iosfix',on);if(on)R0.style.setProperty('--app-h',sh+'px');else R0.style.removeProperty('--app-h');return on?sh:0;}
|
||||
function resize(){const ah=fixStandaloneHeight();DPR=Math.min(2,window.devicePixelRatio||1);CW=innerWidth;CH=ah||innerHeight;cv.width=CW*DPR;cv.height=CH*DPR;}
|
||||
addEventListener('resize',()=>{resize();WL.key=null;renderLeft();fitHud();});resize();
|
||||
// Viewport readout for debugging phone layouts: open the game once with ?vp in the address (or the start URL).
|
||||
function vpDebug(){let el=document.getElementById('vpdbg');if(!el){el=document.createElement('pre');el.id='vpdbg';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none';document.body.appendChild(el);
|
||||
const pr=document.createElement('div');pr.id='vpprobe';pr.style.cssText='position:fixed;visibility:hidden;padding:env(safe-area-inset-top,0px) 0 env(safe-area-inset-bottom,0px)';document.body.appendChild(pr);}
|
||||
const pr=document.getElementById('vpprobe'),cs=getComputedStyle(pr),vv=window.visualViewport,de=document.documentElement,tb=document.getElementById('tabbar').getBoundingClientRect();
|
||||
el.textContent=`inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height}\nvv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\nstandalone ${navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches)} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}`;}
|
||||
let VP_T=null;const vpOn=on=>{clearInterval(VP_T);VP_T=null;const el=document.getElementById('vpdbg');if(el)el.remove();if(on){VP_T=setInterval(vpDebug,500);vpDebug();}try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');}catch(e){}};
|
||||
if(/[?&]vp\b/.test(location.search))vpOn(true);else if(/[?&]novp\b/.test(location.search))vpOn(false);
|
||||
try{if(localStorage.getItem('sot-vp')==='1')vpOn(true);}catch(e){}
|
||||
// Inside an installed app there is no address bar: five quick taps on the date toggle the readout.
|
||||
{let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];vpOn(!VP_T);}});}
|
||||
// iOS settles the standalone viewport a moment after launch and after rotating.
|
||||
for(const t of [300,1000])setTimeout(()=>{resize();WL.key=null;},t);addEventListener('pageshow',()=>{resize();WL.key=null;});
|
||||
|
|
|
|||
|
|
@ -30,9 +30,10 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`<div class="setline"
|
|||
${seg(tr('settings.quiet_notifications'),'prefSet',cur('quiet'),onoff('quiet'),tr('settings.only_trouble_and_milestones_pop_up'))}
|
||||
<h3 class="sub4">${tr('settings.display_and_sound')}</h3>
|
||||
${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))}
|
||||
${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glCan()?' '+tr('settings.this_browser_cannot_so_the_map'):''))}
|
||||
${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])}
|
||||
<div class="setline"><label for="langSel">${tr('common.language')}</label>${langPick('langSel')}</div>
|
||||
${seg(tr('common.viewport_info'),'vpSet',VP_T?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_reporting_layout_bugs_shows_what'))}
|
||||
${seg(tr('settings.diagnostic_info'),'vpSet',DIAG.on?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_bug_reports_shows_your_screen'))}
|
||||
${installRow()}<div class="btns" style="margin-top:12px">${btn(tr('common.done_8dd3'),'settingsClose',{},'pink')}</div>`;}
|
||||
const refreshSettings=()=>{if(UI.setOpen)openModal(settingsHtml());};
|
||||
function animOn(){const m=UI.anim||'auto';if(m==='on')return true;if(m==='off')return false;try{return !matchMedia('(prefers-reduced-motion: reduce)').matches;}catch(e){return true;}}
|
||||
|
|
|
|||
|
|
@ -30,8 +30,9 @@ function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const
|
|||
// Cable names are drawn in one font, so each width is measured once.
|
||||
const LBW=new Map(),labW=t=>{let w=LBW.get(t);if(w===undefined)LBW.set(t,w=ctx.measureText(t).width);return w;};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>LBW.clear());}catch(e){}
|
||||
function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab);
|
||||
if(!selC&&z<1.7&&cached)return;
|
||||
function drawCables(ks){const G=glOn(),z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab)&&!G;
|
||||
// On the card the cables are drawn by glBegin(); here only their labels are left.
|
||||
if(!selC&&z<1.7&&cached)return;if(G&&!selC&&z<1.7)return;
|
||||
ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';
|
||||
// Labels that would sit on another, or on a segment shorter than the name, are left out (a selected city's always show).
|
||||
// Placed labels go in a 64px grid, so each check only looks at its neighbours.
|
||||
|
|
@ -41,8 +42,8 @@ function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.dra
|
|||
for(let cx=c0;cx<=c1;cx++)for(let cy=r0;cy<=r1;cy++){const k=cx*8192+cy;let o=LG.get(k);if(!o)LG.set(k,o=[]);o.push(b);}return true;};
|
||||
const ar=arOn();for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;const col=cableCol(C);
|
||||
for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]<mn)mn=q[0];if(q[0]>mx)mx=q[0];}if(mx<-20||mn>CW+20)continue;
|
||||
if(hot||!cached){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);ctx.stroke();ctx.setLineDash([]);}
|
||||
if((hot||(z>=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);}
|
||||
if(!G&&(hot||!cached)){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);ctx.stroke();ctx.setLineDash([]);}
|
||||
if((hot||(z>=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,'rgba(255,255,255,.85)',3,m[0],m[1]-8);}
|
||||
ctx.globalAlpha=1;}}}
|
||||
function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit;
|
||||
const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;}
|
||||
|
|
|
|||
17
src/game/96-map/55-link-look.js
Normal file
17
src/game/96-map/55-link-look.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
/* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in
|
||||
58-webgl-links.js), so they cannot drift apart. */
|
||||
// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable.
|
||||
const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5]];
|
||||
// A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash.
|
||||
function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
|
||||
const cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby);
|
||||
return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)),
|
||||
col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:bld?3:idle?4:0,
|
||||
pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills
|
||||
// The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the
|
||||
// links and with the day's routing (R), not with the camera, so it is kept until one of those changes.
|
||||
let MLK=null;
|
||||
function mapLinks(day){const key=[S.links,S.links.length,R,day];
|
||||
if(MLK&&key.every((v,i)=>v===MLK.key[i]))return MLK;
|
||||
const PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0]))));
|
||||
return MLK={key,PI,LG,GM,looks:LG.map(g=>linkLook(g,day))};}
|
||||
100
src/game/96-map/56-webgl.js
Normal file
100
src/game/96-map/56-webgl.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
/* The map on the graphics card (WebGL2), wherever the browser can; Settings › Map drawing › Always 2D keeps the 2D
|
||||
canvas instead (a choice per device). A late-game map sends the 2D canvas several strokes per tube every frame (thousands on a
|
||||
big network) and repaints the land whenever you pan; here the card draws it all from buffers that change only with
|
||||
the network, so a frame costs the processor a few draws and uniforms.
|
||||
Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and
|
||||
packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for
|
||||
the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used.
|
||||
Puzzles, and any browser without WebGL2 or whose context fails, keep the 2D map; a lost context, until it is back. So does WebGL drawn by
|
||||
the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs
|
||||
microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */
|
||||
const GLX={want:true,dead:false,lost:false,sleep:false,losses:0,lose:null,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''};
|
||||
try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){}
|
||||
// Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark).
|
||||
const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i;
|
||||
const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit();
|
||||
// Whether the card can draw the map, as far as is known without asking it: Settings says so without making a context
|
||||
// (on the title screen or in a puzzle that made the 64 MB atlas for a map drawn in 2D). A card not tried yet counts as able.
|
||||
const glCan=()=>!GLX.dead&&typeof WebGL2RenderingContext!=='undefined';
|
||||
// Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not.
|
||||
// Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back.
|
||||
function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){}
|
||||
if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}}
|
||||
GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;}
|
||||
function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;}
|
||||
// Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame.
|
||||
function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;}
|
||||
function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true;
|
||||
const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);}
|
||||
/* The card given up for good (not Always 2D: glSleep()) still held what was sent to it, the atlas alone
|
||||
64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go
|
||||
(WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps
|
||||
the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */
|
||||
function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf);
|
||||
const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){}
|
||||
GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;}
|
||||
/* A lost context comes back. The browser may lose it (a driver reset; on a phone, sometimes just leaving the app) and
|
||||
give it back (webglcontextrestored): the 2D map draws meanwhile, and everything on the card is built again on the
|
||||
same context, as for the first frame. A card lost more than GL_LOSSES times is given up for the session, so a card
|
||||
that keeps failing does not keep the map switching. Always 2D lets the context go the same way (WEBGL_lose_context)
|
||||
and Auto asks for it back, so 64 MB of atlas and the rest are not held for a map that is not drawn. */
|
||||
const GL_LOSSES=2;
|
||||
// Forgets what was on the card (the context itself is kept): glInit() builds it all again.
|
||||
function glForget(){GLX.gl=null;spritesDrop();GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;Object.assign(GLX,{tex:null,land:{},ckey:null,key:[]});glShow(false);UI.drawnAt=0;}
|
||||
function glLost(e){if(GLX.dead)return;e.preventDefault();if(GLX.lost)return; // let go by Always 2D (glSleep())
|
||||
if(++GLX.losses>GL_LOSSES){glKill('the graphics context was lost '+GLX.losses+' times');return;}
|
||||
GLX.lost=true;glForget();}
|
||||
function glRestored(){if(GLX.dead)return;GLX.lost=false;glForget();if(!GLX.want)glSleep();}
|
||||
// Always 2D: lets the context go, unless the browser has it already (its restore then finds Always 2D and lets it go).
|
||||
function glSleep(){const L=GLX.lose;if(!GLX.ctx||GLX.dead||!L||typeof L.restoreContext!=='function')return;
|
||||
if(GLX.lost){GLX.sleep=true;return;}glForget();GLX.sleep=GLX.lost=true;try{L.loseContext();}catch(e){GLX.sleep=GLX.lost=false;}}
|
||||
/* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for
|
||||
getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big
|
||||
uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never
|
||||
every frame: each read waits for the card. Up to four flags are read, as one call returns only one. */
|
||||
function glMem(gl,what){for(let i=0;i<4;i++){const e=gl.getError();if(!e||e===gl.CONTEXT_LOST_WEBGL)return;
|
||||
if(e===gl.OUT_OF_MEMORY)throw glErr(new Error('the graphics card is out of memory ('+what+')'));}}
|
||||
const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n';
|
||||
// Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing).
|
||||
const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n';
|
||||
function glProg(gl,vs,fs){const sh=(t,s)=>{const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))throw new Error('shader: '+gl.getShaderInfoLog(x));return x;};
|
||||
const p=gl.createProgram();gl.attachShader(p,sh(gl.VERTEX_SHADER,vs));gl.attachShader(p,sh(gl.FRAGMENT_SHADER,fs));gl.linkProgram(p);
|
||||
if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw new Error('link: '+gl.getProgramInfoLog(p));
|
||||
const u={},n=gl.getProgramParameter(p,gl.ACTIVE_UNIFORMS);for(let i=0;i<n;i++){const a=gl.getActiveUniform(p,i);u[a.name]=gl.getUniformLocation(p,a.name);}return {p,u};}
|
||||
// A vertex array and its buffer: attributes of the given sizes (in floats), interleaved, one record per instance
|
||||
// (div 1) or per vertex (div 0), filled with data if given.
|
||||
function glVao(gl,sizes,div=1,data=null){const v=gl.createVertexArray(),b=gl.createBuffer(),stride=sizes.reduce((a,x)=>a+x,0)*4;
|
||||
gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
|
||||
let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;});
|
||||
gl.bindVertexArray(null);return {v,b};}
|
||||
function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false;
|
||||
try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers');
|
||||
const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'});
|
||||
if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl;
|
||||
if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}}
|
||||
try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){}
|
||||
if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu);
|
||||
const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)};
|
||||
// The tubes' points for the packets: floats read with texelFetch, never filtered.
|
||||
const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST);
|
||||
glsInit(gl);
|
||||
// The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every
|
||||
// frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself.
|
||||
const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype;
|
||||
if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}}
|
||||
const V=s=>glVao(gl,s);
|
||||
Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;}
|
||||
catch(e){glKill(e);return false;}}
|
||||
// Colours as [r,g,b,a] from '#rrggbb', '#rgb' or 'rgba(r,g,b,a)', kept by string.
|
||||
const GLCOL=new Map();
|
||||
function glColor(s){let v=GLCOL.get(s);if(v)return v;let r=0,g=0,b=0,a=1;
|
||||
if(s[0]==='#'){let h=s.slice(1);if(h.length===3)h=h.replace(/./g,x=>x+x);r=parseInt(h.slice(0,2),16)/255;g=parseInt(h.slice(2,4),16)/255;b=parseInt(h.slice(4,6),16)/255;}
|
||||
else{const m=/rgba?\(([^)]*)\)/.exec(s);if(m){const p=m[1].split(',').map(x=>parseFloat(x));r=p[0]/255;g=p[1]/255;b=p[2]/255;a=p.length>3?p[3]:1;}}
|
||||
v=[r,g,b,a];GLCOL.set(s,v);return v;}
|
||||
// Sets a line or a point program's view for copy k of the map (wm: the line width multiplier).
|
||||
function glSet(gl,P,k,wm){gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.uniform1f(P.u.uWMul,wm);gl.uniform1f(P.u.uDpr,DPR);}
|
||||
// A full-screen fill, from one premultiplied colour at the bottom to another at the top (the sea), or of one colour
|
||||
// (the land and the clouds, through the stencil).
|
||||
const FILL_VS=GL_HEAD+`void main(){vec2 p=vec2((gl_VertexID&1)==0?-1.:1.,(gl_VertexID&2)==0?-1.:1.);gl_Position=vec4(p,0.,1.);}`;
|
||||
const FILL_FS=GL_HEAD+`uniform vec4 uTop,uBot;uniform float uH;out vec4 o;void main(){o=mix(uBot,uTop,gl_FragCoord.y/uH);}`;
|
||||
function glFill(gl,top,bot=top){const P=GLX.fill;gl.useProgram(P.p);gl.uniform4fv(P.u.uTop,top);gl.uniform4fv(P.u.uBot,bot);gl.uniform1f(P.u.uH,GLX.c.height);gl.bindVertexArray(GLX.empty);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}
|
||||
126
src/game/96-map/57-webgl-background.js
Normal file
126
src/game/96-map/57-webgl-background.js
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
/* The background on the card, painted first each frame: the sea, the land, the waves, the clouds and the cables, as
|
||||
the 2D map paints them (drawFrame(), paintWorld()) and in the same colours. The land and the cables are geometry
|
||||
built once, so panning and zooming repaint nothing; only the waves and the clouds move. */
|
||||
const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends
|
||||
const SEA_TOP=glPm('#62CBEA'),SEA_BOT=glPm('#43AED6'),CLOUD_COL=glPm('rgba(255,255,255,.55)');
|
||||
const LAND_SHADOW=glPm('rgba(20,90,130,.35)'),LAND_GRASS=glPm('#9BDA6C'),HILL_COL=glPm('#86CB5B'),HILL_SHINE=glPm('rgba(255,255,255,.18)');
|
||||
// The land's fill: a fan of triangles per coastline, counted in the stencil (how many times the coasts wind round each
|
||||
// pixel: glLandFill()), then one cover where the count is not zero. uOff shifts it in CSS px (the shadow).
|
||||
const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam;
|
||||
void main(){gl_Position=clip((aV-uCam.xy)*uCam.z+uView*.5+uOff,uView,0.);}`;
|
||||
const FAN_FS=GL_HEAD+`out vec4 o;void main(){o=vec4(0.);}`;
|
||||
// Ellipses (the hills and their shine): centre and radii in map units, one premultiplied colour, smooth edges.
|
||||
const ELL_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aE;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out vec2 vr;
|
||||
void main(){vec2 c=(aE.xy-uCam.xy)*uCam.z+uView*.5,r=aE.zw*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m.x:m.x,(gl_VertexID&2)==0?-m.y:m.y);vr=r;gl_Position=clip(c+vq,uView,0.);}`;
|
||||
const ELL_FS=GL_HEAD+`in vec2 vq;flat in vec2 vr;uniform vec4 uCol;uniform float uDpr;out vec4 o;
|
||||
void main(){float d=(length(vq/vr)-1.)*min(vr.x,vr.y),a=clamp(.5-d*uDpr,0.,1.);if(a<=0.)discard;o=uCol*a;}`;
|
||||
// Discs for the stencil only (the clouds' puffs): centre and radius in map units.
|
||||
const CIRC_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aC;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out float vr;
|
||||
void main(){vec2 c=(aC.xy-uCam.xy)*uCam.z+uView*.5;float r=aC.z*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vr=r;gl_Position=clip(c+vq,uView,0.);}`;
|
||||
const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(length(vq)>vr)discard;o=vec4(1.);}`;
|
||||
/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does) and per zoom level
|
||||
lv (powers of 2): the fan for the fills, the coastlines as line segments (paintWorld()'s curves, four segments each)
|
||||
for the sand and the dark edge, and the hills. Zoomed out a coastline has far more points than pixels, and its
|
||||
vertices were most of the card's work: at level lv it is simplified so that no point moves more than COAST_TOL px at
|
||||
the level's zoom (Douglas-Peucker). Without lv, the whole coastline. COAST and onLand() are not touched.
|
||||
Each level stays on the card once built (GLX.land, freed with the card): from 0.4 MB zoomed out to 3 MB at the
|
||||
closest zoom, about 15 MB if a game visits every zoom, so zooming back never builds one again mid-gesture. */
|
||||
const COAST_TOL=0.25,COASTP=[];
|
||||
// A coastline as paintWorld() draws it (smoothPath(): a quadratic curve from the middle of each side to the next,
|
||||
// through the corner between them), four segments per curve; the first point is repeated at the end.
|
||||
function coastPts(ri){let P=COASTP[ri];if(P)return P;const ring=COAST[ri],n=ring.length;P=[];
|
||||
const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(ring[n-1],ring[0]);P.push(m);
|
||||
for(let i=0;i<n;i++){const c=ring[i],e=mid(c,ring[(i+1)%n]);for(let j=1;j<=4;j++){const t=j/4,u=1-t;P.push([u*u*m[0]+2*u*t*c[0]+t*t*e[0],u*u*m[1]+2*u*t*c[1]+t*t*e[1]]);}m=e;}
|
||||
return COASTP[ri]=P;}
|
||||
// The points of P to keep so that none of the others is further than tol from the line kept (Douglas-Peucker).
|
||||
function coastSimplify(P,tol){const n=P.length;if(n<4||!(tol>0))return P;const keep=new Uint8Array(n),st=[0,n-1],t2=tol*tol;keep[0]=keep[n-1]=1;
|
||||
while(st.length){const b=st.pop(),a=st.pop(),ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;let m=-1,md=t2;
|
||||
for(let i=a+1;i<b;i++){let t=((P[i][0]-ax)*dx+(P[i][1]-ay)*dy)/L;t=t<0?0:t>1?1:t;const ex=ax+t*dx-P[i][0],ey=ay+t*dy-P[i][1],d=ex*ex+ey*ey;if(d>md){md=d;m=i;}}
|
||||
if(m>=0){keep[m]=1;st.push(a,m,m,b);}}
|
||||
const o=[];for(let i=0;i<n;i++)if(keep[i])o.push(P[i]);return o;}
|
||||
// The zoom level the land is drawn at: 2^lv ≤ zoom < 2^(lv+1). Zooming in takes the finer level at once; zooming out
|
||||
// keeps the finer one (only more points, never less detail) until the zoom is 10 % under it, so a zoom that hovers
|
||||
// around a power of 2 does not switch back and forth.
|
||||
function coastLevel(z){const want=Math.floor(Math.log2(Math.max(z,1/64))),cur=GLX.coastLv;
|
||||
if(cur===undefined||want>cur||z<Math.pow(2,cur)/1.1)GLX.coastLv=want;return GLX.coastLv;}
|
||||
/* A coastline as a fan of triangles from its first point, all turned the same way (anticlockwise on the map): summed
|
||||
with their signs, they count how many times the coast winds round each point. Every coast counts +1 inside, so where
|
||||
two coasts overlap (Timor is drawn twice) the land is 2, still land, as each coast filled on its own in 2D. */
|
||||
function coastFan(P,out){let a=0;const n=P.length;for(let i=0;i<n;i++){const p=P[i],q=P[(i+1)%n];a+=p[0]*q[1]-q[0]*p[1];}
|
||||
const s=a<0?1:0;for(let i=1;i+1<n;i++){const b=P[i+s],c=P[i+1-s];out.push(P[0][0],P[0][1],b[0],b[1],c[0],c[1]);}return out;}
|
||||
function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@'+lv);let G=GLX.land[key];if(G)return G;
|
||||
const keep=far?new Set(LANDP_FAR):null,tol=lv===undefined?0:COAST_TOL/Math.pow(2,lv),fan=[],sand=[],edge=[],SAND=glColor('#F8E6A8'),EDGE=glColor('#1E2640');
|
||||
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+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 F=a=>new Float32Array(a);
|
||||
G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE,
|
||||
hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};
|
||||
glMem(gl,'the land');return GLX.land[key]=G;}
|
||||
// Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map.
|
||||
// The stencil counts the coasts' windings (+1 for a triangle facing one way, -1 the other: coastFan()), as the 2D
|
||||
// canvas's nonzero rule does; counting only odd or even made two overlapping coasts cancel out into sea.
|
||||
function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST);
|
||||
gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan);
|
||||
gl.colorMask(false,false,false,false);gl.stencilFunc(gl.ALWAYS,0,255);gl.stencilMask(255);
|
||||
gl.stencilOpSeparate(gl.FRONT,gl.KEEP,gl.KEEP,gl.INCR_WRAP);gl.stencilOpSeparate(gl.BACK,gl.KEEP,gl.KEEP,gl.DECR_WRAP);
|
||||
for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArrays(gl.TRIANGLES,0,G.nFan);}
|
||||
// The cover paints where the count is not zero and sets the stencil back to zero for the next user.
|
||||
gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,255);gl.stencilOp(gl.ZERO,gl.ZERO,gl.ZERO);
|
||||
glFill(gl,col);gl.disable(gl.STENCIL_TEST);}
|
||||
function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col);
|
||||
for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}
|
||||
// In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline.
|
||||
function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z));
|
||||
glLandFill(gl,G,ks,5,7,LAND_SHADOW);
|
||||
glLines(gl,G.sand,G.nSeg,ks);
|
||||
glLandFill(gl,G,ks,0,0,LAND_GRASS);
|
||||
glEllipses(gl,G.hills,G.nHill,ks,HILL_COL);glEllipses(gl,G.shine,G.nHill,ks,HILL_SHINE);
|
||||
glLines(gl,G.edge,G.nSeg,ks);}
|
||||
// The waves: each one two quadratic curves of four segments, swaying with the map's clock as in drawFrame(). They are
|
||||
// written into the same array every frame (no garbage for the collector to pick up while you play).
|
||||
const WAVE_COL=glColor('rgba(255,255,255,.45)');
|
||||
function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0;
|
||||
for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;
|
||||
// Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame).
|
||||
for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y;
|
||||
for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}}
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);}
|
||||
// The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack.
|
||||
function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)return;
|
||||
// Written into one array kept from frame to frame, grown when more copies of the map show.
|
||||
if(!GLX.ca||GLX.ca.length<need)GLX.ca=new Float32Array(need);const A=GLX.ca;let n=0;
|
||||
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,s=c.s;
|
||||
A[n++]=x;A[n++]=y;A[n++]=16*s;A[n++]=0;A[n++]=x+18*s;A[n++]=y-8*s;A[n++]=20*s;A[n++]=0;A[n++]=x+40*s;A[n++]=y;A[n++]=15*s;A[n++]=0;}
|
||||
const F=A.subarray(0,n),P=GLX.circ;gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cl.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW);
|
||||
gl.enable(gl.STENCIL_TEST);gl.stencilFunc(gl.ALWAYS,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE);gl.colorMask(false,false,false,false);
|
||||
gl.useProgram(P.p);gl.bindVertexArray(GLX.cl.v);gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,F.length/4);
|
||||
gl.colorMask(true,true,true,true);gl.stencilFunc(gl.EQUAL,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);glFill(gl,CLOUD_COL);gl.disable(gl.STENCIL_TEST);}
|
||||
// The cables, as drawCables() strokes them: rebuilt only when the highlighted city or the architect view changes.
|
||||
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+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);glMem(gl,'the cables');GLX.cn=F.length/LINE_STRIDE;GLX.ckey=key;}
|
||||
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
|
||||
// (glsFrameEnd()); draw() paints anything else on the overlay, which becomes ctx until the frame ends.
|
||||
function glBegin(now,ks){const gl=GLX.gl,c=GLX.c,f=GLX.f;glShow(true);GLS.frame=true;
|
||||
if(c.width!==cv.width||c.height!==cv.height){c.width=f.width=cv.width;c.height=f.height=cv.height;}
|
||||
// The 2D map under the card stays empty: it is cleared once, not every frame.
|
||||
if(!GLX.c0clean){CTX0.setTransform(1,0,0,1,0,0);CTX0.clearRect(0,0,cv.width,cv.height);GLX.c0clean=true;}
|
||||
gl.viewport(0,0,c.width,c.height);gl.clearColor(0,0,0,0);gl.clearDepth(1);gl.clearStencil(0);gl.colorMask(true,true,true,true);gl.depthMask(true);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT|gl.STENCIL_BUFFER_BIT);
|
||||
gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST);gl.disable(gl.STENCIL_TEST);
|
||||
glFill(gl,SEA_TOP,SEA_BOT);
|
||||
glLand(gl,ks);
|
||||
glWaves(gl,now,ks);
|
||||
glClouds(gl,now,ks);
|
||||
const selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null);
|
||||
glCables(gl,ks,selC,arOn());
|
||||
const fx=GLX.fx;if(GLX.fxUsed){fx.setTransform(1,0,0,1,0,0);fx.clearRect(0,0,f.width,f.height);GLX.fxUsed=false;}
|
||||
ctx=fx;ctx.setTransform(DPR,0,0,DPR,0,0);}
|
||||
95
src/game/96-map/58-webgl-links.js
Normal file
95
src/game/96-map/58-webgl-links.js
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
/* The tubes on the card: every tube is one instanced draw per layer (halo, casing, colour, fiber dots, packets), and
|
||||
the packets travel their paths in the vertex shader, so a frame costs a few uniforms however many tubes there are.
|
||||
The buffers are rebuilt only when the network, the routing or the day change; a selection only rebuilds the halo,
|
||||
a buffer of the selected tube's own segments. Depth stands in for
|
||||
the 2D painting order: a later tube's casing still covers an earlier tube's colour and packets. */
|
||||
// The line program's passes: a tube's layers in drawFrame()'s order, and plain lines (coasts, waves, cables).
|
||||
const LP={halo:0,casing:1,colour:2,dots:3,plain:4};
|
||||
// A segment's flags: on the selected tube, lit fiber (its dots show), round ends for a plain line.
|
||||
const LINE_SEL=1,LINE_FIBER=2,LINE_ROUND=4;
|
||||
/* One segment is 12 floats: x0,y0,x1,y1 (map units) | the length before it, width (CSS px), dash (LDASH), flags |
|
||||
a, r,g,b, where a is the depth for a tube and the opacity for a plain line. */
|
||||
const LINE_STRIDE=12;
|
||||
function glSegAt(A,i,ax,ay,bx,by,cum,w,dash,fl,a,col){const o=i*LINE_STRIDE;
|
||||
A[o]=ax;A[o+1]=ay;A[o+2]=bx;A[o+3]=by;A[o+4]=cum;A[o+5]=w;A[o+6]=dash;A[o+7]=fl;A[o+8]=a;A[o+9]=col[0];A[o+10]=col[1];A[o+11]=col[2];}
|
||||
function glSeg(A,p,q,cum,w,dash,fl,col){A.push(p[0],p[1],q[0],q[1],cum,w,dash,fl,col[3],col[0],col[1],col[2]);}
|
||||
/* 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;
|
||||
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;
|
||||
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;
|
||||
if(uPass==${LP.halo}){hw=(w+14.)*.5;col=vec4(1.,79./255.,154./255.,.35);dash=vec2(0.);skip=(fl&${LINE_SEL})==0;}
|
||||
else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(30./255.,38./255.,64./255.,1.);}
|
||||
else if(uPass==${LP.dots}){hw=max(1.,w*.25)*.5;col=vec4(1.,1.,1.,.75);dash=dashOf(5);skip=(fl&${LINE_FIBER})==0||uBusy>.5;}
|
||||
else if(uPass==${LP.plain})col.a=aC.x;
|
||||
if(skip){gl_Position=vec4(2.,2.,2.,1.);return;}
|
||||
vec2 d=b-a;float L=length(d);vec2 t=L>1e-4?d/L:vec2(1.,0.),n=vec2(-t.y,t.x);float m=hw+1./uDpr;
|
||||
float sx=(gl_VertexID&1)==0?-m:L+m,sy=(gl_VertexID&2)==0?-m:m;
|
||||
vLoc=vec2(sx,sy);vLen=L;vS0=aP.x*uCam.z;vHalf=hw;vCol=col;vDash=dash;vButt=uPass==${LP.plain}&&(fl&${LINE_ROUND})==0?1.:0.;
|
||||
gl_Position=clip(a+t*sx+n*sy,uView,(uPass==${LP.plain}?.9998:aC.x)*2.-1.);}`;
|
||||
const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol;flat in vec2 vDash;uniform float uDpr;out vec4 o;
|
||||
void main(){float x=vLoc.x,y=vLoc.y,d;
|
||||
if(vButt>.5&&(x<0.||x>vLen))discard;
|
||||
if(vDash.x<=0.){float c=clamp(x,0.,vLen);d=length(vec2(x-c,y));}
|
||||
else{float P=vDash.x+vDash.y,g=vS0+x,k=floor(g/P);d=1e9;
|
||||
for(int i=-1;i<=1;i++){float a0=(k+float(i))*P,lo=max(a0,vS0),hi=min(a0+vDash.x,vS0+vLen);if(lo<=hi){float c=clamp(g,lo,hi);d=min(d,length(vec2(g-c,y)));}}}
|
||||
float al=clamp((vHalf-d)*uDpr+.5,0.,1.);if(al<=0.)discard;o=vec4(vCol.rgb*vCol.a*al,vCol.a*al);}`;
|
||||
// Plain lines (coasts, waves, cables): colour and opacity from the data, flat ends unless LINE_ROUND, under the tubes.
|
||||
function glLines(gl,vao,n,ks){const L=GLX.line;gl.useProgram(L.p);gl.bindVertexArray(vao);gl.uniform1i(L.u.uPass,LP.plain);gl.uniform1f(L.u.uBusy,0);
|
||||
for(const k of ks){glSet(gl,L,k,1);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}
|
||||
/* Packets: one instance per packet; where it is on its tube comes from the tube's points (a float texture of x, y and
|
||||
the share of the length so far, GL_PTS_W texels a row), found by bisection the way polyAtXY() finds it. */
|
||||
const GL_PTS_W=2048;
|
||||
const GL_PK_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aK;layout(location=1) in vec4 aQ;
|
||||
uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uT,uFar;uniform highp sampler2D uPts;
|
||||
out vec2 vLoc;flat out float vR,vLw;
|
||||
vec4 P(int i){return texelFetch(uPts,ivec2(i%${GL_PTS_W},i/${GL_PTS_W}),0);}
|
||||
void main(){float n=uFar>.5?max(1.,floor(aK.w*.5)):aK.w,i=aQ.x;if(i>=n){gl_Position=vec4(2.,2.,2.,1.);return;}
|
||||
float t=fract(uT*90./max(aK.z*uCam.z,40.)+i/n);if(mod(i,2.)>.5)t=1.-t;
|
||||
int o=int(aK.x+.5),lo=1,hi=int(aK.y+.5)-1;for(int s=0;s<16&&lo<hi;s++){int md=(lo+hi)/2;if(P(o+md).z<t)lo=md+1;else hi=md;}
|
||||
vec4 p0=P(o+lo-1),p1=P(o+lo);float f=p1.z>p0.z?(t-p0.z)/(p1.z-p0.z):0.;vec2 c=(mix(p0.xy,p1.xy,f)-uCam.xy)*uCam.z+uView*.5;
|
||||
float w=aQ.y*uWMul,r=uFar>.5?1.6:max(2.2,w*.42),lw=uFar>.5?1.:1.5,m=r+lw*.5+1./uDpr;
|
||||
vec2 q=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vLoc=q;vR=r;vLw=lw;
|
||||
gl_Position=clip(c+q,uView,aQ.z*2.-1.);}`;
|
||||
const GL_PK_FS=GL_HEAD+`in vec2 vLoc;flat in float vR,vLw;uniform float uDpr;out vec4 o;
|
||||
void main(){float d=length(vLoc),out_=clamp((vR+vLw*.5-d)*uDpr+.5,0.,1.);if(out_<=0.)discard;
|
||||
float inn=clamp((vR-vLw*.5-d)*uDpr+.5,0.,1.);vec3 c=mix(vec3(30./255.,38./255.,64./255.),vec3(1.),inn);o=vec4(c*out_,out_);}`;
|
||||
/* The tubes as instance data: their segments (see LINE_STRIDE; later tubes are nearer), their packets (first point,
|
||||
points, length, packets | which, base width, depth, -), and every tube's points in the texture. */
|
||||
const glDepth=(gi,N)=>1-(gi+1)/(N+2);
|
||||
function glBuild(LG,GM,looks){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0;
|
||||
for(let gi=0;gi<N;gi++){ns+=GM[gi].pts.length-1;np+=GM[gi].pts.length;nk+=looks[gi].pk;}
|
||||
const SEG=new Float32Array(ns*LINE_STRIDE),PK=new Float32Array(nk*8),TH=Math.max(1,Math.ceil(np/GL_PTS_W)),PT=new Float32Array(GL_PTS_W*TH*4);
|
||||
let si=0,ki=0,pi=0;
|
||||
for(let gi=0;gi<N;gi++){const L=looks[gi],{pts,cum,len}=GM[gi],dep=glDepth(gi,N),col=glColor(L.col);
|
||||
const fl=L.df&&!L.bld&&!L.dark?LINE_FIBER:0,p0=pi;
|
||||
for(let j=0;j<pts.length;j++){PT[pi*4]=pts[j][0];PT[pi*4+1]=pts[j][1];PT[pi*4+2]=cum[j];pi++;}
|
||||
for(let j=0;j+1<pts.length;j++)glSegAt(SEG,si++,pts[j][0],pts[j][1],pts[j+1][0],pts[j+1][1],cum[j]*len,L.w0,L.dash,fl,dep,col);
|
||||
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.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);glMem(gl,'the tubes');
|
||||
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.
|
||||
function glHalo(LG,GM,looks,selId){const gl=GLX.gl,N=LG.length,A=[];
|
||||
if(selId)for(let gi=0;gi<N;gi++){if(!LG[gi].some(x=>x.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<pts.length;j++)A.push(pts[j][0],pts[j][1],pts[j+1][0],pts[j+1][1],cum[j]*len,L.w0,L.dash,LINE_SEL,dep,col[0],col[1],col[2]);}
|
||||
const F=new Float32Array(A);if(F.length){gl.bindBuffer(gl.ARRAY_BUFFER,GLX.hv.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW);}
|
||||
GLX.nHalo=F.length/LINE_STRIDE;return F;}
|
||||
// Draws the tubes and their packets over the background glBegin() painted (ML: mapLinks(), sc: the icon scale).
|
||||
function glFrame(ML,ks,far,busy,now,sc){const gl=GLX.gl;
|
||||
const selId=UI.sel&&UI.sel.type==='link'?UI.sel.id:'',net=GLX.key[0]!==ML;
|
||||
if(net)glBuild(ML.LG,ML.GM,ML.looks);
|
||||
if(net||GLX.key[1]!==selId){glHalo(ML.LG,ML.GM,ML.looks,selId);GLX.key=[ML,selId];}
|
||||
gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.depthMask(true);
|
||||
const L=GLX.line,K=GLX.pk,wm=sc*(far?0.5:1),lines=(pass,v=GLX.lv.v,n=GLX.nSeg)=>{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass);
|
||||
for(const k of ks){glSet(gl,L,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}};
|
||||
if(GLX.nSeg)for(const pass of [LP.casing,LP.colour,LP.dots])lines(pass);
|
||||
if(GLX.nPk){gl.useProgram(K.p);gl.bindVertexArray(GLX.pv.v);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.uniform1i(K.u.uPts,0);
|
||||
gl.uniform1f(K.u.uT,now/1000);gl.uniform1f(K.u.uFar,far?1:0);for(const k of ks){glSet(gl,K,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,GLX.nPk);}}
|
||||
// The selection's halo goes over earlier tubes but under its own line and later ones, as in 2D.
|
||||
if(GLX.nHalo){gl.depthFunc(gl.LESS);gl.depthMask(false);lines(LP.halo,GLX.hv.v,GLX.nHalo);gl.depthMask(true);}
|
||||
gl.bindVertexArray(null);}
|
||||
151
src/game/96-map/59-gl-sprites.js
Normal file
151
src/game/96-map/59-gl-sprites.js
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
/* Pictures on the card. Cities, labels, markers and everything that bobs or pulses on them (cones, ships, offer
|
||||
bubbles, hot badges, floaters) are painted once with the 2D canvas, packed into one texture (the atlas), and drawn
|
||||
as instanced quads, with the small round things (lights, steam, glows) as discs, in one draw per frame after the
|
||||
tubes. Without WebGL the same calls draw the pictures with the 2D canvas, so the map's code does not care which. */
|
||||
const SPR_MAX=1400,SPR_STRIDE=13;
|
||||
// The card's pictures (SPRS) and the 2D map's (SPRC), by key; both at the screen's pixel density SPR_DPR.
|
||||
const SPRS=new Map(),SPRC=new Map();let SPR_DPR=0;
|
||||
/* The 2D map's pictures each keep a canvas, so they are also held to a size: a long zoom on a big network paints every
|
||||
city again at each step, and the list (only capped at SPR_MAX) held up to 180 MB of them where a frame shows 2 to
|
||||
23 MB. At the end of a frame over SPRC_BUDGET bytes, the pictures it did not use go, those unused the longest first,
|
||||
down to 3/4 of the budget (so this happens once in a while, not every frame). The frame's own are always kept: a
|
||||
screen that needs more than the budget keeps what it needs. A canvas let go is emptied (0×0) at once, which frees
|
||||
its pixels without waiting for the collector. The card's atlas has its own fixed size (GLS.size).
|
||||
SPR_F counts frames (draw()); finding or drawing a picture marks it as used in this one (e.f). */
|
||||
const SPRC_BUDGET=48*1048576;let SPRC_B=0,SPR_F=0;
|
||||
const sprFree=e=>{if(e.cv){e.cv.width=e.cv.height=0;e.cv=null;}};
|
||||
function sprcTrim(){if(SPRC_B<=SPRC_BUDGET)return;const old=[];for(const [k,e] of SPRC)if(e.f<SPR_F)old.push([e.f,k,e]);
|
||||
old.sort((a,b)=>a[0]-b[0]);const goal=SPRC_BUDGET*0.75;
|
||||
for(const [,k,e] of old){if(SPRC_B<=goal)break;SPRC.delete(k);SPRC_B-=e.pw*e.ph*4;sprFree(e);}}
|
||||
const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0,upq:false,memT:-1e9};
|
||||
/* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its
|
||||
colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */
|
||||
const SPR_VS=GL_HEAD+`layout(location=0) in vec4 aP;layout(location=1) in vec4 aUV;layout(location=2) in vec4 aC;layout(location=3) in float aK;
|
||||
uniform vec2 uDev;uniform float uDpr;out vec2 vUV,vQ;out vec4 vC;flat out float vK,vR;
|
||||
void main(){vec2 c=vec2((gl_VertexID&1)==0?0.:1.,(gl_VertexID&2)==0?0.:1.),p;
|
||||
if(aK>.5){float m=aP.z+1./uDpr;vQ=(c*2.-1.)*m;vR=aP.z;vUV=vec2(0.);p=aP.xy+vQ;}
|
||||
else{vQ=vec2(0.);vR=0.;vUV=mix(aUV.xy,aUV.zw,c);p=aP.xy+c*aP.zw;}
|
||||
vC=aC;vK=aK;gl_Position=vec4(p.x*uDpr/uDev.x*2.-1.,1.-p.y*uDpr/uDev.y*2.,0.,1.);}`;
|
||||
const SPR_FS=GL_HEAD+`uniform sampler2D uTex;uniform float uDpr;in vec2 vUV,vQ;in vec4 vC;flat in float vK,vR;out vec4 o;
|
||||
void main(){if(vK>.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);}
|
||||
else o=texture(uTex,vUV)*vC.a;}`;
|
||||
function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b;
|
||||
// 4096 px square (64 MB), or what the card allows if that is less (some phones). A card that has not the memory for
|
||||
// it gets 2048 (16 MB: more resets of the atlas, the same map); without even that, the map stays 2D (glMem).
|
||||
GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);glMem(gl,'setup');
|
||||
for(GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096);;GLS.size>>=1){
|
||||
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null);
|
||||
try{glMem(gl,'the pictures');break;}catch(e){if(GLS.size<=2048)throw e;}}
|
||||
for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR);
|
||||
for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE);
|
||||
GLS.shx=GLS.shy=GLS.shh=0;GLS.memT=-1e9;GLS.upq=false;}
|
||||
// Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it).
|
||||
function spritesReset(){glsDrawNow();for(const e of SPRC.values())sprFree(e);SPRS.clear();SPRC.clear();SPRC_B=0;GLS.shx=GLS.shy=GLS.shh=0;}
|
||||
// The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten.
|
||||
function spritesDrop(){GLS.n=GLS.up=0;GLS.upq=false;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;}
|
||||
/* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a
|
||||
canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context
|
||||
and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas.
|
||||
Each picture goes in with a clear border of GLS_GAP px: the card blends the texels around the point it reads, so a
|
||||
picture drawn off whole pixels or a little stretched read half a texel past its edge, and showed a thin line of its
|
||||
neighbour in the atlas (or of a picture from before the last reset, which leaves the texture as it was). */
|
||||
const GLS_GAP=1;
|
||||
const GLS_PAD={cv:null,g:null};
|
||||
function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('canvas');P.cv.width=P.cv.height=256;}
|
||||
if(P.cv.width<pw||P.cv.height<ph){P.cv.width=Math.max(P.cv.width,Math.ceil(pw/64)*64);P.cv.height=Math.max(P.cv.height,Math.ceil(ph/64)*64);P.g=null;}
|
||||
if(!P.g)P.g=P.cv.getContext('2d',{willReadFrequently:true});return P;}
|
||||
// Where this frame's pictures are kept: the card's or the 2D map's. A new pixel density starts both again.
|
||||
function sprMap(){if(DPR!==SPR_DPR){SPR_DPR=DPR;spritesReset();}return GLS.frame&&!!GLX.gl&&!!GLS.prog?SPRS:SPRC;}
|
||||
// The picture already painted under key, if any: callers ask first, so a picture drawn every frame costs no closure.
|
||||
const spriteHas=key=>{const e=sprMap().get(key);if(e)e.f=SPR_F;return e;};
|
||||
// A picture of w×h CSS px with its anchor at (ax,ay): painted once by paint(g) (the 2D canvas, at the screen's pixel
|
||||
// density), and kept by key in SPRS (the card's) or SPRC (the 2D map's).
|
||||
function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.get(key);if(e){e.f=SPR_F;return e;}
|
||||
if(SPRS.size+SPRC.size>=SPR_MAX)spritesReset();
|
||||
const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx;
|
||||
e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1,f:SPR_F};
|
||||
const G=GLS_GAP;
|
||||
if(gpu&&pw+2*G<=GLS.size&&ph+2*G<=GLS.size){const P=glsPad(pw+2*G,ph+2*G),g=P.g;
|
||||
// Clipped to the picture, as its own canvas would be, so the border stays clear.
|
||||
g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw+2*G,ph+2*G);g.beginPath();g.rect(G,G,pw,ph);g.clip();ctx=g;
|
||||
try{g.setTransform(DPR,0,0,DPR,G,G);sprPen(g);paint(g);}finally{ctx=saved;g.restore();}
|
||||
// A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next.
|
||||
try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);}
|
||||
}else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g;
|
||||
try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;}e.cv=cv;
|
||||
if(M===SPRC)SPRC_B+=pw*ph*4;}
|
||||
M.set(key,e);return e;}
|
||||
/* A picture starts with the pen the map's own canvas has when it draws cities and markers: the tubes leave it with
|
||||
round line ends and corners, the labels with text centred on its middle. Drawn straight on the map, the dashed rings,
|
||||
the cones' tips and a sleeping POP's "zzz" took those, and a new canvas has others (square ends, text on its baseline). */
|
||||
function sprPen(g){g.lineCap='round';g.lineJoin='round';g.textAlign='center';g.textBaseline='middle';}
|
||||
// Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame.
|
||||
function glsEnsure(e){if(e.up)return true;const gl=GLX.gl,G=GLS_GAP;if(!gl||!GLS.prog||!e.cv)return false;
|
||||
if(e.pw+2*G>GLS.size||e.ph+2*G>GLS.size)return false;
|
||||
const P=glsPad(e.pw+2*G,e.ph+2*G),g=P.g;g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,e.pw+2*G,e.ph+2*G);g.drawImage(e.cv,G,G);
|
||||
try{return glsPut(gl,e,P.cv);}catch(x){throw glErr(x);}}
|
||||
// src holds the picture at (GLS_GAP,GLS_GAP), in a clear border that goes into the atlas with it.
|
||||
function glsPut(gl,e,src){const G=GLS_GAP,pw=e.pw+2*G,ph=e.ph+2*G,A=GLS.size;if(pw>A||ph>A)return false;
|
||||
if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;}
|
||||
if(GLS.shy+ph>A){spritesReset();return false;}
|
||||
const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph);
|
||||
gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true);
|
||||
// Only the picture's corner of the source (with its border): the pad is bigger than most pictures.
|
||||
gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false);
|
||||
GLS.up++;Object.assign(e,{up:true,u0:(x+G)/A,v0:(y+G)/A,u1:(x+pw-G)/A,v1:(y+ph-G)/A});return true;}
|
||||
// The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace.
|
||||
function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;}
|
||||
// Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas.
|
||||
function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const o=glsNext(),d=GLS.data;
|
||||
d[o]=x;d[o+1]=y;d[o+2]=w;d[o+3]=h;d[o+4]=e.u0;d[o+5]=e.v0;d[o+6]=e.u1;d[o+7]=e.v1;d[o+8]=d[o+9]=d[o+10]=0;d[o+11]=ctx.globalAlpha;d[o+12]=0;}
|
||||
else if(e.cv)ctx.drawImage(e.cv,x,y,w,h);}
|
||||
// A round dot of radius r at (x,y), in colour col (CSS colour string) at opacity a, on the card or the 2D canvas.
|
||||
function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),o=glsNext(),d=GLS.data;
|
||||
d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;}
|
||||
else{const sa=ctx.globalAlpha;if(a!==undefined)ctx.globalAlpha=a;ctx.fillStyle=col;ctx.beginPath();ctx.arc(x,y,r,0,7);ctx.fill();ctx.globalAlpha=sa;}}
|
||||
/* Pictures that grow with the zoom (cities, ships, badges) are painted at steps of 1/24 of their scale. On the card,
|
||||
while the zoom moves, they keep the step of the scale they had when it began, stretched by up to 1.25× either way
|
||||
(the card filters them smoothly), and are painted again at the right step once the zoom rests (ZOOM_REST ms): a
|
||||
pinch otherwise repainted every city at every step, hundreds of pictures a frame, and filled the atlas over and
|
||||
over. ZH.sc is the icon scale held, ZH.f how much a picture is painted smaller (<1) or bigger than it shows. */
|
||||
const CSPR_STEP=24,ZOOM_REST=250,ZH={z:0,t:-1e9,sc:0,f:1};
|
||||
function zoomHold(sc,G){const t=performance.now();if(cam.z!==ZH.z){ZH.z=cam.z;ZH.t=t;}
|
||||
if(!G||!ZH.sc||t-ZH.t>=ZOOM_REST||sc/ZH.sc>1.25||ZH.sc/sc>1.25)ZH.sc=sc;ZH.f=ZH.sc/sc;}
|
||||
// The zoom moved a moment ago: the pictures may be stretched, so a still map is drawn again once it rests (mapStill()).
|
||||
const zoomMoving=()=>performance.now()-ZH.t<ZOOM_REST;
|
||||
const sprQ=k=>Math.max(1/CSPR_STEP,Math.round(k*ZH.f*CSPR_STEP)/CSPR_STEP);
|
||||
// A small picture w×h px at scale k with its anchor at (ax,ay), painted once by paint(g) with the origin on the anchor
|
||||
// (k in steps of 1/24, as the cities; zoomed: k grows with the zoom, and is held while it moves, sprQ()), then drawn with
|
||||
// the anchor at (x,y). Things that bob or pulse are drawn as these at a moving place, so the overlay above the card
|
||||
// stays untouched (repainting it costs a whole screen of pixels).
|
||||
// The full key of a stamp at scale kq, kept per key: it was built again for every stamp on every frame.
|
||||
const STK=new Map();
|
||||
function stamp(key,w,h,ax,ay,k,x,y,paint,zoomed){const kq=zoomed?sprQ(k):Math.max(1/CSPR_STEP,Math.round(k*CSPR_STEP)/CSPR_STEP),r=k/kq;
|
||||
let m=STK.get(key);if(!m||m.kq!==kq){if(STK.size>4000)STK.clear();STK.set(key,m={kq,k:key+'|'+kq});}
|
||||
const e=spriteHas(m.k)||spriteEntry(m.k,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);});
|
||||
blit(e,x-e.ax*r,y-e.ay*r,e.w*r,e.h*r);}
|
||||
// Text with an outline, centred on (x,y), as a picture placed on whole device pixels; tw is its width, px its size.
|
||||
function textStamp(t,font,px,tw,fill,stroke,lw,x,y){const W=Math.ceil(tw+lw+4),H=Math.ceil(px*1.5+lw+2);
|
||||
const e=spriteEntry(['txt',t,font,fill,stroke,lw].join('|'),W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.font=font;g.textAlign='center';g.textBaseline='middle';
|
||||
if(lw){g.lineWidth=lw;g.lineJoin='round';g.strokeStyle=stroke;g.strokeText(t,0,0);}g.fillStyle=fill;g.fillText(t,0,0);});
|
||||
blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);}
|
||||
// Sends the queued pictures to the card in one draw.
|
||||
function glsDrawNow(){const gl=GLX.gl,n=GLS.n;GLS.n=0;if(!gl||!GLS.prog||!n)return;
|
||||
try{glsDraw(gl,n);}catch(x){throw glErr(x);}}
|
||||
function glsDraw(gl,n){gl.useProgram(GLS.prog.p);gl.bindVertexArray(GLS.vao);gl.bindBuffer(gl.ARRAY_BUFFER,GLS.buf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER,GLS.data.subarray(0,n*SPR_STRIDE),gl.STREAM_DRAW);
|
||||
gl.uniform2f(GLS.prog.u.uDev,GLX.c.width,GLX.c.height);gl.uniform1f(GLS.prog.u.uDpr,DPR);gl.uniform1i(GLS.prog.u.uTex,0);
|
||||
gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);
|
||||
gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST);
|
||||
gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);gl.bindVertexArray(null);}
|
||||
/* The end of a frame on the card: the pictures go up over the tubes. The frame is over even if that draw fails.
|
||||
Pictures sent are checked (did the card take them?): a card short of memory may refuse one without throwing, and the
|
||||
picture would be kept as sent. It then gives the map to 2D (glMem() throws, draw() draws the frame again there and
|
||||
glKill() forgets the card's pictures). Each read waits for the card to finish everything sent so far, so it is done
|
||||
at most once every GL_MEM_EVERY ms: the card keeps an error until it is read, so a later read still finds it, and a
|
||||
picture refused in between shows at worst as a dark box for that time. The first pictures sent into a new atlas are
|
||||
checked at once (a card that allocates it lazily refuses there). A frame that only reuses the atlas asks nothing. */
|
||||
const GL_MEM_EVERY=1000;
|
||||
function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;if(GLS.up)GLS.upq=true;GLS.up=0;
|
||||
if(GLS.upq&&GLX.gl){const t=performance.now();if(t-GLS.memT>=GL_MEM_EVERY){GLS.memT=t;GLS.upq=false;glMem(GLX.gl,'the pictures');}}
|
||||
glsDrawNow();}
|
||||
|
|
@ -1,11 +1,25 @@
|
|||
function draw(now){DFC=new Map();try{drawFrame(now);}finally{DFC=null;}}
|
||||
/* A frame. An error from the card itself (glErr()) gives WebGL up for this session and draws the same frame again in
|
||||
2D, once; any other error goes on to the loop's tickErr(). Either way the 2D context and the sprite queue are reset. */
|
||||
function draw(now){for(let pass=0;;pass++){let err=null;DFC=new Map();SPR_F++;
|
||||
try{drawFrame(now);}catch(e){err=e;}
|
||||
try{glsFrameEnd();}catch(e){if(!err)err=e;}finally{DFC=null;GLS.frame=false;GLS.n=0;ctx=CTX0;sprcTrim();}
|
||||
if(!err)return;if(!err.glErr||pass)throw err;glKill(err);}}
|
||||
// Rectangles on a 64 px grid: a new one is compared only with the few that share its cells (a plain list made the
|
||||
// label placement quadratic in the number of cities).
|
||||
class RGrid{constructor(){this.m=new Map();}
|
||||
cells(r,f){for(let cx=Math.floor(r.x/64);cx<=Math.floor((r.x+r.w)/64);cx++)for(let cy=Math.floor(r.y/64);cy<=Math.floor((r.y+r.h)/64);cy++)f(cx*100003+cy);}
|
||||
push(r){this.cells(r,k=>{const a=this.m.get(k);if(a)a.push(r);else this.m.set(k,[r]);});}
|
||||
hits(r){let h=false;this.cells(r,k=>{if(h)return;const a=this.m.get(k);if(a)for(const q of a)if(r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h){h=true;return;}});return h;}}
|
||||
function drawFrame(now){
|
||||
if(!ctx)return;
|
||||
const ks=visibleKs(),z=cam.z,G=glOn();
|
||||
// WebGL on: the sea, land, waves, clouds and cables are on the card (glBegin); the 2D canvas below them stays empty.
|
||||
// Off (2D chosen, no game, a puzzle, the card given up), its layers are hidden here, before anything can return early.
|
||||
if(G){try{glBegin(now,ks);}catch(e){throw glErr(e);}}
|
||||
else{glShow(false);GLX.c0clean=false;const wl=worldLayer(z);
|
||||
ctx.setTransform(DPR,0,0,DPR,0,0);
|
||||
// sea
|
||||
const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,'#62CBEA');g.addColorStop(1,'#43AED6');ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH);
|
||||
const ks=visibleKs(),z=cam.z;
|
||||
const wl=worldLayer(z);
|
||||
for(const k of ks){
|
||||
ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));
|
||||
// waves: one path, one stroke
|
||||
|
|
@ -19,43 +33,49 @@ function drawFrame(now){
|
|||
ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath();
|
||||
for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100,y=c.y;ctx.moveTo(x+16*c.s,y);ctx.arc(x,y,16*c.s,0,7);ctx.moveTo(x+38*c.s,y-8*c.s);ctx.arc(x+18*c.s,y-8*c.s,20*c.s,0,7);ctx.moveTo(x+55*c.s,y);ctx.arc(x+40*c.s,y,15*c.s,0,7);}ctx.fill();
|
||||
}
|
||||
}
|
||||
ctx.setTransform(DPR,0,0,DPR,0,0);
|
||||
if(!S)return;
|
||||
const sc=iconScale(),day=S.day;
|
||||
const sc=iconScale(),day=S.day;zoomHold(sc,G);
|
||||
// cable systems
|
||||
drawCables(ks);
|
||||
// links
|
||||
AR_PILLS.length=0;
|
||||
const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY;
|
||||
for(let gi=0;gi<LG.length;gi++){const grp=LG[gi],l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
|
||||
const gm=GM[gi],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 far=lodFar(),ML=mapLinks(day),LG=ML.LG,GM=ML.GM,PI=ML.PI,busy=linesOnScreen(GM,ks)>MAP_BUSY;
|
||||
// WebGL on: the card draws every line and packet now, and the rest (labels, markers, cities…) goes on the overlay.
|
||||
if(G)try{glFrame(ML,ks,far,busy,now,sc);}catch(e){throw glErr(e);}
|
||||
for(let gi=0;gi<LG.length;gi++){const grp=LG[gi],{l,many,up,cap,load,df,bld,cut,dark,vx,w0,col,dash,pk}=ML.looks[gi],gm=GM[gi];
|
||||
const pz=pzOn(),arPz=pz&&!!S.ar,sel=(UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id))||(pz&&pzLinkHot(grp));let lab=null;
|
||||
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)))*sc*(far?0.5:1),np=gm.pts.length;
|
||||
// Only what sits at the middle of a line is still painted here when the card draws the lines.
|
||||
if(G&&!(bld||cut&&!vx||sel||z>0.9&&!busy))continue;
|
||||
const w=w0*sc*(far?0.5:1),np=gm.pts.length;
|
||||
if(SX.length<np){SX=new Float64Array(np*2);SY=new Float64Array(np*2);}
|
||||
for(const k of ks){
|
||||
// Off screen (with room for the widest line and the markers at its middle): nothing of it would show. The line's
|
||||
// box is kept on its cached geometry, so a link off screen is skipped without projecting its points.
|
||||
const bb=gm.bb||(gm.bb=(()=>{let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity;for(const p of gm.pts){if(p[0]<a)a=p[0];if(p[0]>b)b=p[0];if(p[1]<c)c=p[1];if(p[1]>d)d=p[1];}return [a,b,c,d];})());
|
||||
if((bb[1]+k*W-cam.x)*cam.z+CW/2<-40||(bb[0]+k*W-cam.x)*cam.z+CW/2>CW+40||(bb[3]-cam.y)*cam.z+CH/2<-40||(bb[2]-cam.y)*cam.z+CH/2>CH+40)continue;
|
||||
let mxx,my;
|
||||
if(G){const m=gm.mid||(gm.mid=polyAt(gm.pts,gm.cum,.5));mxx=(m[0]+k*W-cam.x)*cam.z+CW/2;my=(m[1]-cam.y)*cam.z+CH/2;}else{
|
||||
// Screen points as toS() gives them, kept in SX/SY.
|
||||
for(let i=0;i<np;i++){const p=gm.pts[i];SX[i]=(p[0]+k*W-cam.x)*cam.z+CW/2;SY[i]=(p[1]-cam.y)*cam.z+CH/2;}
|
||||
const path=()=>{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;i<np;i++)ctx.lineTo(SX[i],SY[i]);};
|
||||
ctx.lineCap='round';ctx.lineJoin='round';
|
||||
if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();}
|
||||
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:idle?[4,6]:[]);path();ctx.stroke();
|
||||
ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
|
||||
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(LDASH[dash]);path();ctx.stroke();
|
||||
ctx.strokeStyle=col;ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
|
||||
// Architect runs: tubes sharing one trench are drawn as strands of one bundle (one snip takes them all).
|
||||
if(pz&&many){ctx.strokeStyle='#1E2640';ctx.lineWidth=1.3;for(let j=1;j<grp.length;j++){const d=w*(j/grp.length-0.5);ctx.beginPath();for(let i=0;i<np;i++){const a=Math.max(0,i-1),b=Math.min(np-1,i+1),dx=SX[b]-SX[a],dy=SY[b]-SY[a],n=Math.hypot(dx,dy)||1,x=SX[i]-dy/n*d,y=SY[i]+dx/n*d;i?ctx.lineTo(x,y):ctx.moveTo(x,y);}ctx.stroke();}path();}
|
||||
// Still the same path: strokes keep it, so the dotted fiber line goes on top without building it again.
|
||||
if(df&&!bld&&!dark&&!busy){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);ctx.stroke();ctx.setLineDash([]);}
|
||||
const at=t=>polyAtXY(SX,SY,gm.cum,t);
|
||||
if(!cut&&load>0.01){const n=clamp(Math.round(2+u*10),2,12)>>(far?1:0)||1,len=gm.len*z,spd=90;
|
||||
if(pk){const n=pk>>(far?1:0)||1,len=gm.len*z,spd=90;
|
||||
ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=far?1:1.5;
|
||||
const rr2=far?1.6:Math.max(2.2,w*.42),base=now/1000*spd/Math.max(len,40);ctx.beginPath();for(let i=0;i<n;i++){let t=(base+i/n)%1;if(i%2)t=1-t;const [px,py]=at(t);ctx.moveTo(px+rr2,py);ctx.arc(px,py,rr2,0,7);}ctx.fill();ctx.stroke();}
|
||||
const [mx2,my]=at(.5);const mxx=mx2;
|
||||
if(bld){if(far){ctx.fillStyle='#FF8A3D';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,4,0,7);ctx.fill();ctx.stroke();}else drawCone(mxx,my,now);}
|
||||
else if(cut&&!vx){if(far){ctx.fillStyle='#FF4D5E';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,5,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',mxx,my+0.5);}else if(!arPz)drawBackhoe(mxx,my,now,l.sub);}
|
||||
else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
|
||||
[mxx,my]=at(.5);}
|
||||
if(bld){if(far)stamp('bldfar',12,12,6,6,1,mxx,my,g=>{g.fillStyle='#FF8A3D';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,4,0,7);g.fill();g.stroke();});else drawCone(mxx,my,now);}
|
||||
else if(cut&&!vx){if(far)stamp('cutfar',14,14,7,7,1,mxx,my,g=>{g.fillStyle='#FF4D5E';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,5,0,7);g.fill();g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText('!',0,0.5);});else if(!arPz)drawBackhoe(mxx,my,now,l.sub);}
|
||||
else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);pill(t,ctx.font,tw,17,8,'#fff','#1E2640','#1E2640',2,mxx,my-0.5,1.5);}
|
||||
// Every puzzle: say whether the tubes between two cities share one trench or take separate paths.
|
||||
if(pz&&!cut&&!bld&&(many||arPaths(l)>1)&&(many||lineIdx(l,PI.get(edgeKey(l)))===0))AR_PILLS.push([mxx,my+(sel||!S.ar?19:0),many?tr('architect.n_in_one_trench',{n:grp.length}):'✓ '+tr('architect.n_paths',{n:arPaths(l)}),many]);
|
||||
}
|
||||
|
|
@ -76,9 +96,9 @@ function drawFrame(now){
|
|||
// cities
|
||||
UI.feed=null;if(UI.sel&&UI.sel.type==='link'){const sl=S.links.find(x=>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));}}
|
||||
// Place labels: your POPs and the selected city first, then others; a label that would overlap moves above its city or hides.
|
||||
const vis=[];for(const C of CITIES){if(C.off&&!cityOn(C.id))continue;if(pzHide(C.id))continue;for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}}
|
||||
const vis=[];for(const C of CITIES){const sy=(C.y-cam.y)*cam.z+CH/2;if(sy<-60||sy>CH+60)continue;if(C.off&&!cityOn(C.id))continue;if(pzHide(C.id))continue;for(const k of ks){const sx=(C.x+k*W-cam.x)*cam.z+CW/2;if(sx<-60||sx>CW+60)continue;vis.push({C,sx,sy});}}
|
||||
const prio=v=>(UI.sel&&UI.sel.type==='city'&&UI.sel.id===v.C.id?0:S.pops[v.C.id]?1:2);vis.sort((a,b)=>prio(a)-prio(b)||b.C.P-a.C.P);
|
||||
const rects=[],labs=[],hit=(r)=>rects.some(q=>r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h);
|
||||
const rects=new RGrid(),labs=new RGrid(),hit=(r)=>rects.hits(r);
|
||||
const farL=lodFar();
|
||||
// Which cities show an offer bubble (a big one?) or an incident marker, worked out once for all of them.
|
||||
CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}}
|
||||
|
|
@ -93,10 +113,10 @@ function drawFrame(now){
|
|||
const h=farL?6:cityTop(v.C.id,p);const below=farL?v.sy+15:v.sy+16*csc+8,above=farL?v.sy-15:v.sy-h*csc-17*csc;let ly=null;
|
||||
for(const y of [below,above]){const r={x:v.sx-tw/2-2,y:y-10,w:tw+4,h:21};if(!hit(r)){ly=y;rects.push(r);labs.push(r);break;}}
|
||||
// Your POPs may sit over a city icon, but not over another name: that one waits until you zoom in.
|
||||
if(ly===null&&prio(v)===1)for(const y of [below,above]){const r={x:v.sx-tw/2,y:y-10,w:tw,h:21};if(!labs.some(q=>r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h)){ly=y;rects.push(r);labs.push(r);break;}}
|
||||
if(ly===null&&prio(v)===1)for(const y of [below,above]){const r={x:v.sx-tw/2,y:y-10,w:tw,h:21};if(!labs.hits(r)){ly=y;rects.push(r);labs.push(r);break;}}
|
||||
if(ly===null&&(prio(v)===0||(prio(v)===1&&(v.C.id===S.home||UI.hover===v.C.id)))){ly=below;const r={x:v.sx-tw/2,y:below-10,w:tw,h:21};rects.push(r);labs.push(r);}
|
||||
v.ly=ly;}
|
||||
if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,csc,now);pzDrawMarks(ks,now);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,csc,now,v.ly,v.dem);
|
||||
if(pzOn()){for(let i=vis.length-1;i>=0;i--)pzDrawCity(vis[i],csc,now);pzDrawMarks(ks,now);}else for(let i=vis.length-1;i>=0;i--){const v=vis[i];drawCity(v.C,v.sx,v.sy,csc,now,v.ly,v.dem);}
|
||||
// cable ships at sea (88-cable-ships.js), over the city labels so a ship leaving port stays in sight
|
||||
drawShips(ks,now);
|
||||
// Architect runs: what the tubes between two cities are (one trench, or separate paths), above the cities.
|
||||
|
|
@ -105,7 +125,8 @@ function drawFrame(now){
|
|||
if(UI.mk)mkDraw(ks);else if(mkOn()&&!pzOn()&&CITY[S.monkey.c])mkStart(S.monkey.c);
|
||||
// floaters
|
||||
for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;}
|
||||
for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}}
|
||||
const font='800 17px "Baloo 2", sans-serif';if(f.w===undefined){ctx.font=font;f.w=ctx.measureText(f.text).width;}
|
||||
for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;textStamp(f.text,font,17,f.w,f.col,'#fff',4,sx,sy-a*40);ctx.globalAlpha=1;}}
|
||||
}
|
||||
/* A map with more than MAP_BUSY lines on screen (huge late-game networks) is a tangle where nobody reads thousands of
|
||||
overlapping labels or fiber dots, and painting them took about half of every frame. They come back once fewer lines
|
||||
|
|
@ -116,7 +137,7 @@ function linesOnScreen(GM,ks){let n=0;for(const gm of GM){const b=gm.box||(gm.bo
|
|||
for(const k of ks){const x0=(b[0]+k*W-cam.x)*cam.z+CW/2,x1=(b[2]+k*W-cam.x)*cam.z+CW/2,y0=(b[1]-cam.y)*cam.z+CH/2,y1=(b[3]-cam.y)*cam.z+CH/2;
|
||||
if(!(x1<-40||x0>CW+40||y1<-40||y0>CH+40))n++;}}return n;}
|
||||
function ptsBox(pts){let a=Infinity,b=Infinity,c=-Infinity,d=-Infinity;for(const p of pts){if(p[0]<a)a=p[0];if(p[1]<b)b=p[1];if(p[0]>c)c=p[0];if(p[1]>d)d=p[1];}return [a,b,c,d];}
|
||||
function drawCone(x,y,now){const b=Math.sin(now/300)*1.5;ctx.save();ctx.translate(x,y-12+b);ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();ctx.restore();}
|
||||
function drawCone(x,y,now){stamp('cone',26,28,13,13,1,x,y-12+Math.sin(now/300)*1.5,()=>{ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();});}
|
||||
// Static land + cable map, rendered once per zoom bucket into an offscreen canvas.
|
||||
function paintWorld(c,z,withCables){const LANDP=lodFar()?LANDP_FAR:LANDP_ALL;
|
||||
for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle='rgba(20,90,130,.35)';for(const p of LANDP)c.fill(p);c.restore();}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,10 @@
|
|||
GPU canvas implementations (Firefox on Android) garble big paths (#43). It is painted into an offscreen image
|
||||
instead: the whole world when that fits in MAXPX, otherwise the visible area plus a margin, repainted when you
|
||||
pan out of it. While a zoom gesture is still moving, the last image is scaled rather than repainted. */
|
||||
const SOFT_CANVAS=/Firefox\//.test(navigator.userAgent);
|
||||
/* Only Firefox on Android gets that image as a software canvas (willReadFrequently). Firefox on a computer drew it
|
||||
fine on the graphics card, and a software canvas there is sent to the card again on every frame, a cost that grows
|
||||
with the image: zoomed in, the 2D map ran at half its speed. */
|
||||
const softCanvas=ua=>/Android.*Firefox\//.test(ua),SOFT_CANVAS=softCanvas(navigator.userAgent);
|
||||
function wlCovers(z){if(WL.full)return true;const hw=CW/2/z,hh=CH/2/z,w=WL.cv.width/WL.sc,h=WL.cv.height/WL.sc;
|
||||
return cam.x-hw>=WL.ox&&cam.x+hw<=WL.ox+w&&cam.y-hh>=WL.oy&&cam.y+hh<=WL.oy+h;}
|
||||
function worldLayer(z){
|
||||
|
|
@ -21,14 +24,12 @@ function worldLayer(z){
|
|||
function drawWorldLayer(wl,k,z,k0){if(!wl.full&&k!==k0)return;const f=z*DPR/wl.sc,ox=(wl.full?k*W:wl.ox);
|
||||
ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(wl.cv,Math.round(DPR*((ox-cam.x)*z+CW/2)),Math.round(DPR*((wl.oy-cam.y)*z+CH/2)),wl.cv.width*f,wl.cv.height*f);}
|
||||
function cableCol(C){return C.price<=0.85?'#14A88C':C.price<=1.1?'#2F7BEA':'#A05AE0';}
|
||||
function drawBackhoe(x,y,now,sub){
|
||||
const b=Math.sin(now/180)*2;ctx.save();ctx.translate(x,y-14+b);
|
||||
function drawBackhoe(x,y,now,sub){stamp('hoe|'+(sub?1:0),38,32,15,16,1,x,y-14+Math.sin(now/180)*2,()=>{
|
||||
ctx.strokeStyle='#1E2640';ctx.lineWidth=2.2;
|
||||
if(sub){ // shark fin
|
||||
ctx.fillStyle='#6B7C99';ctx.beginPath();ctx.moveTo(-12,8);ctx.quadraticCurveTo(-2,-14,10,-12);ctx.quadraticCurveTo(4,-2,12,8);ctx.closePath();ctx.fill();ctx.stroke();
|
||||
}else{
|
||||
ctx.fillStyle='#FFD23F';rr(-12,-4,18,12,3);ctx.fill();ctx.stroke();rr(-8,-12,10,9,2);ctx.fillStyle='#BDE8FF';ctx.fill();ctx.stroke();
|
||||
ctx.beginPath();ctx.moveTo(6,0);ctx.lineTo(14,-10);ctx.lineTo(19,2);ctx.stroke();ctx.fillStyle='#1E2640';ctx.beginPath();ctx.arc(-7,10,3,0,7);ctx.arc(2,10,3,0,7);ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
}});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,32 @@
|
|||
// Label widths by text (city labels by id, link labels and far-view labels by text): measuring text every frame is slow.
|
||||
const LBLW={},LINKW=new Map(),LBLF=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;});}catch(e){}
|
||||
const LBLW={},LINKW=new Map(),LBLF=new Map(),FKEY=new Map(),QKEY=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;spritesReset();});}catch(e){}
|
||||
// A label on a pill: its text and look never change, so it is painted once (spriteEntry) and drawn as a picture. The
|
||||
// centre is x, y; the text sits at y+ty. The pill's box is w×h with corners r; the picture also takes the outline.
|
||||
// Keys are kept by text (PILLK), one per look: joining them for every label on every frame was most of the map's garbage.
|
||||
const PILLK=new Map();
|
||||
function pill(t,font,w,h,r,fill,ink,stroke,lw,x,y,ty){
|
||||
const pad=lw+2,W=Math.ceil(w+pad*2),H=Math.ceil(h+pad*2);let L=PILLK.get(t),m=null;
|
||||
if(L)for(let i=0;i<L.length;i++){const q=L[i];if(q.font===font&&q.w===w&&q.h===h&&q.r===r&&q.fill===fill&&q.ink===ink&&q.stroke===stroke&&q.lw===lw&&q.ty===ty){m=q;break;}}
|
||||
if(!m){if(!L){if(PILLK.size>4000)PILLK.clear();PILLK.set(t,L=[]);}L.push(m={font,w,h,r,fill,ink,stroke,lw,ty,k:['pill',t,font,w,h,r,fill,ink,stroke,lw,ty].join('|')});}
|
||||
const e=spriteHas(m.k)||spriteEntry(m.k,W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.fillStyle=fill;g.strokeStyle=stroke;g.lineWidth=lw;
|
||||
rr(-w/2,-h/2,w,h,r);g.fill();g.stroke();g.fillStyle=ink;g.font=font;g.textAlign='center';g.textBaseline='middle';g.fillText(t,0,ty);});
|
||||
// Whole device pixels, so the text stays as sharp as before.
|
||||
blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);}
|
||||
// Zoomed out a city is a small picture (a dot, or your POP's box), kept as a sprite; a POP in trouble glows under it.
|
||||
function drawCityFar(C,sx,sy,sc,now,lyOverride){
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
ctx.save();ctx.translate(sx,sy);ctx.strokeStyle='#1E2640';
|
||||
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.strokeStyle='#1E2640';}
|
||||
if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9)dot(sx,sy,12,'rgba(255,77,94,1)',.35+.25*Math.sin(now/200));
|
||||
const t=cTier(C.id),ph=sel?Math.floor(now/40)%8:-1,f=(p?1:0)|(down?2:0)|(p&&p.site2?4:0)|(p&&(p.routers||1)>=2?8:0)|(hov?16:0)|(hasIxAt(C.id)?32:0)|(CM.off.has(C.id)?64:0)|(CM.inc.has(C.id)?128:0);
|
||||
// The key, kept per city and built again only when the picture changes.
|
||||
let m=FKEY.get(C.id);if(!m||m.f!==f||m.t!==t||m.ph!==ph)FKEY.set(C.id,m={f,t,ph,k:'far|'+t+'|'+f+'|'+ph});
|
||||
stamp(m.k,36,36,18,18,1,sx,sy,()=>cityFarStatic(C,p,down,sel,hov,ph));
|
||||
if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride;
|
||||
pill(t,ctx.font,tw,16,8,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',1.6,sx,ly,1);}
|
||||
}
|
||||
function cityFarStatic(C,p,down,sel,hov,ph){ctx.strokeStyle='#1E2640';
|
||||
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-ph;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;ctx.strokeStyle='#1E2640';}
|
||||
if(p){
|
||||
if(!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){ctx.fillStyle=`rgba(255,77,94,${.35+.25*Math.sin(now/200)})`;ctx.beginPath();ctx.arc(0,0,12,0,7);ctx.fill();}
|
||||
const col=down?'#8A91A8':'#FF4F9A';ctx.lineWidth=1.8;
|
||||
if(p.site2){ctx.setLineDash([2,2]);ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(9,6);ctx.stroke();ctx.setLineDash([]);ctx.fillStyle=col;rr(5,3,9,7,3);ctx.fill();ctx.stroke();}
|
||||
if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-6,-7,15,10,4);ctx.fill();ctx.stroke();}
|
||||
|
|
@ -15,26 +35,26 @@ function drawCityFar(C,sx,sy,sc,now,lyOverride){
|
|||
const t=cTier(C.id),r=FAR_R[t]*(hov?1.3:1);if(t===4){ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath();ctx.arc(0,0,r+4.5,0,7);ctx.fill();}
|
||||
ctx.fillStyle=hasIxAt(C.id)?'#FFD23F':'#FFFFFF';ctx.lineWidth=t>=3?1.6:1.3;ctx.beginPath();ctx.arc(0,0,r,0,7);ctx.fill();ctx.stroke();}
|
||||
if(CM.off.has(C.id)){ctx.fillStyle='#16A866';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?9:5,p?-7:-5,3,0,7);ctx.fill();ctx.stroke();}
|
||||
if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}
|
||||
ctx.restore();
|
||||
if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride;
|
||||
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;rr(sx-tw/2,ly-8,tw,16,8);ctx.fill();ctx.stroke();
|
||||
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);}
|
||||
}
|
||||
function drawCity(C,sx,sy,sc,now,lyOverride,dem){
|
||||
if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride);
|
||||
const hot=(UI.hotMap||{})[C.id];
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
// No room for its skyline here: a quiet dot, a little bigger for bigger cities, until you zoom in (cityRoom).
|
||||
if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc;ctx.fillStyle=hasIxAt(C.id)?'#FFD23F':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;ctx.beginPath();ctx.arc(sx,sy+2*sc,r,0,7);ctx.fill();ctx.stroke();return;}
|
||||
const t=cTier(C.id),cs=p?1:CSC[t];
|
||||
const k=sc*(hov?1.15:1);
|
||||
ctx.save();ctx.translate(sx,sy);
|
||||
if(UI.feed&&UI.feed.has(C.id)){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
// A flood is filling ports here: they pulse until it is over (#242).
|
||||
if(p&&R.ddosHot&&R.ddosHot[C.id]){ctx.strokeStyle='#FF4D5E';ctx.lineWidth=3;ctx.setLineDash([4,4]);ctx.lineDashOffset=now/30;ctx.beginPath();ctx.arc(0,-6*k,33*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){const a=.35+.25*Math.sin(now/200);ctx.fillStyle=`rgba(255,77,94,${a})`;ctx.beginPath();ctx.arc(0,-6*k,26*k,0,7);ctx.fill();}
|
||||
if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}}
|
||||
// A city's picture is painted once per state and kept as a sprite (citySprite). What moves every frame is painted on top
|
||||
// (cityMoving): the lights, the steam, a flashing IX, the hot badges and the offer bubble. The rings and the glow move too,
|
||||
// but in steps (cityPhase), so their sprite changes only at a step; so does its scale (sprQ(), 59-gl-sprites.js).
|
||||
// dd is -1 without an attack: the attack's ring at step 0 must not share a sprite with no ring at all.
|
||||
function cityPhase(C,p,sel,now){const ph={sel:0,dd:-1,gl:-1};
|
||||
if(sel)ph.sel=Math.floor(now/40)%12; // dash period 12 px, lineDashOffset -now/40
|
||||
if(p&&R.ddosHot&&R.ddosHot[C.id])ph.dd=Math.floor(now/30)%8; // dash period 8 px, lineDashOffset now/30
|
||||
if(p&&!(p.down>S.day)&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9)ph.gl=Math.round((Math.sin(now/200)+1)*3.5); // 8 levels of .35+.25·sin
|
||||
return ph;}
|
||||
// The IX badge. Hot (a flood or a fault) it flashes: cityMoving() then draws it from two pictures, one per colour.
|
||||
function cityIX(C,p,t,h,hot,now){const mine=!!S.myIx[C.id],joined=hasIxAt(C.id),q=!p&&!hot&&ixQuiet(C.id),Rr=q?6.5:8.5,ix=p?19:SKY_W[t]/2+(q?2:4);
|
||||
ctx.fillStyle=hot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(ix+Rr*Math.cos(a),-h+2+Rr*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=q?1.4:2;ctx.stroke();
|
||||
ctx.fillStyle=mine||hot?'#fff':'#1E2640';ctx.font=`900 ${q?6.5:8}px Nunito, sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',ix,-h+2.5);}
|
||||
// Everything about the city that does not move, in the city's own frame (origin on the city). Drawn into a sprite, so
|
||||
// it reads only what citySprite() puts in the key.
|
||||
function cityStatic(C,p,t,cs,k,ph,st){const down=st.down;
|
||||
if(st.feed){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
if(st.sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-ph.sel;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;}
|
||||
if(ph.dd>=0){ctx.strokeStyle='#FF4D5E';ctx.lineWidth=3;ctx.setLineDash([4,4]);ctx.lineDashOffset=ph.dd;ctx.beginPath();ctx.arc(0,-6*k,33*k,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;}
|
||||
ctx.scale(k*cs,k*cs);
|
||||
ctx.fillStyle='rgba(30,38,64,.2)';ctx.beginPath();ctx.ellipse(0,9,p?20:SKY_W[t]/2+5,5,0,0,7);ctx.fill();
|
||||
const h=p?18:SKY_H[t];
|
||||
|
|
@ -56,30 +76,64 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){
|
|||
if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-13,-13,34,16,6);ctx.fill();ctx.stroke();}
|
||||
if(p.gen){ctx.fillStyle='#FFD23F';rr(-27,-1,9,11,2);ctx.fill();ctx.stroke();}
|
||||
ctx.fillStyle=down?'#8A91A8':'#FF4F9A';rr(-17,-7,34,16,6);ctx.fill();ctx.stroke();
|
||||
if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const t=(now/700+i/3)%1;ctx.fillStyle=`rgba(90,98,130,${0.55*(1-t)})`;ctx.beginPath();ctx.arc(6+i*3,-12-t*18,3+t*4,0,7);ctx.fill();}}
|
||||
if((p.rgen||0)>0){const G=RG[p.rgen||0];ctx.fillStyle=G.badge?'#7CFFB2':'#FFD23F';ctx.beginPath();ctx.arc(17,-7,6,0,7);ctx.fill();ctx.lineWidth=1.8;ctx.stroke();ctx.fillStyle='#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(G.badge||String(G.cls+1),17,-6.5);ctx.lineWidth=2.2;}
|
||||
const sf=sfOf(R,C.id);
|
||||
for(let i=0;i<4;i++){const on=down?false:(((now/(160+i*37))|0)+i)%3!==0;ctx.fillStyle=down?'#3B4260':on?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';ctx.beginPath();ctx.arc(-10+i*6.6,1,2.1,0,7);ctx.fill();}
|
||||
if(down){ctx.fillStyle='#fff';ctx.font='900 14px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.fillText('zzz',20,-14);}
|
||||
if(flip)ctx.restore();
|
||||
ctx.translate(0,-2);
|
||||
}
|
||||
const ixn=ixName(C.id);
|
||||
// The IX badge sits at the skyline's top right, whatever its width.
|
||||
if(ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov)){const mine=!!S.myIx[C.id],joined=hasIxAt(C.id),ixHot=hot&&hot.ix,q=!p&&!ixHot&&ixQuiet(C.id),R=q?6.5:8.5,ix=p?19:SKY_W[t]/2+(q?2:4);
|
||||
ctx.fillStyle=ixHot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(ix+R*Math.cos(a),-h+2+R*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=q?1.4:2;ctx.stroke();
|
||||
ctx.fillStyle=mine||ixHot?'#fff':'#1E2640';ctx.font=`900 ${q?6.5:8}px Nunito, sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',ix,-h+2.5);}
|
||||
if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const k of ['r','t','p','c']){if(!hot[k])continue;ctx.globalAlpha=pulse;ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-29,y,6.5,0,7);ctx.fill();ctx.globalAlpha=1;ctx.lineWidth=2;ctx.strokeStyle='#1E2640';ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(HOTL[k],-29,y+0.5);y+=14;}}
|
||||
const off=CM.off.has(C.id);
|
||||
if(off){const by=-h-16+Math.sin(now/250)*3;ctx.fillStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.ellipse(-2,by,11,9,0,0,7);ctx.fill();ctx.stroke();ctx.beginPath();ctx.moveTo(-5,by+8);ctx.lineTo(-7,by+14);ctx.lineTo(0,by+8);ctx.fillStyle='#fff';ctx.fill();const big=CM.big.has(C.id);ctx.fillStyle=big?'#FF4F9A':'#16A866';ctx.font='900 13px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(big?'$$':'$',-2,by+1);}
|
||||
const inc=CM.inc.has(C.id);
|
||||
if(inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
|
||||
ctx.restore();
|
||||
if(st.ixDraw&&!st.ixHot)cityIX(C,p,t,h,false,0);
|
||||
if(st.inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
|
||||
}
|
||||
// The picture of a city in a given state, at the quantised scale kq: painted once and kept until it is not needed.
|
||||
// Its key is kept per city (CKEY) and joined again only when one of its parts changes: the yes/no parts are bits of f.
|
||||
const CKEY=new Map();
|
||||
function citySprite(C,p,t,cs,kq,ph,st){const id=C.id,
|
||||
f=(st.down?1:0)|(p?2:0)|(p&&p.site2?4:0)|(p&&p.site2&&siteDown(id,'b')?8:0)|(p&&p.ringcut>S.day?16:0)|(p&&p.gen?32:0)|(C.au?64:0)|(st.ixDraw?128:0)|
|
||||
(st.ixHot?256:0)|(S.myIx[id]?512:0)|(hasIxAt(id)?1024:0)|(!p&&ixQuiet(id)?2048:0)|(st.feed?4096:0)|(st.inc?8192:0),
|
||||
ro=p?(p.routers||1):0,rg=p?(p.rgen||0):0,ix=ixName(id)||'',sp=st.sel?ph.sel:-1,dd=ph.dd;
|
||||
let m=CKEY.get(id);
|
||||
if(!m||m.t!==t||m.kq!==kq||m.f!==f||m.ro!==ro||m.rg!==rg||m.ix!==ix||m.sp!==sp||m.dd!==dd)CKEY.set(id,m={t,kq,f,ro,rg,ix,sp,dd,k:['city',id,t,kq,f,ro,rg,ix,sp,dd].join('|')});
|
||||
const e=spriteHas(m.k);if(e)return e;
|
||||
const W=Math.ceil(92*kq),H=Math.ceil(84*kq),ax=45*kq,ay=46*kq;
|
||||
return spriteEntry(m.k,W,H,ax,ay,g=>{g.translate(ax,ay);cityStatic(C,p,t,cs,kq,ph,st);});}
|
||||
// The parts that move, in the city's frame at the true scale k.
|
||||
function cityMoving(C,p,t,cs,k,sx,sy,now,h,st,hot){const down=st.down,K=k*cs;
|
||||
if(p){// The POP's own frame is shifted 2 down, and mirrored Down Under (C.au): mp() takes a point of that frame to the city's.
|
||||
// A point (x,y) of that frame is at sx+(fl?-x:x)*K, sy+(fl?-y-2:y+2)*K (written out: no array per light per frame).
|
||||
const fl=!!C.au,sf=sfOf(R,C.id);
|
||||
if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const tt=(now/700+i/3)%1,x=6+i*3,y=-12-tt*18;dot(sx+(fl?-x:x)*K,sy+(fl?-y-2:y+2)*K,(3+tt*4)*K,'rgba(90,98,130,1)',0.55*(1-tt));}}
|
||||
// The four lights: a disc each, lit or not.
|
||||
for(let i=0;i<4;i++){const lit=down?false:(((now/(160+i*37))|0)+i)%3!==0,x=-10+i*6.6,col=down?'#3B4260':lit?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';dot(sx+(fl?-x:x)*K,sy+(fl?-3:3)*K,2.1*K,col,1);}
|
||||
}
|
||||
// A flashing IX: two pictures, one per colour.
|
||||
if(st.ixDraw&&st.ixHot){const on=Math.sin(now/180)>0,ix=p?19:SKY_W[t]/2+4;stamp('ixhot'+(on?1:0),22,22,11,11,K,sx+ix*K,sy+(2-h)*K,()=>{ctx.translate(-ix,h-2);ctx.strokeStyle='#1E2640';cityIX(C,p,t,h,true,on?1:-1);},true);}
|
||||
// Hot badges: the red disc pulses, the ring and the letter over it stay.
|
||||
if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const kk of ['r','t','p','c']){if(!hot[kk])continue;const bx=sx-29*K,by=sy+y*K;dot(bx,by,6.5*K,'#FF4D5E',pulse);
|
||||
stamp('hotb|'+HOTL[kk],18,18,9,9,K,bx,by,g=>{g.lineWidth=2;g.strokeStyle='#1E2640';g.beginPath();g.arc(0,0,6.5,0,7);g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(HOTL[kk],0,0.5);},true);y+=14;}}
|
||||
// The offer bubble bobs over the city.
|
||||
if(st.off)stamp('offer|'+(st.big?2:1),30,28,15,12,K,sx-2*K,sy+(-h-16+Math.sin(now/250)*3)*K,g=>{g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=2.2;g.beginPath();g.ellipse(0,0,11,9,0,0,7);g.fill();g.stroke();
|
||||
g.beginPath();g.moveTo(-3,8);g.lineTo(-5,14);g.lineTo(2,8);g.fill();g.fillStyle=st.big?'#FF4F9A':'#16A866';g.font='900 13px "Baloo 2", sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(st.big?'$$':'$',0,1);},true);}
|
||||
function drawCity(C,sx,sy,sc,now,lyOverride,dem){
|
||||
if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride);
|
||||
const hot=(UI.hotMap||{})[C.id];
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
// No room for its skyline here: a quiet dot, a little bigger for bigger cities, until you zoom in (cityRoom).
|
||||
if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc,rq=Math.round(r*4)/4,fill=hasIxAt(C.id)?'#FFD23F':'#FFFFFF',S2=Math.ceil(rq*2+4);
|
||||
const qk=rq*8+(fill==='#FFFFFF'?0:1);let key=QKEY.get(qk);if(!key)QKEY.set(qk,key=['quiet',rq,fill].join('|'));
|
||||
const e=spriteHas(key)||spriteEntry(key,S2,S2,S2/2,S2/2,g=>{g.translate(S2/2,S2/2);g.fillStyle=fill;g.strokeStyle='#1E2640';g.lineWidth=1.6;g.beginPath();g.arc(0,0,rq,0,7);g.fill();g.stroke();});
|
||||
blit(e,sx-e.ax,sy+2*sc-e.ay,e.w,e.h);return;}
|
||||
const t=cTier(C.id),cs=p?1:CSC[t],k=sc*(hov?1.15:1),kq=sprQ(k);
|
||||
const ixn=ixName(C.id),ixDraw=!!ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov),ixHot=!!(ixDraw&&hot&&hot.ix);
|
||||
const st={down:!!down,feed:!!(UI.feed&&UI.feed.has(C.id)),sel:!!sel,inc:CM.inc.has(C.id),ixDraw,ixHot,off:CM.off.has(C.id),big:CM.big.has(C.id)};
|
||||
const ph=cityPhase(C,p,sel,now),spr=citySprite(C,p,t,cs,kq,ph,st),r=k/kq;
|
||||
// The glow of a city in trouble pulses: a disc each frame, under the picture (as it was under the skyline).
|
||||
if(ph.gl>=0)dot(sx,sy-6*k,26*k,'rgba(255,77,94,1)',.35+.25*(2*ph.gl/7-1));
|
||||
blit(spr,sx-spr.ax*r,sy-spr.ay*r,spr.w*r,spr.h*r);
|
||||
cityMoving(C,p,t,cs,k,sx,sy,now,p?18:SKY_H[t],st,hot);
|
||||
// label
|
||||
if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){
|
||||
ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=LBLW[C.id+(p?1:0)]||(LBLW[C.id+(p?1:0)]=ctx.measureText(t).width+14),ly=lyOverride==null?sy+16*sc+8:lyOverride;
|
||||
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(sx-tw/2,ly-9,tw,19,9);ctx.fill();ctx.stroke();
|
||||
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);
|
||||
pill(t,ctx.font,tw,19,9,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',2,sx,ly+0.5,0.5);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,13 +24,13 @@ function shipAt(s,T){const f=S.fleet&&S.fleet[s.id],H=shipHomePt(s);if(!f||T>=f.
|
|||
else{p=1-(T-f.done)/Math.max(0.01,f.back-f.done);mode='back';}
|
||||
p=clamp(p,0,1);const [x,y]=polyAt(r.pts,r.cum,p),[x2]=polyAt(r.pts,r.cum,clamp(p+(mode==='back'?-0.01:0.01),0,1));return {x,y,m:mode,dx:x2-x||1};}
|
||||
// A cartoon cable ship: red hull, white bridge, the yellow bow sheave cable ships are known by; a wake when under way.
|
||||
function shipSprite(x,y,face,sc,col,now,mode){const c=ctx;c.save();c.translate(x,y+Math.sin(now/420+x*0.05)*1.2*sc);c.scale(face*sc,sc);
|
||||
function shipSprite(x,y,face,sc,col,now,mode){const bl=mode==='work'&&Math.floor(now/350)%2;
|
||||
stamp(['ship',col,face,mode,bl?1:0].join('|'),52,32,26,18,sc,x,y+Math.sin(now/420+x*0.05)*1.2*sc,c=>{c.scale(face,1);
|
||||
if(mode!=='port'&&mode!=='work'){c.strokeStyle='rgba(255,255,255,.85)';c.lineWidth=1.6;c.beginPath();c.moveTo(-10,3);c.quadraticCurveTo(-16,1,-22,4);c.moveTo(-10,5);c.quadraticCurveTo(-15,8,-21,9);c.stroke();}
|
||||
c.fillStyle=col;c.strokeStyle='#1E2640';c.lineWidth=1.6;c.lineJoin='round';c.beginPath();c.moveTo(-11,0);c.lineTo(11,0);c.lineTo(8,6);c.lineTo(-9,6);c.closePath();c.fill();c.stroke();
|
||||
c.fillStyle='#fff';c.beginPath();c.rect(-7,-7,8,7);c.fill();c.stroke();c.fillStyle='#1E2640';c.fillRect(-5,-5,4,2);
|
||||
c.beginPath();c.arc(9,-2,2.6,0,7);c.fillStyle='#FFD23F';c.fill();c.stroke();
|
||||
if(mode==='work'&&Math.floor(now/350)%2){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}
|
||||
c.restore();}
|
||||
if(bl){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}},true);}
|
||||
function drawShips(ks,now){SHIP_HITS.length=0;if(!S||pzOn()||!S.fleet)return;
|
||||
const T=S.day+(UI.speed?clamp(acc/DAY_MS,0,0.999):0),z=cam.z,sc=Math.max(0.85,Math.min(1.5,Math.sqrt(z)))*(lodFar()?0.9:1.05),list=[];
|
||||
for(const s of SHIPS){const p=shipAt(s,T);if(p.m==='port'&&z<1.1)continue;list.push({p,s,col:s.club==='prv'?'#7A5CFF':'#FF4D5E'});}
|
||||
|
|
|
|||
|
|
@ -11,5 +11,5 @@ let PD={t:0,b:null};
|
|||
document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true);
|
||||
function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true;
|
||||
if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;}
|
||||
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
|
||||
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
|
||||
|
||||
|
|
|
|||
37
src/game/96-map/97-diagnostics.js
Normal file
37
src/game/96-map/97-diagnostics.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/* Settings › Diagnostic info: one readout in a corner, for bug reports. What the screen tells the game (for phone
|
||||
layouts), how the map is drawn (the graphics card or 2D, and why), and how fast: frames per second, the slowest
|
||||
frames, the time draw() takes. It is also opened with ?vp or ?fps in the address (?novp, ?nofps close it), and,
|
||||
inside an installed app where there is no address bar, with five quick taps on the date. Its words are technical on
|
||||
purpose and stay in English: they are pasted into bug reports. */
|
||||
const DIAG={on:false,el:null,t:null,fr:[],dr:[],last:0,dms:-1};
|
||||
// One frame of the loop (99-loop.js): its interval, and the time draw() took if the map was drawn.
|
||||
function diagFrame(now){const D=DIAG;if(D.last)D.fr.push(now-D.last);D.last=now;if(D.dms>=0){D.dr.push(D.dms);D.dms=-1;}
|
||||
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')+')';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. The loop runs at
|
||||
// the screen's rate even when a still map is not drawn again (mapStill()), so how often it was drawn is shown too.
|
||||
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;
|
||||
return `${sum?(f.length*1000/sum).toFixed(0):'-'} fps · map drawn ${sum?(d.length*1000/sum).toFixed(0):'-'}/s · p95 ${q(.95)} ms · max ${q(1)} ms\ndraw ${d.length?(d.reduce((a,x)=>a+x,0)/d.length).toFixed(1):'-'} ms · x${UI.speed||0} · zoom ${cam.z.toFixed(2)}`+
|
||||
(gl?` · ${GLX.nSeg} segments · ${GLX.nPk} packets`:'');}
|
||||
function diagShow(){const D=DIAG;let el=D.el;
|
||||
if(!el){el=D.el=document.createElement('pre');el.id='diag';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;max-width:calc(100vw - 32px);background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none;white-space:pre-wrap;overflow-wrap:anywhere';
|
||||
// A hidden probe reads the safe areas (the notch, the home bar) as CSS gives them.
|
||||
const pr=document.createElement('div');pr.id='diagprobe';pr.style.cssText='position:fixed;visibility:hidden;padding:env(safe-area-inset-top,0px) 0 env(safe-area-inset-bottom,0px)';el.appendChild(pr);
|
||||
D.txt=document.createTextNode('');el.appendChild(D.txt);document.body.appendChild(el);}
|
||||
const cs=getComputedStyle(document.getElementById('diagprobe')),vv=window.visualViewport,de=document.documentElement,tb=document.getElementById('tabbar').getBoundingClientRect(),
|
||||
sa=navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches);
|
||||
D.txt.data=`Series of Tubes ${APP_VERSION} · ${LANG}\n`+
|
||||
`inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height} · dpr ${window.devicePixelRatio||1}\n`+
|
||||
`vv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\n`+
|
||||
`standalone ${sa} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}\n`+
|
||||
diagMap()+'\n'+diagPerf();}
|
||||
// Shows or hides the readout, and remembers it on this device.
|
||||
function diagOn(on){const D=DIAG;clearInterval(D.t);D.t=null;if(D.el){D.el.remove();D.el=null;}D.on=!!on;D.fr.length=D.dr.length=0;D.last=0;D.dms=-1;
|
||||
if(on){D.t=setInterval(diagShow,500);diagShow();}
|
||||
try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');}catch(e){}}
|
||||
{const q=location.search;let on=false;try{on=localStorage.getItem('sot-vp')==='1';}catch(e){}
|
||||
if(/[?&](vp|fps)\b/.test(q))on=true;else if(/[?&]no(vp|fps)\b/.test(q))on=false;diagOn(on);}
|
||||
{let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];diagOn(!DIAG.on);}});}
|
||||
|
|
@ -12,7 +12,8 @@ function frame(now){
|
|||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt);
|
||||
if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
|
||||
const t=animOn()?animT:0;
|
||||
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;}
|
||||
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;}
|
||||
if(DIAG.on)diagFrame(now);
|
||||
}
|
||||
// dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames
|
||||
// do not (src/agent/, a hidden tab), under the frame's own conditions otherwise.
|
||||
|
|
@ -27,12 +28,12 @@ function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c
|
|||
const r=c.getBoundingClientRect();if(r.top<=1&&r.left<=1&&r.right>=innerWidth-1&&r.bottom>=innerHeight-1)return true;}return false;}
|
||||
/* Paused, or with animations off, the map only changes when you move it, point at something or the network changes.
|
||||
Until then the last frame is still right, so it is not drawn again (phones keep cool). It is redrawn at least once
|
||||
a second anyway, and every frame while the land picture is still catching up with a zoom. */
|
||||
a second anyway, and every frame while the land picture is still catching up with a zoom (the WebGL map has none). */
|
||||
const FRAME=[];
|
||||
function mapStill(t,now){const sl=UI.sel,dr=UI.drag;
|
||||
const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk?UI.mk.tx:0,UI.mk?UI.mk.mood:0];
|
||||
const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk?UI.mk.tx:0,UI.mk?UI.mk.mood:0,zoomMoving()];
|
||||
let same=v.length===FRAME.length;for(let i=0;i<v.length;i++)if(FRAME[i]!==v[i]){same=false;FRAME[i]=v[i];}
|
||||
return same&&now-(UI.drawnAt||0)<1000&&!!(WL.cv&&WL.key===(cam.z*DPR).toFixed(4)&&wlCovers(cam.z));}
|
||||
return same&&now-(UI.drawnAt||0)<1000&&(glOn()||!!(WL.cv&&WL.key===(cam.z*DPR).toFixed(4)&&wlCovers(cam.z)));}
|
||||
function tickErr(e){console.error('[tubes] tick failed',e);if(UI.tickErr)return;UI.tickErr=true;track('tick_error',true);
|
||||
toast(tr('loop.something_in_the_noc_glitched_the'),'bad');}
|
||||
function boot(data){
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue