diff --git a/CHANGELOG.md b/CHANGELOG.md index 28c03f4..a22a7d5 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 game no longer freezes while it routes each day's traffic on big networks. A background thread of the game does the routing, so the map, panels and buttons keep responding while days go by; what the day brings is exactly what it was before. Clicks that change your network still route right away. + ## [2.4.0] — 2026-11-01 - Cable ships now sail out to fix your subsea cables, and you can watch them on the map. A cut at sea calls the nearest free ship of its region's repair club, from ports such as Cornwall, Curaçao, Cape Town, Marseille, Vancouver, Tokyo, Manila and Singapore. The cut lasts while the ship sails out (about 500 km a day), splices for 3 to 5 days in shallow water or a week or two in the deep, and in some countries waits weeks for a repair permit. A ship is busy until it is home again. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 469afbc..d3b7cad 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -141,6 +141,29 @@ link) is only put together for a link when something reads it. Served share per city (`sfOf`) drives eyeball revenue and customer mood. +## Routing in a worker + +During play, each day's `compute()` runs off the main thread (`src/game/80-simulation/28-route-worker.js`), so a big +network does not freeze the page once a day. + +- **Built from the page itself.** The worker is the page's own inline game script (`document.currentScript.textContent`) + run again from a Blob URL, after a short prelude of inert stand-ins for `document`, storage and the other DOM globals, + and the player's dictionary. Nothing is fetched: GitHub Pages still serves one page, and a release cannot mismatch. + In the worker `RW_IN` is true and `boot()` never runs; the catalogs are rebuilt by the same top-level code. +- **The day split.** `dayTick()` is `dayPre()` (the world moves on), `compute()`, `dayPost()` (bills, moods, offers, + goals). In play, `frame()` calls `rwDay()` instead: `dayPre()`, then S and what routing reads of yesterday's R + (`R.load`, `R.l2route`, `R.efg`) are posted, and the next day waits until R comes back and `dayPost()` has run. So a day + sees exactly the routing it would have had in one go: same results, same random numbers. Half a day is never saved. +- **What crosses.** `R.ef` and `R.fl` are lazy getters; their pieces (`R.efp`, `R.flc`) travel instead, typed arrays + transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page. +- **Actions mid-day.** Every `compute()` bumps `RW.gen`. If an action routed while a day was in flight, the worker's + answer is stale: it is dropped and the day ends with the action's R. +- **Fallbacks.** Tests (`__TUBES_TEST__`, and jsdom has no Worker), `window.__TUBES_SYNC__`, a browser without workers, a + post that fails or a worker that errors take the synchronous path (`rwKill()` routes the day in flight on the page). +- **Still on the main thread**, because the caller reads R right away: actions (`after()`), loading a game, failures and + events that fire during a day, standing orders, the chaos monkey, RouteScript what-ifs, the link panel's cut check and + automatic offers. + ## Actions and rendering - Player actions live in `ACT`. Buttons render as `btn(label, act, args, cls, disabled)` diff --git a/src/game/80-simulation/28-route-worker.js b/src/game/80-simulation/28-route-worker.js new file mode 100644 index 0000000..57d9fdb --- /dev/null +++ b/src/game/80-simulation/28-route-worker.js @@ -0,0 +1,56 @@ +/* Routing off the main thread. The worker is this page's own game script run a second time + from a Blob URL: nothing is fetched, so GitHub Pages still serves one page. In the worker, DOM globals are inert + stand-ins and boot() never runs; the catalogs (cities, networks, cones) are rebuilt from the same code. + Only the day uses it: dayPre(), then S goes to the worker, the day waits (no next day starts) and dayPost() runs + when R is back, so a day sees exactly the routing it would have had in one go. An action in between routes + synchronously as always (compute() bumps RW.gen); then the worker's answer is stale and the action's R stands. + Tests (no Worker in jsdom, __TUBES_TEST__) and any worker failure take the synchronous path. */ +const RW_IN=!!self.__TUBES_WORKER__; +const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null; +const RW={w:null,dead:false,seq:0,gen:0,job:null,stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}}; +function rwOn(){return !RW_IN&&!RW.dead&&!window.__TUBES_TEST__&&!window.__TUBES_SYNC__&&typeof Worker==='function'&&!!RW_EL;} +function rwStart(){if(RW.w)return RW.w; + try{const L=LANG,dict=L!=='en'&&window.I18N[L]?JSON.stringify(window.I18N[L]):'null'; + const pre=`'use strict';self.__TUBES_WORKER__=1;self.window=self; +const _n=new Proxy(function(){},{get:(t,k)=>k===Symbol.toPrimitive?()=>0:k==='then'?undefined:_n,apply:()=>_n,construct:()=>_n,set:()=>true}); +const _st={getItem:()=>null,setItem(){},removeItem(){},key:()=>null,length:0}; +Object.assign(self,{document:_n,localStorage:_st,sessionStorage:_st,requestAnimationFrame:()=>0,cancelAnimationFrame(){},innerWidth:1280,innerHeight:800,devicePixelRatio:1, + matchMedia:()=>({matches:false,addEventListener(){},addListener(){}}),Image:_n,Audio:_n,screen:_n,visualViewport:_n,history:_n,getComputedStyle:_n,ResizeObserver:_n,MutationObserver:_n,IntersectionObserver:_n,Path2D:_n,scrollTo(){},SOT_LANG:${JSON.stringify(L)},SOT_LANGS:{},I18N:{}}); +if(${dict})self.I18N[${JSON.stringify(L)}]=${dict}; +`; + const url=URL.createObjectURL(new Blob([pre,RW_EL.textContent,'\n;self.onmessage=e=>rwServe(e.data);'],{type:'text/javascript'})); + const w=RW.w=new Worker(url);URL.revokeObjectURL(url); + w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwDone(m);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();}; + }catch(e){console.error('[tubes] no route worker',e);rwKill();} + return RW.w;} +// Gone for good this session: the day it was routing is routed here instead. +function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;RW.job=null;if(j){try{compute();dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();}} +// One day in play: the first half here, the routing in the worker, the second half when it answers. +function rwDay(){const d=dayPre();if(d===false)return;const w=rwStart(); + if(!w){compute();dayPost(d);rwDayDone();return;} + const t=performance.now(),seq=++RW.seq; + // The worker also needs what compute() reads from yesterday's R: link loads, and the scenic circuits' paths. + try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)});}catch(e){console.error('[tubes] route worker post',e);rwKill();compute();dayPost(d);rwDayDone();return;} + const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,d,gen:RW.gen,t:t1};} +function rwDone(m){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const t=performance.now(); + if(m.err){console.error('[tubes] route worker',m.err);compute();} + else if(RW.gen===j.gen){R=rwUnpack(m.R,m.ef);UI.hotMap=hotByCity();} + const t1=performance.now(),st=RW.stat;st.n++;st.apply+=t1-t;st.wait+=t-j.t;st.work+=m.ms||0; + try{dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();} +function rwDayDone(){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}} +/* R as plain data. R.ef and R.fl are lazy getters, sent as the pieces they are built from (R.efp, R.flc, see efBuild() + and flDefine() in 30-compute.js), their typed arrays moved, not copied. Exits become their ids (all R.fl reads), and an + attack record names its attack in S by id. */ +const FL_COLS=['FREM','FCI','FNJ','FCA','FBZ','FGT','FGI','FGP','FGH','FTI','FII']; +function rwPack(R){const o={};for(const k in R)o[k]=k==='ef'?0:k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k]; + const p=R.efp,c={...R.flc,E:R.flc.E.map(e=>({id:e.id}))},tr=[p.ACN.buffer,p.ACD.buffer];for(const k of FL_COLS)tr.push(c[k].buffer); + return {o,p:{...p,flc:c},tr};} +function rwUnpack(o,p){o.ef={};efBuild(o,p.L,p.ACN,p.ACD,p.NKN,p.NC,p.NN);flDefine(o,p.flc); + const as=ddosAll(S,false);for(const m of o.ddos){m.attack=as.find(a=>a.id===m.attack)||null;m.ports=new Map();}return o;} +// Yesterday's egress sums for scenic routing, as plain data (EgSums is a class; a clone would lose its get()). +const rwEfgOut=efg=>{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[k].t;return o;}; +const rwEfgIn=o=>{const efg={};for(const k in o)efg[k]=new EgSums(o[k]);return efg;}; +// In the worker: route the state it was sent, answer with R. +function rwServe(m){try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{};if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)}); + const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);postMessage({seq:m.seq,R:o,ef:p,ms},tr);} + catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index e8efa7c..5c4cfdd 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -8,7 +8,18 @@ function flbGrow(){const c=Math.max(4096,FLB.cap*2),g=(A,o)=>{const a=new A(c);i FLB.rem=g(Float64Array,FLB.rem);FLB.ci=g(Int32Array,FLB.ci);FLB.nj=g(Int32Array,FLB.nj);FLB.ca=g(Uint8Array,FLB.ca);FLB.bz=g(Uint8Array,FLB.bz);FLB.cap=c;} // R.efg[link]: what each egress put on that link, read by scenic routing the next day (t.g gives each egress its slot in t.v). class EgSums{constructor(t){this.t=t;}get(k){const s=this.t.g.get(k);return s===undefined?undefined:this.t.v[s];}} -function compute(){ +/* R.ef and R.efg from what routing added up per edge (L: [link id, edge index, its sums t]), and R.fl from the flow + columns (c). Also how a route worker's answer is put back together (28-route-worker.js): getters do not cross + threads, so it sends these plain pieces (R.efp, R.flc) and the page rebuilds the same lazy R. */ +function efBuild(R2,L,ACN,ACD,NKN,NC,NN){const efg={};for(const [id,i,t] of L){let rec=null;efg[id]=new EgSums(t); + Object.defineProperty(R2.ef,id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,s] of t.g)rec.eg[k]=t.v[s]; + for(const j of t.n)rec.net[jadj[CIDX[p]]=[]); @@ -302,10 +313,7 @@ function compute(){ for(const o of G.values()){const c=CITIES[o.src].id,cur=R2.latFar[c];if(!cur||o.g>cur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}} // R.ef is read for the link you inspect: each edge's record is put together the first time it is asked for. Scenic // routing only needs the egress amounts, so R.efg keeps those as they are (not listed, so R reads the same). - {const efg={};for(const l of EL){const t=l.tr,i=l.i;let rec=null;efg[l.id]=new EgSums(t); - Object.defineProperty(R2.ef,l.id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,s] of t.g)rec.eg[k]=t.v[s]; - for(const j of t.n)rec.net[j[l.id,l.i,l.tr]),ACN,ACD,NKN,NC,NN); // Active links fill first, by capacity; standby links take what is left over. for(const k in edges){const e=edges[k],ld=e.ld||0,ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;for(const l of e.links){const c=capOf(l);R2.load[l.id]=l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0);}} for(const e of TORD){const m=R2.tNet[e.id]={},b=e.ts*NN;for(const j of TNK[e.ts])m[NET_IDS[j]]=TNA[b+j];} @@ -330,8 +338,7 @@ function compute(){ C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix); R2.costMo=Object.values(C).reduce((a,b)=>a+b,0); R2.revMo=V.eyeballs+V.business+V.ix+V.grant; - // R.fl: the flows as objects, made only when something asks (38-pni-value.js), from this call's own columns. - {let fl=null;Object.defineProperty(R2,'fl',{get(){if(!fl){fl=new Array(NF);for(let i=0;i=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);} else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));} - compute(); + return d;} +function dayPost(d){ ddosNews();ddosTrack(); for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();} S.cash+=(R.revMo-R.costMo)/30; diff --git a/src/game/91-save.js b/src/game/91-save.js index 9737d78..49edca6 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -5,6 +5,8 @@ /* A puzzle is never saved: only its stars are, under their own key (sot-puzzles). While one runs, the network it set aside (UI.pzKeep) is the one saved, to its own slot, so closing the tab mid-puzzle loses nothing. */ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot; + // Half a day (its routing still in the worker) is never saved: the day's end saves instead. + if(RW.job&&st===S){UI.saveDue=true;UI.lastSave=performance.now();return;} if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return; if(st===S){S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st; if(!force&&failed&&performance.now()-f.at5000)save(); // The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them. if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();} - if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} - if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}} + if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0; + // With the route worker one day is in flight at a time; time does not pile up behind it. + if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}} + else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} + if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}} 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;} @@ -47,4 +50,4 @@ function boot(data){ window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}})); if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);} } -slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})); +if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 65612ac..67fa522 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -230,9 +230,9 @@ test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at test('M3: every subsystem that can annoy the player reads a rule', () => { // [function, what it must read] - const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], + const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], - ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"], ['snub', "rule('market')"]]; + ['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"]]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); // and in play: no chaos and no market means a quiet year const g = load(); diff --git a/tests/route-worker.test.js b/tests/route-worker.test.js new file mode 100644 index 0000000..4f673fe --- /dev/null +++ b/tests/route-worker.test.js @@ -0,0 +1,48 @@ +// The route worker (src/game/80-simulation/28-route-worker.js): jsdom has no Worker, so these check the parts that +// decide whether its answer is the same as routing on the page: R packed, cloned the way postMessage clones it, and +// unpacked gives the same R; a day split around its routing is the same day; tests stay on the synchronous path. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); + +const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); +const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close()); + h.dom.window.structuredClone = globalThis.structuredClone; // what postMessage does between the threads + h.ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;compute();`); return h; }; +// R with its lazy parts (R.ef, R.fl) read out, attacks by id. +const SIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()"; + +test('R packed, cloned and unpacked is the same R, lazy parts and key order included', (t) => { + const { ev, errors } = big(t); + const want = ev(SIG); + ev("{const {o,p,tr}=rwPack(R);const c=structuredClone({o,p},{transfer:tr});R=rwUnpack(c.o,c.p);UI.hotMap=hotByCity();}"); + assert.equal(ev(SIG), want); + assert.equal(ev('pniFlows(Object.keys(S.pops)[0])!==null'), true, 'the PNI list reads the unpacked flows'); + assert.deepEqual(errors, []); +}); + +test('the worker side routes what it is sent: same R as routing on the page', (t) => { + const { ev, errors } = big(t); + // rwServe() in the page itself stands in for the worker: it posts back what the worker would. + ev("window.__got=null;window.postMessage=(m)=>{window.__got=m;};"); + ev("{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}"); + ev("R=rwUnpack(structuredClone(__got.R),__got.ef)"); + const fromWorker = ev(SIG); + ev('R=__R0;S=JSON.parse(__S0);compute()'); + assert.equal(ev('JSON.stringify(S)'), ev('__S0'), 'routing does not change S'); + assert.equal(ev(SIG), fromWorker); + assert.deepEqual(errors, []); +}); + +test('a day split around its routing is the same day; tests never use the worker', (t) => { + const a = big(t), b = big(t); + for (const h of [a, b]) h.ev('S.nextFail=S.nextEvent=S.day+99;__reseed(4242)'); + a.ev('for(let i=0;i<3;i++)dayTick()'); + b.ev('for(let i=0;i<3;i++){const d=dayPre();compute();dayPost(d);}'); + const st = "JSON.stringify({day:S.day,cash:S.cash,moods:S.biz.map(b=>b.mood),offers:S.offers.length,served:R.served})"; + assert.equal(b.ev(st), a.ev(st)); + assert.equal(a.ev('rwOn()'), false); + assert.deepEqual([...a.errors, ...b.errors], []); +});