diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c8ca7d..8444386 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. +- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. +- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. - A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. - Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips the peering inbox, hardware shortages and sold-out routes. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. - Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index ea34fc6..33e3d0b 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -96,6 +96,8 @@ function compute(){ const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),n:[],d:[]};EL.push(l);}t.g.set(eg,(t.g.get(eg)||0)+a); let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;}; R2.l2route={};R2.l2split={}; + /* compute() reads only S, except here: scenic circuits remember yesterday's path in R.l2route and R.efg (deliberate + hysteresis, so they do not flap). A second call can still move one; the third gives the same answer as the second. */ /* Scenic routing (#28). "Busy" is judged without the customer's own traffic, or it flees its own load and flips paths every day. Two paths that are about as quiet share the load, and yesterday's choice is kept unless today's is clearly better. */ @@ -283,7 +285,7 @@ function compute(){ C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO*(l.own&&isRdm(l.sys)&&!l.sub?Math.max(1,l.pairs|0):1)+(l.regen|0)*REGEN_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0); C.links=S.links.reduce((a,l)=>a+(l.mo||0),0); C.nni=(S.nni||[]).reduce((a,x)=>a+NNI[x.tier].mo,0); - C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0);R2.p95[t.id]=q;return a+transitMo(t,q);},0); + const htd=histToday();C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0,htd);R2.p95[t.id]=q;return a+transitMo(t,q);},0); C.ix=Object.keys(S.ixp).reduce((a,c)=>a+ixMo(c),0); C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0); C.caches=S.caches.length*CACHE_MO; diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index d86b619..c46efa0 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -1,4 +1,7 @@ -function p95(t,cur){const h=(t.hist||[]).slice(-29).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} +// The last 29 days plus today. Once dayTick() has written today into t.hist (S.hist then ends on today too), that +// sample is today's own: leave it out, or every recompute later that day counts today twice and drops a day. +const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;}; +function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0);} function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js index ab9f52c..53306c0 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -37,20 +37,31 @@ function diversityPossible(a,b,state=S){ if(!CITY[a]||!CITY[b]||a===b)return false; const rules=state.scn&&state.scn.rules||{},key=JSON.stringify([!!state.won,rules]); if(!diversityMap||diversityMap.key!==key){ - const links=[],cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id); - const add=(a,b,id)=>links.push({a,b,id}); - for(let i=0;ip===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(a,b,'cab:'+c.cid); - if(state.won&&seaCab(a,b)&&landing(a)&&landing(b)&&!cnCity(a)&&!cnCity(b))add(a,b,'own:'+a+':'+b); - for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id); + /* Built once per ruleset, over every city pair, so it runs on the first load of every save: on city indices, with + the cables between each pair from a table. A link is the number of its risk: each land trench and your own cable + on its own, every segment of one cable (or one fabric) the same; adj[i] lists [neighbour, risk] in the order the + links were added, as a graph built from a list of them would. */ + const cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),N=cities.length,ix=new Map(cities.map((c,i)=>[c,i])); + const cab=new Map();for(const c of CABLE_PAIRS){const k=c.alands(CITY[c])),land=cities.map(landing),cn=cities.map(cnCity),fab=cities.map(c=>FABS.filter(f=>f.cities.includes(c))),ban=rules.banPairs||[]; + const adj=cities.map(()=>[]),grp=new Map();let n=0,k=0;const add=(i,j,g)=>{let r;if(g===undefined)r=k++;else{r=grp.get(g);if(r===undefined)grp.set(g,r=k++);}adj[i].push(j,r);adj[j].push(i,r);n++;}; + for(let i=0;iLS[j].includes(x)); + if(!sub){add(i,j);add(i,j);} + if(cs)for(const c of cs)if(!ban.some(p=>p===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(i,j,'cab:'+c.cid); + if(state.won&&land[i]&&land[j]&&(sub||cs)&&!cn[i]&&!cn[j])add(i,j); + if(fab[i].length&&fab[j].length)for(const f of FABS)if(fab[i].includes(f)&&fab[j].includes(f))add(i,j,'fab:'+f.id); } - diversityMap={key,links,answers:{}}; + diversityMap={key,ix,adj,links:n,answers:{}}; } - const pair=[a,b].sort().join(':'); - return diversityMap.answers[pair]??(diversityMap.answers[pair]=disjointRoutes(a,b,diversityMap.links)); + const pair=[a,b].sort().join(':'),M=diversityMap; + return M.answers[pair]??(M.answers[pair]=M.ix.has(a)&&M.ix.has(b)&&disjointOn(M.adj,M.ix.get(a),M.ix.get(b))); } +// disjointRoutes() on such a graph: a shortest path by hops, then another one that shares none of its risks. +function disjointOn(adj,a,b){const N=adj.length,bfs=skip=>{const prev=new Int32Array(N).fill(-1),pl=new Int32Array(N),q=[a];prev[a]=a; + for(let h=0;h{const m=new Map();for(const l of S.links)if(!m.has(l.id))m.set(l.id,l);return m;}; diff --git a/src/game/96-map/20-land-and-clouds.js b/src/game/96-map/20-land-and-clouds.js index ed77503..00e3f3a 100644 --- a/src/game/96-map/20-land-and-clouds.js +++ b/src/game/96-map/20-land-and-clouds.js @@ -1,5 +1,8 @@ function rng(seed){return()=>{seed|=0;seed=seed+0x6D2B79F5|0;let t=Math.imul(seed^seed>>>15,1|seed);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};} -function inPoly(x,y,pts){let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;} +// A point outside a ring's bounding box is outside the ring: the box is kept on the ring, so the hundreds of tests +// at load (sea waves, hills, which islets the far view keeps) skip nearly every coastline without walking it. +const polyBox=pts=>{let b=pts.box;if(!b){let x0=Infinity,y0=Infinity,x1=-Infinity,y1=-Infinity;for(const [x,y] of pts){if(xx1)x1=x;if(yy1)y1=y;}b=pts.box=[x0,y0,x1,y1];}return b;}; +function inPoly(x,y,pts){const b=polyBox(pts);if(xb[2]||yb[3])return false;let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;} function smoothPath(pts){const p=new Path2D();const n=pts.length;const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(pts[n-1],pts[0]);p.moveTo(m[0],m[1]);for(let i=0;i0){nx=-nx;ny=-ny;} const base=Math.max(4,Math.min(len*0.1,90)),step=Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*step); const mx=(A.x+bx)/2,my=(A.y+by)/2; - const obs=CITIES.filter(c=>c.id!==l.a&&c.id!==l.b).map(c=>[mx+wrapDx(mx,c.x),c.y]); - const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(dMath.sign(o)*Math.min(Math.abs(o),cap); const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k))); + /* Only cities that could come within `need` of a candidate curve count: a curve stays inside the box of its end and + control points, so a city further than `need` outside the box of all of them only ever measures as clear, and + min(clearance, need) comes out the same without it (the map's first frame did this for every city and link). */ + let x0=Math.min(A.x,bx),x1=Math.max(A.x,bx),y0=Math.min(A.y,by),y1=Math.max(A.y,by); + for(const off of cand){const cx=mx+nx*off,cy=my+ny*off;if(cxx1)x1=cx;if(cyy1)y1=cy;} + const obs=[];for(const c of CITIES){if(c.id===l.a||c.id===l.b)continue;const ox=mx+wrapDx(mx,c.x),oy=c.y;if(ox>=x0-need&&ox<=x1+need&&oy>=y0-need&&oy<=y1+need)obs.push([ox,oy]);} + const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(d=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}} const g={ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};GEO.set(key,g);return g;} diff --git a/tests/compute-idempotent.test.js b/tests/compute-idempotent.test.js new file mode 100644 index 0000000..4a2470f --- /dev/null +++ b/tests/compute-idempotent.test.js @@ -0,0 +1,42 @@ +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.ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();`); return h; }; +// R as JSON; DDoS reports hold the live attack, whose `worst` dayTick updates, so it is named by id. +const rj = (ev) => ev("JSON.stringify(R,(k,v)=>k==='attack'||k==='parent'?(v&&v.id):v)"); + +test('95th percentile: a recompute later in the day bills the same 30 days as the day tick did', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'lvl',tier:1});closeModal()"); + // Thirty days on file, two of them huge: counting today twice (and dropping the oldest day left) would lose one. + ev("S.offers=[];const t=S.transit[0];t.hist=Array.from({length:30},(_,i)=>i===1||i===3?5000:1);S.nextFail=S.nextEvent=S.day+99;dayTick()"); + const tick = ev('R.p95[S.transit[0].id]'), cost = ev('R.cost.transit'); + assert.equal(tick, 5000, 'the tick bills the 29 days before today and today'); + ev('compute()'); + assert.equal(ev('R.p95[S.transit[0].id]'), tick); + assert.equal(ev('R.cost.transit'), cost); + assert.deepEqual(errors, []); +}); + +test('compute() is a pure function of the game: a second call right after a day changes nothing', (t) => { + const { ev, errors } = big(t); + for (let d = 0; d < 4; d++) { + ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick();compute()'); + const a = rj(ev); ev('compute()'); + assert.equal(rj(ev), a, `day ${d}`); + } + assert.deepEqual(errors, []); +}); + +test('scenic circuits keep the last path unless a new one is clearly better, so two calls converge', (t) => { + const { ev, errors } = big(t); + ev("for(const b of S.biz)if(BIZ_T[b.type].l2)b.route='scenic';R=emptyR();compute()"); + ev('compute()'); const b = rj(ev); + ev('compute()'); assert.equal(rj(ev), b); + assert.deepEqual(errors, []); +}); diff --git a/tests/load-time.test.js b/tests/load-time.test.js new file mode 100644 index 0000000..9106cab --- /dev/null +++ b/tests/load-time.test.js @@ -0,0 +1,56 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Work done once when a game loads (the possible-diversity map, link curves, the map's sea and hills) has shortcuts; +// each must give exactly what the plain version gives. + +test('diversity map: the indexed graph answers like disjointRoutes() over every possible link', (t) => { + const { ev, dom, errors } = load(); t.after(() => dom.window.close()); + ev('ACT.start({})'); + // The plain map: one record per possible link, in the order the indexed one adds them. + ev(`window.plainLinks=state=>{const rules=state.scn&&state.scn.rules||{},links=[],cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),add=(a,b,id)=>links.push({a,b,id}); + for(let i=0;ip===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(a,b,'cab:'+c.cid); + if(state.won&&seaCab(a,b)&&landing(a)&&landing(b)&&!cnCity(a)&&!cnCity(b))add(a,b,'own:'+a+':'+b); + for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id);}return links;}`); + const cp = ev('CABLE_PAIRS[0].cid+":"+CABLE_PAIRS[0].a+"-"+CABLE_PAIRS[0].b'); + for (const st of [{ won: false }, { won: true }, { won: false, scn: { rules: { banCities: ['jam', 'lon'], banPairs: [cp] } } }]) { + const r = JSON.parse(ev(`(()=>{const st=${JSON.stringify(st)},L=plainLinks(st);diversityMap=null;diversityPossible('fra','nyc',st); + const ids=CITIES.map(c=>c.id),bad=[];let n=0;for(let i=0;ix===a||x===b))?diversityPossible(a,b,st):disjointRoutes(a,b,L);if(diversityPossible(a,b,st)!==want)bad.push(a+'-'+b);} + return JSON.stringify({links:L.length,mine:diversityMap.links,n,bad})})()`)); + assert.equal(r.mine, r.links, 'the same possible links'); + assert.ok(r.n > 2000); + assert.deepEqual(r.bad, [], JSON.stringify(st)); + } + assert.deepEqual(errors, []); +}); + +test('link curves: skipping far-away cities gives the same bend around the ones in the way', (t) => { + const { ev, dom, errors } = load(); t.after(() => dom.window.close()); + ev('ACT.start({})'); + // bezGeom() as it was: every other city is measured against every candidate curve. + ev(`window.plainGeom=(l,i)=>{const A=CITY[l.a],B=CITY[l.b];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;} + const base=Math.max(4,Math.min(len*0.1,90)),step=Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*step);const mx=(A.x+bx)/2,my=(A.y+by)/2; + const obs=CITIES.filter(c=>c.id!==l.a&&c.id!==l.b).map(c=>[mx+wrapDx(mx,c.x),c.y]); + const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(dMath.sign(o)*Math.min(Math.abs(o),cap); + const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k)));let best=null,bs=-Infinity; + for(const off of cand){const cx=mx+nx*off,cy=my+ny*off,c=clear(cx,cy);if(c>=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}} + return {ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};}`); + const bad = JSON.parse(ev(`(()=>{const ids=CITIES.map(c=>c.id),bad=[];for(let i=0;i { + const { ev, dom, errors } = load(); t.after(() => dom.window.close()); + const bad = ev(`(()=>{const plain=(x,y,pts)=>{let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;}; + let bad=0;for(let x=0;x