From ecb862e70d2a6a7c95d331b8a0d34b80ff22fe34 Mon Sep 17 00:00:00 2001 From: Hugues <16280457+huguesdelamure@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:44:47 +0100 Subject: [PATCH 1/4] Map of huge networks: fiber capacity once per frame, skip links off screen draw() asked dfCap() three to five times per fiber link and per frame (width, colour, label, up or down), each time over all its channels: on a save with 3,140 dark fibers of 18 channels on average that was about half of draw()'s JavaScript. dfCap() now keeps its answers in DFC while one frame is drawn (cleared in a finally, so a failed frame keeps nothing), and the link label is built once per line instead of once per world copy. Links entirely above or below the screen are skipped like those left or right of it already were. Player save (202 POPs, 3,142 links), jsdom: draw() 40 -> 25 ms; perf-bench "Map at three zoom levels" 89.7 -> 47.1 ms. Canvas call log identical at every zoom without the vertical skip; Firefox pixels identical (SHA-1 of the canvas) in 7 views. Firefox still spends ~95% of the frame painting. --- CHANGELOG.md | 2 ++ src/game/10-catalog/60-reach-and-subsea.js | 6 +++++- src/game/96-map/60-draw.js | 12 +++++++----- tests/speed.test.js | 21 +++++++++++++++++++++ 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 738dc06..5971143 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The map of a huge network spends less time working out fiber capacities on every frame, and skips links above or below the screen. + ## [1.34.1] — 2026-10-27 - The game starts faster in Italian, Portuguese and French: their translations are about 40% smaller to download. diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index 2ed9bc5..9ff08a3 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -54,7 +54,11 @@ const subMaxTier=km=>{let t=0;LT.forEach((T,i)=>{if(!subWaveWhy(i,km,true))t=i;} // Cached per optic, span and cable state: subsea, and which submarine upgrades are in service (#78). const OPTG={};const optG=(o,l)=>{const km=spanKm(l),fl=l.sub?1+(subUpgradeReady(l,'terminal')?2:0)+(subUpgradeReady(l,'engineering')?4:0):0,c=OPTG[o]||(OPTG[o]=[]),m=c[fl]||(c[fl]=new Map());let g=m.get(km);if(g===undefined){const x=optMode(o,l);m.set(km,g=x?x.g:0);}return g;}; const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/OPT[o].reach)-1); -const dfCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; +// The map asks for every fiber's capacity several times per frame (width, colour, label, up or down), each time over +// all its channels. Nothing changes while a frame is drawn, so draw() keeps the answers in DFC for that frame. +let DFC=null; +const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; +const dfCap0=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); // A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 4ed461f..75801b7 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -1,4 +1,5 @@ -function draw(now){ +function draw(now){DFC=new Map();try{drawFrame(now);}finally{DFC=null;}} +function drawFrame(now){ if(!ctx)return; ctx.setTransform(DPR,0,0,DPR,0,0); // sea @@ -27,13 +28,14 @@ function draw(now){ const far=lodFar(),PI=pairIdx(); for(const grp of linkGroups()){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; const gm=linkGeom(l,PI.get(edgeKey(l))),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'; - const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id); + const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);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; if(SX.lengthmx)mx=x;} - if(mx<-40||mn>CW+40)continue; + let mn=Infinity,mx=-Infinity,mny=Infinity,mxy=-Infinity;for(let i=0;imx)mx=x;if(ymxy)mxy=y;} + // Off screen (with room for the widest line and the markers at its middle): nothing of it would show. + if(mx<-40||mn>CW+40||mxy<-40||mny>CH+40)continue; const path=()=>{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;i0.9||sel){const t=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);} + else if(z>0.9||sel){const t=lab||(lab=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);} } } // drag preview diff --git a/tests/speed.test.js b/tests/speed.test.js index f977228..0ea9f41 100644 --- a/tests/speed.test.js +++ b/tests/speed.test.js @@ -100,6 +100,27 @@ test('the map draws a big network at every zoom, with a city or a link selected' assert.deepEqual(errors, []); }); +test('the map keeps fiber capacities for one frame only, and skips links above or below the screen', () => { + const { ev, errors } = load(); + bigNet(ev); + ev("S.links.push({id:'dfT',a:'fra',b:'ams',kind:'df',own:true,km:kmBetween('fra','ams'),ready:0,ch:['zr4']});compute()"); + ev('cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=2;draw(0)'); + assert.equal(ev('DFC'), null, 'nothing is kept between frames'); + const cap = ev("dfCap(S.links.find(l=>l.id==='dfT'))"); + ev("S.links.find(l=>l.id==='dfT').ch.push('zr4');draw(0)"); + assert.equal(ev("dfCap(S.links.find(l=>l.id==='dfT'))"), 2 * cap, 'a new channel counts on the next frame'); + ev("ctx.fillText=()=>{throw new Error('boom')}"); + assert.throws(() => ev('draw(0)')); + ev('delete ctx.fillText'); + assert.equal(ev('DFC'), null, 'not even after a frame that failed'); + // The whole network far above the screen: the links cost nothing, as if there were none. + const calls = (body) => ev(`(()=>{cam.x=CITY.fra.x;cam.y=CITY.fra.y+${'2000'};cam.z=2;${body};const n=ctx.calls.n;draw(0);return ctx.calls.n-n;})()`); + const withLinks = calls(''), links = ev('JSON.stringify(S.links)'); + assert.equal(withLinks, calls('S.links=[]')); + ev(`S.links=JSON.parse(${JSON.stringify(links)})`); + assert.deepEqual(errors, []); +}); + test('long lists in the NOC dashboard show 100 rows at a time and grow on request', () => { const { ev, errors } = load(); bigNet(ev); From d7301747f734a359291e732896440b5e37e2a5f9 Mon Sep 17 00:00:00 2001 From: Hugues <16280457+huguesdelamure@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:44:57 +0100 Subject: [PATCH 2/4] Saves too big for the browser: wait before retrying A late-game save of ~22 million characters is over Firefox's localStorage quota, so every save failed, yet the game rebuilt it with JSON.stringify(S) every 5 seconds, every 10 days and after every action: ~95 ms each in headless Firefox, 300-570 ms in a player's browser, all thrown away. After a failed save the autosave now waits 1 minute before trying again, then 2, 4, at most 5. A save that works resets this, so normal games still save every time. Leaving the page, exporting, reloading for an update or a language and a new game (a new S) still try at once. Player save in Firefox: first save 95 ms as before, the next autosaves 0 ms. --- CHANGELOG.md | 1 + src/game/90-actions/10-interface.js | 2 +- src/game/90-actions/89-game-and-settings.js | 2 +- src/game/91-save.js | 15 ++++++++++---- tests/persist.test.js | 22 +++++++++++++++++++++ 5 files changed, 36 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5971143..03a3406 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Huge networks stop stuttering every few seconds when their save is too big for the browser to keep: after a failed save the game waits a minute before trying again, then longer, instead of retrying every 5 seconds and after every click. Leaving the page, exporting and new games still save at once. - The map of a huge network spends less time working out fiber capacities on every frame, and skips links above or below the screen. ## [1.34.1] — 2026-10-27 diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index af3bcfa..daedd0f 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -22,7 +22,7 @@ const ACT={ dashLink:({id})=>{$('dash').hidden=true;selectLink(id);}, 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();location.reload();}, + langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();}, mute:()=>{UI.muted=!UI.muted;try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();}, closePanel:()=>{UI.sel=null;UI.confirm=null;renderPanel();renderLeft();}, closeModal:()=>closeModal(), diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index ed9a284..82f3adc 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -31,7 +31,7 @@ Object.assign(ACT,{ vpSet:({v})=>{vpOn(v==='on');refreshSettings();}, resetAsk:()=>openModal(`

${tr('game_and_settings.start_a_new_network')}

${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(S?S.name:tr('common.your_network'))})}

${btn(tr('game_and_settings.delete_and_start_over'),'newgame',{},'red big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`), whatsNewShow:()=>whatsNew(true,true), - updateNow:()=>{save();location.reload();}, + updateNow:()=>{save(true);location.reload();}, updateLater:()=>{$('update').hidden=true;UI.updLater=Date.now();}, helpClose:()=>{if(UI.started)closeModal();else showTitle();}, }); diff --git a/src/game/91-save.js b/src/game/91-save.js index e80a76c..9b0c3f6 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -1,12 +1,19 @@ /* ================= SAVE ================= */ -function save(){if(!S||S.lost)return;S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};try{localStorage.setItem('sot-save-v1',JSON.stringify(S));}catch(e){}UI.lastSave=performance.now();} +/* A network too big for the browser's storage fails to save every time, and turning it into text takes a + moment on huge saves, every 5 seconds and after every click. After a failure the autosave waits before trying + again (1 minute, then 2, 4, at most 5); leaving the page, exporting or another game (a new S) still try at once. */ +function save(force){if(!S||S.lost)return;S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};const f=UI.saveFail; + if(!force&&f&&f.s===S&&performance.now()-f.atsave()); -document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save();else checkUpdate();}); +addEventListener('pagehide',()=>save(true)); +document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='hidden')save(true);else checkUpdate();}); /* Export / import: move a network to another device or keep a backup. The file is the same object the autosave writes, wrapped with a little metadata. */ function saveFileName(){const d=new Date().toISOString().slice(0,10),n=(S&&S.name||'network').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'network';return `series-of-tubes-${n}-${d}.json`;} -function exportSave(){if(!S)return;save();const blob=new Blob([JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S},null,1)],{type:'application/json'}); +function exportSave(){if(!S)return;save(true);const blob=new Blob([JSON.stringify({app:'series-of-tubes',version:APP_VERSION,exported:new Date().toISOString(),S},null,1)],{type:'application/json'}); const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=saveFileName();document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000); toast(tr('save.save_exported_file_is_in_your',{file:esc(saveFileName())}),'good');} function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_is_not_valid_json')};let j;try{j=JSON.parse(txt);}catch(e){return {err:tr('save.that_file_is_not_valid_json')};} diff --git a/tests/persist.test.js b/tests/persist.test.js index 733b1ef..73cd166 100644 --- a/tests/persist.test.js +++ b/tests/persist.test.js @@ -30,6 +30,28 @@ test('leaving the page saves the game', () => { assert.equal(JSON.parse(a.ev("localStorage.getItem('sot-save-v1')")).day, a.ev('S.day')); }); +test('a save too big for the browser is not retried every few seconds, but leaving still tries', () => { + const a = load(); + // A storage that counts tries and refuses the game save, like a full quota. + a.ev(`window.__tries=0;window.__full=true;const P=Object.getPrototypeOf(localStorage),set=P.setItem; + P.setItem=function(k,v){if(k==='sot-save-v1'){__tries++;if(__full){const e=new Error('full');e.name='QuotaExceededError';throw e;}}return set.call(this,k,v);}; + ACT.start({});for(let i=0;i<7;i++)dayTick();__tries=0;UI.saveFail=null;save()`); + assert.equal(a.ev('__tries'), 1); + a.ev('save();save();after()'); + assert.equal(a.ev('__tries'), 1, 'autosaves wait after a failure'); + a.ev("dispatchEvent(new Event('pagehide'))"); + assert.equal(a.ev('__tries'), 2, 'leaving the page still tries'); + assert.equal(a.ev('UI.saveFail.wait'), 120000, 'and each failure waits longer'); + a.ev('__full=false;UI.saveFail.at-=120001;save()'); + assert.equal(a.ev('__tries'), 3, 'tried again once the wait is over'); + assert.equal(JSON.parse(a.ev("localStorage.getItem('sot-save-v1')")).day, a.ev('S.day')); + assert.equal(a.ev('UI.saveFail'), null); + a.ev('save()'); + assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time'); + a.ev('__full=true;save();S=migrate(JSON.parse(JSON.stringify(S)));save()'); + assert.equal(a.ev('__tries'), 6, 'another game (a new state) tries at once'); +}); + test('returning players see what is new after an update, once', () => { const { saved } = playedGame(); execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } }); From 22817c83c59cf1f1867a6433fe31ec460681f08f Mon Sep 17 00:00:00 2001 From: Hugues <16280457+huguesdelamure@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:44:57 +0100 Subject: [PATCH 3/4] Remember each used customer name once S.usedNames only answers "was this name used?", but every offer pushed its name again, also once all names were taken: a 5,500-day save holds 560,345 entries for 129 names, 11.8 of its 22.4 million characters. Names are now added once (useName), and sanitize() drops duplicates from older saves. Player save, 30 days from load, against main: routing and the whole state except usedNames identical, usedNames identical as a set; save 22.4 -> 10.6 million characters, first save in Firefox 95 -> 55 ms, JSON.stringify 68 -> 42 ms. Still over Firefox's quota on this save. --- CHANGELOG.md | 1 + src/game/70-rules/10-helpers.js | 3 +++ src/game/80-simulation/50-sanitize.js | 2 +- src/game/80-simulation/70-customers-and-events.js | 2 +- src/game/88-days/10-day-tick.js | 4 ++-- src/game/90-actions/50-customers.js | 2 +- tests/persist.test.js | 10 ++++++++++ 7 files changed, 19 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03a3406..e891308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - Huge networks stop stuttering every few seconds when their save is too big for the browser to keep: after a failed save the game waits a minute before trying again, then longer, instead of retrying every 5 seconds and after every click. Leaving the page, exporting and new games still save at once. +- Saves of long games are much smaller: the list of customer names already used kept growing by the same names every day (half of a late-game save). Older saves shrink when loaded. - The map of a huge network spends less time working out fiber capacities on every frame, and skips links above or below the screen. ## [1.34.1] — 2026-10-27 diff --git a/src/game/70-rules/10-helpers.js b/src/game/70-rules/10-helpers.js index c082d5e..29d14ec 100644 --- a/src/game/70-rules/10-helpers.js +++ b/src/game/70-rules/10-helpers.js @@ -6,6 +6,9 @@ const pct=x=>Math.round(x*100)+'%'; const reachPct=x=>x>0.999?'100%':x>=0.99?(Math.floor(x*1000)/10).toFixed(1)+'%':pct(x); const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)); const pick=a=>a[Math.floor(Math.random()*a.length)]; +// Names already given to customers, each once: only whether a name is in the list counts. Once every name had been +// used, the same names were added again every day (half a million entries, half of a late-game save). +const useName=n=>{if(!S.usedNames.includes(n))S.usedNames.push(n);}; const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function dateStr(d){const y=1+Math.floor(d/360),m=Math.floor(d/30)%12,dd=d%30+1;return tr('helpers.y_y_mon_d',{y,mon:MONTHS[m],d:dd});} function wrapDx(a,b){let dx=b-a;if(dx>W/2)dx-=W;if(dx<-W/2)dx+=W;return dx;} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 318903e..fd6ffed 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -43,7 +43,7 @@ function sanitize(s){ s.biz=s.biz.filter(okBiz).map(fixBiz);s.offers=s.offers.filter(okBiz).map(fixBiz); s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i)); s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));for(const l of s.loans){if(l.model!==undefined&&!['balloon','storm','transit','astro'].includes(l.model))delete l.model;for(const k of ['apr0','cut','share'])if(l[k]!==undefined&&!isFinite(+l[k]))delete l[k];if(!Array.isArray(l.covs))l.covs=[];l.covs=l.covs.filter(c=>own(COVS,c));}s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank)); - s.usedNames=s.usedNames.filter(x=>typeof x==='string');s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='inbox'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null; + s.usedNames=[...new Set(s.usedNames.filter(x=>typeof x==='string'))];s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='inbox'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null; return {id:typeof e.id==='string'&&e.id.length<=40?e.id:uid(),d:num(e.d,0),t:e.t.slice(0,600),h:typeof e.h==='string'?e.h.slice(0,200):'',k:LOG_KINDS.includes(e.k)?e.k:'',at:Number.isFinite(+e.at)?+e.at:0,o,n:int(e.n,1,9999,1)};}); // One scrubbing center became a list (#117): older saves carry theirs over. if(!Array.isArray(s.scrubs))s.scrubs=s.scrubAt&&isCity(s.scrubAt)?[{city:s.scrubAt,tier:s.scrubTier}]:[];delete s.scrubAt;delete s.scrubTier; diff --git a/src/game/80-simulation/70-customers-and-events.js b/src/game/80-simulation/70-customers-and-events.js index 27142ff..1b90c6e 100644 --- a/src/game/80-simulation/70-customers-and-events.js +++ b/src/game/80-simulation/70-customers-and-events.js @@ -31,7 +31,7 @@ function spawnMega(t,T,nm,mine){ S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('customers_and_events.n_fiber_pairs_in_your_a',{n,a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*n*0.2),reqs:[],exp:S.day+30,mega:true});} } function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops),lv=S.lvl||1; - const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n));const n=list.length?pick(list):pick(T.names);S.usedNames.push(n);return n;}; + const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n));const n=list.length?pick(list):pick(T.names);useName(n);return n;}; if(T.mega){spawnMega(t,T,nm,mine);return;} if(T.event){const city=Math.random()<0.85&&mine.length?pick(mine):pick(OFFC);const bw=pick(T.opts.slice(0,Math.min(T.opts.length,lv+2)));const dur=3+Math.floor(Math.random()*5),start=S.day+12+Math.floor(Math.random()*14); S.offers.push({id:uid(),city,city2:null,name:tr('customers_and_events.name_in_city',{name:nm(),city:CITY[city].name}),type:t,bw,rate:0,reqs:[],start,dur,fee:Math.round(bw*dur*70),exp:start-2});return;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index a7213b4..4fcd4d6 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -86,7 +86,7 @@ function spawnOffer(){ const t=pick(types),T=BIZ_T[t]; if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;} if(T.nni){const city=pick(fabC),prov=pick(FABS.filter(f=>f.cities.includes(city))).id,bw=pick(T.opts),others=mine.filter(c=>c!==city),city2=T.l2&&others.length?pick(others):null;if(T.l2&&!city2)return; - const base=pick(BIZ_N.filter(n=>!S.usedNames.includes(n)).concat(BIZ_N)).replace(/ (Inc\.|Co\.|Ltd)$/,'');const name=tr('day_tick.name_via_fab',{name:base,fab:FAB[prov].name});S.usedNames.push(base); + const base=pick(BIZ_N.filter(n=>!S.usedNames.includes(n)).concat(BIZ_N)).replace(/ (Inc\.|Co\.|Ltd)$/,'');const name=tr('day_tick.name_via_fab',{name:base,fab:FAB[prov].name});useName(base); const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate; S.offers.push({id:uid(),city,city2,prov,name,type:t,bw,rate,reqs:['nni'],exp:S.day+40});return;} let city=(Math.random()<0.65&&mine.length)?pick(mine):pick(OFFC.concat(cnOk()?['pek','sha']:[])),city2=null; @@ -94,7 +94,7 @@ function spawnOffer(){ let bw=T.lv>=2?pick(T.opts):pick(T.opts.slice(0,mine.length>=4?4:3)); const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n)); let name=list.length?pick(list):(T.names?pick(T.names):'Startup #'+Math.floor(Math.random()*999)); - S.usedNames.push(name); + useName(name); if(t==='provedor')city=pick(br); if(t==='hft'){const fin=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'],mf=mine.filter(c=>fin.includes(c));city=mf.length?pick(mf):pick(mine);city2=pick(fin.filter(c=>c!==city));} let rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate; diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index 0ffd772..d83cb3a 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -1,7 +1,7 @@ Object.assign(ACT,{ advertise:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||l.ready>S.day)return;if(S.offers.some(o=>o.link===l.id))return; const t=freeCh(l)>=1?'wwave':pairFree(l)?'dfpair':null;if(!t){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;} - const T=BIZ_T[t],nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);S.usedNames.push(n);return n;}; + const T=BIZ_T[t],nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;}; // A capacity broker finds a buyer at once and keeps 10% of the monthly price. const o=fiberOffer(t,l,nm,0.9);o.broker=true;S.offers.push(o);toast(tr('customers.listed_with_a_capacity_broker_name',{name:esc(o.name),what:esc(o.what)}),'good');sfx('click');after();}, accept:({id})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} diff --git a/tests/persist.test.js b/tests/persist.test.js index 73cd166..dae58db 100644 --- a/tests/persist.test.js +++ b/tests/persist.test.js @@ -52,6 +52,16 @@ test('a save too big for the browser is not retried every few seconds, but leavi assert.equal(a.ev('__tries'), 6, 'another game (a new state) tries at once'); }); +test('customer names already used are remembered once each, and old saves shrink on load', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.usedNames=['A','B','A','A',7,'B'];S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.usedNames)')), ['A', 'B']); + ev("for(let i=0;i<400;i++)dayTick()"); + const u = JSON.parse(ev('JSON.stringify(S.usedNames)')); + assert.equal(new Set(u).size, u.length, 'no name twice'); + assert.deepEqual(errors, []); +}); + test('returning players see what is new after an update, once', () => { const { saved } = playedGame(); execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, env: { ...process.env, OUT, VERSION: '1.1.0', BUILD_DATE: '2026-10-23' } }); From a3dd1dd8103b945f84bb03dc3440681893366ac5 Mon Sep 17 00:00:00 2001 From: Hugues <16280457+huguesdelamure@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:03:04 +0100 Subject: [PATCH 4/4] Busy maps: no link labels or fiber dots above 1,000 lines on screen On a save with 2,700 lines on screen, Firefox spent about 95% of each frame painting, and the dotted line on lit fiber (~160 ms) and the link labels (~55 ms) were half of it, in a tangle where neither can be read. draw() now counts the lines it would paint (linesOnScreen(), same box and margin as its own culling, boxes cached on the geometry) and above MAP_BUSY = 1000 leaves out both. They come back as soon as fewer lines show, zooming in for instance. The selected link keeps its label. Firefox Developer Edition headless, 1600x900 at DPR 2, player save, median of 3x9 frames: save view 414 -> 214 ms, pan 472 -> 238, zoom 0.6 269 -> 181, New York zoom 2 213 -> 107, selected link 412 -> 201. Under the threshold pixels are identical (canvas SHA-1): zoom 3.2 and 6 on the player save, six views of the big-network fixture. --- CHANGELOG.md | 1 + src/game/96-map/60-draw.js | 19 ++++++++++++++----- tests/speed.test.js | 25 +++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e891308..ca7ac0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - Huge networks stop stuttering every few seconds when their save is too big for the browser to keep: after a failed save the game waits a minute before trying again, then longer, instead of retrying every 5 seconds and after every click. Leaving the page, exporting and new games still save at once. - Saves of long games are much smaller: the list of customer names already used kept growing by the same names every day (half of a late-game save). Older saves shrink when loaded. +- Maps with more than a thousand lines on screen draw about twice as fast: they leave out the link labels and the dots on lit fiber, which nobody could read in such a tangle. Zoom in and they come back; the selected link keeps its label. - The map of a huge network spends less time working out fiber capacities on every frame, and skips links above or below the screen. ## [1.34.1] — 2026-10-27 diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 75801b7..8b2a2a3 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -25,9 +25,9 @@ function drawFrame(now){ // cable systems drawCables(ks); // links - const far=lodFar(),PI=pairIdx(); - for(const grp of linkGroups()){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; - const gm=linkGeom(l,PI.get(edgeKey(l))),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'; + 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;gi1,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'; const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);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; if(SX.length0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]); // Still the same path: strokes keep it, so the dotted fiber line goes on top without building it again. - if(df&&!bld&&!dark){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);ctx.stroke();ctx.setLineDash([]);} + 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; ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=far?1:1.5; @@ -50,7 +50,7 @@ function drawFrame(now){ 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 drawBackhoe(mxx,my,now,l.sub);} - else if(z>0.9||sel){const t=lab||(lab=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);} + else if(sel||(z>0.9&&!busy)){const t=lab||(lab=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);} } } // drag preview @@ -90,6 +90,15 @@ function drawFrame(now){ 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;}} } +/* 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 + show, zooming in for instance; the selected link keeps its label. */ +const MAP_BUSY=1000; +// How many lines draw() would paint: one per group and world copy whose box is on screen (the same margin as draw()). +function linesOnScreen(GM,ks){let n=0;for(const gm of GM){const b=gm.box||(gm.box=ptsBox(gm.pts)); + 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]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();} // 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; diff --git a/tests/speed.test.js b/tests/speed.test.js index 0ea9f41..069449b 100644 --- a/tests/speed.test.js +++ b/tests/speed.test.js @@ -121,6 +121,31 @@ test('the map keeps fiber capacities for one frame only, and skips links above o assert.deepEqual(errors, []); }); +test('a map with more than MAP_BUSY lines on screen leaves out link labels and fiber dots, and they come back', () => { + const { ev, errors } = load(); + bigNet(ev); + // Spy on the two things that go: the dotted line on lit fiber and the link labels. + ev("window.__dots=0;window.__labels=[];ctx.setLineDash=d=>{if(d.length===2&&d[0]===1&&d[1]===6)__dots++;};ctx.fillText=t=>{if(/ DF$/.test(t))__labels.push(t);}"); + const frame = () => ev("__dots=0;__labels=[];draw(0);JSON.stringify([__dots,__labels.length])"); + const view = "cam.x=(CITY.fra.x+CITY.lon.x)/2;cam.y=(CITY.fra.y+CITY.lon.y)/2;cam.z=1.6;"; + const lines = () => ev("(()=>{const PI=pairIdx();return linesOnScreen(linkGroups().map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),visibleKs());})()"); + ev("const ps=[['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['fra','lon'],['ams','par']];for(let i=0;i<20;i++){const [a,b]=ps[i%6];S.links.push({id:'dfB'+i,a,b,kind:'df',own:true,km:kmBetween(a,b),ready:0,ch:['zr4']});}compute()"); + ev(view); + assert.ok(lines() < ev('MAP_BUSY')); + const [dots, labels] = JSON.parse(frame()); + assert.ok(dots >= 20 && labels >= 20, 'a normal map shows them'); + ev("const ps2=[['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['fra','lon'],['ams','par']];for(let i=20;i ev('MAP_BUSY')); + assert.equal(frame(), '[0,0]', 'a tangle of lines does not'); + ev("UI.sel={type:'link',id:'dfB3'}"); + assert.equal(frame(), '[0,1]', 'except the label of the selected link'); + ev("UI.sel=null;S.links=S.links.filter(l=>!/^dfB/.test(l.id)||+l.id.slice(3)<20);compute()"); + ev(view); + assert.deepEqual(JSON.parse(frame()), [dots, labels], 'back as soon as fewer lines show'); + assert.deepEqual(errors, []); +}); + test('long lists in the NOC dashboard show 100 rows at a time and grow on request', () => { const { ev, errors } = load(); bigNet(ev);