Merge remote-tracking branch 'upstream/main' into noc-window

# Conflicts:
#	CHANGELOG.md
#	src/game/99-loop.js
#	tests/harness.js
This commit is contained in:
Christopher Hawker 2026-11-04 20:01:57 +11:00
commit f9d24699c1
83 changed files with 3845 additions and 1031 deletions

View file

@ -20,7 +20,7 @@ const dfLeaseMo=km=>Math.round(400+km*1.0);
const dfBuildCost=km=>Math.round((25000+km*120)*hwMul('build'));
const dfBuildDays=km=>leadDays(Math.round(120+km*0.25)),IRU_DAYS=30;
const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY));
const fmtCap=g=>g>=1000?(+(g/1000).toFixed(1))+'T':g+'G';
const fmtCap=g=>g>=999950?(+(g/1e6).toFixed(g>=9.995e6?0:1))+'P':g>=1000?(+(g/1000).toFixed(1))+'T':g+'G';
const WAVECO=['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','Bolt Technology','youNetworks','G&T (Gin and Transit)'];
const MONTHS=[tr('common.jan'),tr('common.feb'),tr('common.mar'),tr('common.apr'),tr('common.may'),tr('common.jun'),tr('common.jul'),tr('common.aug'),tr('common.sep'),tr('common.oct'),tr('common.nov'),tr('common.dec')];
const REG={AM:tr('common.americas'),SA:tr('common.south_america'),EU:tr('common.europe'),AF:tr('common.africa'),AS:tr('common.asia'),OC:tr('common.oceania')};

View file

@ -1,5 +1,9 @@
/* ================= STATE ================= */
let S=null, R=emptyR();
const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false};
const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false,clockLocked:false};
/* Where tools that are not part of the game (the development page's agent, src/agent/) may hook in. Empty in the page
players get, and the game only ever calls into it with ?.(), so nothing changes there. clockLocked: the clock is not
the player's (an agent drives): no pause, no speed buttons, no auto-pause, and the speed is HOOKS.speed()'s. */
const HOOKS={};
let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++);
function emptyR(){return {nt:{},cone:{},reachNT:0,teBlack:0,tNet:{},egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},latF:{},latFar:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{},ddos:[],haul:[],tgtF:{},bbF:{},fsUse:{},ddosHot:{}};}

View file

@ -51,7 +51,7 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci
if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup();
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}
// Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen.
UI.speed=UI.lastSpeed=rule('clock')?0.5:0;UI.resumeSpeed=null;
UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null;
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal');
renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle')tutorialStart();}

View file

@ -1,9 +1,13 @@
/* ---------- traceroute and looking glass ---------- */
const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x';
function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
// The three ways a customer's circuit can be routed (RT in 90-sites-and-service.js), applied to the trace: follow the metrics,
// lowest latency, or the quietest links (one path; a scenic circuit may share the load between two).
const TR_MODES=['normal','fast','scenic'];
const trUtil=l=>{const c=capOf(l);return c>0?Math.max(0,((R.load&&R.load[l.id])||0)/c):0;};
function trPaths(src,mode){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
// Every link between two cities costs what the pair costs, as in compute(); the trace shows an active link over one on standby.
const pw={};for(const l of live){const k=edgeKey(l);pw[k]=Math.min(pw[k]??Infinity,pairW(k,l.km));}
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=pw[edgeKey(l)]+(l.standby?1e-6:0);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);}
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const k=edgeKey(l),w=(mode==='fast'?linkLat(l)+0.05:mode==='scenic'?pw[k]*(1+10*trUtil(l)):pw[k])+(l.standby?1e-6:0);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);}
const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
const path=dst=>{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};}
function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[];
@ -16,7 +20,7 @@ function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev
// coneChain(peer,net): [peer, …, net], the shortest walk down customer links (the network's up lists, read backwards).
function coneChain(top,id){const prev={[id]:null},q=[id];while(q.length){const x=q.shift();if(x===top)break;for(const u of NET[x].up||[])if(NET[u]&&!(u in prev)){prev[u]=x;q.push(u);}}
if(!(top in prev))return [top,id];const out=[];for(let x=top;x!==null;x=prev[x])out.push(x);return out;}
function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1;
function traceroute(src,to,mode){mode=TR_MODES.includes(mode)?mode:'normal';const P=trPaths(src,mode),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1;
const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);};
hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,tr('traceroute.city_your_router',{city:CITY[src].name}));
const walk=path=>{for(const h of path){const l=h.l,lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}};
@ -45,12 +49,13 @@ function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[]
const order=e.via?tr('traceroute.a_peer_s_customers_come_after'):{c:tr('traceroute.caches_beat_pnis'),p:tr('traceroute.pnis_beat_ix_peering'),ix:tr('traceroute.ix_peering_beats_transit'),t:tr('traceroute.transit_is_the_last_resort')}[e.k];
const cn=cnCity(src)!==!!N.cn?' '+tr('traceroute.crossing_the_great_firewall_here',{p:S.ev.gfw>S.day?35:20}):'';
return {text:lines.join('\n'),why:`${tr('traceroute.exit_exit_in_city',{exit:e.lab,city:CITY[e.city].name})} ${tr('traceroute.rule_and_closer_exits_win_ties',{rule:order[0].toUpperCase()+order.slice(1)})}${e.pref!=='normal'?tr('traceroute.this_one_is_set_to_mode',{mode:e.pref==='high'?tr('common.prefer'):tr('common.backup_only')}):''}.${direct}${e.used>=e.cap*0.999?' '+tr('traceroute.it_is_full_so_some_traffic'):''}${cn}`,asPath};}
function traceModal(src,to){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0];
const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t;
const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)}):traceroute(src,{city:t.slice(5)});
function traceModal(src,to,mode){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0];
const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t;mode=TR_MODES.includes(mode)?mode:UI.trMode||'normal';UI.trMode=mode;
const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)},mode):traceroute(src,{city:t.slice(5)},mode);
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.looking_glass')}</div><h2 style="font-size:26px">${tr('common.traceroute')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<div class="trsel"><label>${tr('common.from')} <select id="trFrom">${pops.map(c=>`<option value="${c}"${c===src?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label>
<label>${tr('common.to')} <select id="trTo"><optgroup label="${tr('common.networks')}">${nets.map(n=>`<option value="net:${n.id}"${t==='net:'+n.id?' selected':''}>${esc(n.name)} (AS${n.asn})</option>`).join('')}</optgroup><optgroup label="${tr('common.your_pops')}">${pops.filter(c=>c!==src).map(c=>`<option value="city:${c}"${t==='city:'+c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</optgroup></select></label>${btn(tr('common.run'),'traceRun',{},'pink sm')}</div>
<pre class="term">${esc(r.text)}</pre>${r.asPath?`<p class="meta">${tr('traceroute.as_path_path',{path:r.asPath.map(a=>'AS'+a).join(' → ')})}</p>`:''}<p class="note">${esc(r.why)}</p>
<div class="btns"><span class="meta" style="align-self:center">${tr('common.route_4a2e')}</span>${TR_MODES.map(m=>btn(RT[m],'traceMode',{m},mode===m?'pink sm':'ghost sm')).join('')}</div>
${mode!=='normal'?`<p class="note">${tr('traceroute.your_traffic_follows_the_metrics_this',{mode:RT[mode]})}</p>`:''}<pre class="term">${esc(r.text)}</pre>${r.asPath?`<p class="meta">${tr('traceroute.as_path_path',{path:r.asPath.map(a=>'AS'+a).join(' → ')})}</p>`:''}<p class="note">${esc(r.why)}</p>
<div class="btns">${btn(tr('common.copy'),'traceCopy',{},'ghost sm')}</div>`);UI.trText=r.text;}

View file

@ -132,7 +132,7 @@ function pzBegin(def){if(!def)return;pzMkStop();mkStop();
if(live)pzFlush();go();}
function pzLeave(){pzMkStop();if(S&&S.ar)arStop(true);mkStop();const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null;
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
if(sv){try{S=migrate(sv);compute();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
// It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told.
if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}}
renderAll();showTitle();}

View file

@ -12,6 +12,7 @@ const INTERNS={
// fees, or (mo) of the running costs the order adds, for caches, which are free to rack but cost rent every month.
const OPS=[
{k:'transit',i:'📈',pop:1,cap:50000,t:N_('ops.o_transit'),d:N_('ops.o_transit_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||v==='have'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}},
{k:'ports',i:'🔌',pop:1,cap:50000,t:N_('ops.o_ports'),d:N_('ops.o_ports_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'}}},
{k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}}},
{k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}},
{k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}},
@ -24,7 +25,7 @@ const OPS=[
const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k);
const OPS_TPL=['bb','transit','ix','kit'];
// What the shift log can say. One line per day: "{name} did this, that and the other."
const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')};
const OPS_SAY={transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')};
// Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little.
const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')];
const OPS_TRIALS=1,OPS_FF_RATE={oncall:1/150,bgp:1/60};
@ -90,6 +91,7 @@ function opsMoNow(){let m=cachesMo();
for(const l of S.links)m+=(l.mo||0)+(l.kind==='df'?(l.spares?Math.round(150+(l.ch||[]).length*80):0)+(l.regen|0)*REGEN_MO:0);
for(const t of S.transit)m+=transitMo(t,0);
for(const p of S.pni){const q=p.up||p,N=NET[p.net];m+=(q.g1?Math.round(PORT[0].pni/2):PORT[q.tier].pni)*(q.n||1)+(N.pol==='paid'&&!paidFree(N)?N.paidFee:0);}
for(const c in S.ixp)if(!S.myIx[c])m+=ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1);
return m;}
const opsFFLine=e=>tr('ops.ff_line',{name:tr(INTERNS[e.i].s),what:tr(OPS_FF[e.f],{city:CITY[e.c].name})});
// Mute what a click would show (toasts, sounds, floaters, the full redraw) and keep the player's selection.
@ -154,6 +156,29 @@ const OPS_RUN={
if(i!==undefined)job={cost:PORT[i].setup,go:()=>ACT.buyTransit({city:c,net:n.id,tier:i}),w:'+'+PORT[i].n};}}
if(!job||!X.can('transit',job.cost)||!X.pay('transit',job.go))break;
X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);}}},
// PNIs and IX ports keep Headroom times today's traffic, hottest first. One port at a POP with several routers gets a
// second in a LAG, so it is not the only way out; anything else moves up to the smallest port size that fits. A PNI
// augment lands weeks later, so that port waits for it. A flood fills ports for a day or two: not worth buying for.
ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[],
// Router ports that pending PNI augments will take when they land are spoken for.
resv=c=>S.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0),room=c=>portsMax(c)-portsUsed(c)+1e-9-resv(c);
// Each port: cap() now, use today, lag() and ups() the jobs it could have as {cost, cap after, w for the log, go}, sig() to see a job took.
for(const p of S.pni){const c=p.city,use=R.usePni[p.id]||0,cap=()=>lagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue;
L.push({city:c,at:c,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(),
lag:()=>n()<LAG_MAX&&!msfNope(p.net,c)&&PORT_SLOT(p.tier)<=room(c)?{cost:1500+PORT[p.tier].setup/2,cap:lagCap(pniG(p),n()+1),w:'+1×'+pniPN(p),go:()=>ACT.lagP({id:p.id,d:1})}:null,
ups:()=>{const out=[];for(let t=p.g1?0:p.tier+1;t<PORT.length&&portShown(t);t++){const q=pniQuote(c,p.net,t,resv(c));if(q&&!q.why)out.push({cost:q.cost,cap:lagCap(PORT[t].g,n()),w:pniPN(p)+'→'+PORT[t].n,go:()=>ACT.pni({city:c,net:p.net,tier:t})});}return out;}});}
// Nominal capacity, not ixCap(): a LACP fault or one building down halves a LAG for a day or two, not worth a bigger port.
for(const x in S.ixp){const c=ixCity(x),use=R.useIx[x]||0,n=()=>(S.ixn||{})[x]||1,cap=()=>lagCap(PORT[S.ixp[x]].g,n())*(isRemote(x)?REMOTE_CAP:1),pop=S.pops[c];if(S.myIx[x]||!(use>0)||!(cap()>0)||cap()>=N*use||!opsHere('ports',c))continue;
const g=()=>PORT[S.ixp[x]].g;
L.push({city:c,at:x,use,u:use/cap(),cap,n,rt:pop?pop.routers||1:1,busy:()=>false,sig:()=>S.ixp[x]+','+n(),
lag:()=>pop&&n()<LAG_MAX&&PORT_SLOT(S.ixp[x])<=room(c)?{cost:ixPortMo(x,S.ixp[x]),cap:cap()*lagCap(g(),n()+1)/lagCap(g(),n()),w:'+1×'+PORT[S.ixp[x]].n,go:()=>ACT.lagIx({city:x,d:1})}:null,
// A remote port (no POP there) stops at 100G; at a POP the router has to take the bigger port.
ups:()=>{const out=[],t0=S.ixp[x];for(let t=t0+1;t<PORT.length&&portShown(t);t++){if(pop?!portOk(c,t)||(PORT_SLOT(t)-PORT_SLOT(t0))*n()>room(c):t>1)continue;
out.push({cost:ixPortMo(x,t)*n(),cap:cap()*lagCap(PORT[t].g,n())/lagCap(g(),n()),w:PORT[t0].n+'→'+PORT[t].n,go:()=>ACT.buyIx({city:x,tier:t})});}return out;}});}
for(const o of L.sort((a,b)=>b.u-a.u))for(let step=0;step<3&&!o.busy()&&o.cap()<N*o.use;step++){
const lag=o.lag(),wantLag=o.n()<2&&o.rt>1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig();
if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;}))break;
X.did('ports',o.at+' '+job.w);}},
optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o);
for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue;
let cap=dfCap(l);const load=(R.load&&R.load[l.id])||0;
@ -197,7 +222,7 @@ const OPS_RUN={
function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}}
const OPS_ORDER=['repair','sales','routers','transit','optics','caches','ix','pni','decom'];
const OPS_ORDER=['repair','sales','routers','transit','ports','optics','caches','ix','pni','decom'];
// The shift: once per game day from dayTick, after outages and events have had their turn.
function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};}
// A new week: last week's tally becomes the shift report, and the one NOC notice of the week.

View file

@ -1,6 +1,6 @@
/* ================= HELPERS ================= */
const fmt$=v=>{const a=Math.abs(v),s=v<0?'-':'';if(a>=1e6)return s+'$'+(a/1e6).toFixed(a>=1e7?1:2)+'M';if(a>=1e3)return s+'$'+(a/1e3).toFixed(a>=1e5?0:1)+'k';return s+'$'+Math.round(a);};
const fmtG=g=>g>=1000?(g/1000).toFixed(g>=10000?1:2)+' Tbps':(g>=100?g.toFixed(0):g.toFixed(1))+' Gbps';
const fmt$=v=>{const a=Math.abs(v),s=v<0?'-':'';if(a>=999.95e6)return s+'$'+(a/1e9).toFixed(a>=9.995e9?1:2)+'B';if(a>=1e6)return s+'$'+(a/1e6).toFixed(a>=1e7?1:2)+'M';if(a>=1e3)return s+'$'+(a/1e3).toFixed(a>=1e5?0:1)+'k';return s+'$'+Math.round(a);};
const fmtG=g=>g>=999950?(g/1e6).toFixed(g>=9.995e6?1:2)+' Pbps':g>=1000?(g/1000).toFixed(g>=10000?1:2)+' Tbps':(g>=100?g.toFixed(0):g.toFixed(1))+' Gbps';
const pct=x=>Math.round(x*100)+'%';
// Reach never rounds up to 100%: Tier 1 needs more than 99.9%, and 99.6% must not look like a full house (#73).
const reachPct=x=>x>0.999?'100%':x>=0.99?(Math.floor(x*1000)/10).toFixed(1)+'%':pct(x);

View file

@ -5,7 +5,12 @@ const DK_CITIES=['fra','mad','mrs','dxb','bom','nyc'];
const isDk=c=>(DK_CITIES.includes(c)||scnRule('dkAll'))&&!!CITY[c]&&!!CITY[c].ix&&!S.myIx[c];
const DK_ADDONS=[['Blackholing Plus™',tr('de_kicks.like_blackholing_but_with_a_plus')],['Route Server Gold',tr('de_kicks.the_same_route_server_in_a')],['Premium Port LEDs',tr('de_kicks.your_port_light_now_blinks_in')],['Strategic Peering Insights',tr('de_kicks.a_monthly_pdf_of_your_own')],['GlobePeer Ready™',tr('de_kicks.makes_your_port_ready_for_a')],['Cloud Exchange Readiness Fee',tr('de_kicks.a_fee_for_being_ready_for')],['Account Manager Lunch Fund',tr('de_kicks.your_account_manager_is_hungry')]];
const DK_STALL=[tr('de_kicks.your_account_manager_would_love_to'),tr('de_kicks.pricing_is_reviewed_by_the_global'),tr('de_kicks.they_sent_a_14_page_nda'),tr('de_kicks.your_account_manager_is_at_a')];
function dkMult(c){if(!S||!isDk(c)||!S.dk||!S.dk.m[c])return 1;const ret=S.dk.ret[c];return S.dk.m[c]*(ret&&ret>S.day?0.6:1);}
// Harmonisation and ended promos raise the personal price, but only up to this multiple of the list price: uncapped, 8-15% a
// year turned a 60-year game into $100k ports. Saves are clamped in sanitize(), remembered quotes too.
const DK_MAX=4;
function dkMult(c){if(!S||!isDk(c)||!S.dk||!S.dk.m[c])return 1;const ret=S.dk.ret[c];return Math.min(S.dk.m[c],DK_MAX)*(ret&&ret>S.day?0.6:1);}
// The rise that actually happened (1 at the ceiling), so a toast never announces more than the bill shows.
function dkRaise(c,f){const dk=S.dk,was=Math.min(dk.m[c],DK_MAX);dk.m[c]=Math.min(DK_MAX,+(dk.m[c]*f).toFixed(3));return dk.m[c]/was;}
function dkAddonMo(c){return S.dk&&S.dk.add[c]?S.dk.add[c].reduce((a,x)=>a+x.mo,0):0;}
function dkState(){S.dk=S.dk||{m:{},add:{},ret:{},retUsed:{},stall:0,q:null};return S.dk;}
function dkQuoteMult(){const pops=Object.keys(S.pops).length,big=Math.min(1.2,pops*0.04+(R.served||0)/20000);return +(0.95+Math.random()*0.45+big).toFixed(2);}
@ -19,8 +24,8 @@ function dkQuoteModal(){const q=S.dk.q,c=q.city,mo=Math.round(PORT[q.tier].ix*(S
<div class="btns">${btn(tr('de_kicks.sign_price_mo',{price:fmt$(mo)}),'dkAccept',{},'pink',S.cash<mo)}${btn(tr('common.haggle'),'dkHaggle',{},'',q.h>=3)}${btn(tr('common.walk_away'),'dkWalk',{},'ghost')}</div>`);}
function dkTick(d){if(!S.dk)return;const dk=S.dk;
for(const c in S.ixp){if(!isDk(c))continue;
if(dk.ret[c]&&dk.ret[c]===d){dk.m[c]=+(dk.m[c]*1.1).toFixed(3);toast(tr('de_kicks.your_ix_promo_ended_price_is',{ix:esc(ixName(c))}),'bad');}
if(dk.m[c]&&(d+hstr(c)%90)%365===0){const f=1.08+Math.random()*0.07;dk.m[c]=+(dk.m[c]*f).toFixed(3);toast(tr('de_kicks.de_kicks_has_harmonised_its_prices',{ix:esc(ixName(c)),p:Math.round((f-1)*100)}),'bad');}
if(dk.ret[c]&&dk.ret[c]===d){dkRaise(c,1.1);toast(tr('de_kicks.your_ix_promo_ended_price_is',{ix:esc(ixName(c))}),'bad');}
if(dk.m[c]&&(d+hstr(c)%90)%365===0){const r=dkRaise(c,1.08+Math.random()*0.07),p=Math.round((r-1)*100);if(p>0)toast(tr('de_kicks.de_kicks_has_harmonised_its_prices',{ix:esc(ixName(c)),p}),'bad');}
const add=dk.add[c]=dk.add[c]||[];
if(add.length<3&&Math.random()<1/150){const a=DK_ADDONS.filter(x=>!add.some(y=>y.n===x[0]));if(a.length){const [n,blurb]=pick(a),mo=Math.round((300+Math.random()*1200)/50)*50;add.push({n,blurb,mo,day:d});
toast(tr('de_kicks.good_news_you_ve_been_enrolled',{addon:esc(n),blurb:esc(blurb),price:fmt$(mo),ix:esc(ixName(c))}),'bad');}}}

View file

@ -46,6 +46,9 @@ function sanitize(s){
{const sp={};if(s.spares&&typeof s.spares==='object')for(const k in s.spares)if(own(OPT,k)){const v=Math.floor(+s.spares[k]);if(v>0)sp[k]=Math.min(999,v);}s.spares=sp;}
s.caches=s.caches.filter(x=>x&&isCity(x.city)&&isNet(x.net)&&NET[x.net].cache).map(x=>(x.id=sid(x.id),x.site=x.site==='b'&&s.pops[x.city]&&s.pops[x.city].site2?'b':'a',x.g===CACHE_BIG?x.g=CACHE_BIG:delete x.g,x));
for(const c of Object.keys(s.ixp)){if(!isIx(c))delete s.ixp[c];else s.ixp[c]=tier(s.ixp[c]);}
// DE-Kicks personal prices: only numbers, and none above the ceiling (older saves compounded them without one).
if(s.dk&&typeof s.dk==='object'){const dk=s.dk;for(const k of ['m','lastQ'])if(dk[k]&&typeof dk[k]==='object'){for(const c of Object.keys(dk[k])){const v=k==='m'?dk[k][c]:dk[k][c]&&dk[k][c].m;
if(!(typeof v==='number'&&v>0&&isFinite(v)))delete dk[k][c];else if(k==='m')dk.m[c]=Math.min(v,DK_MAX);else dk.lastQ[c].m=Math.min(v,DK_MAX);}}else if(k==='m')dk.m={};}
for(const k of ['rs','ixn','ixPref','ixSite'])for(const c of Object.keys(s[k]))if(!isIx(c))delete s[k][c];if(s.ixCut&&typeof s.ixCut==='object'){for(const c of Object.keys(s.ixCut))if(!isIx(c))delete s.ixCut[c];else s.ixCut[c]=Math.min(1,Math.max(0.6,num(s.ixCut[c],1)));}else delete s.ixCut;
for(const c of Object.keys(s.ixn))s.ixn[c]=lag(s.ixn[c]);for(const c of Object.keys(s.ixSite))if(!['a','b','ab'].includes(s.ixSite[c]))s.ixSite[c]='a';
for(const k of Object.keys(s.peers)){const [n,c]=k.split('@');if(!isNet(n)||!isIx(c))delete s.peers[k];}

View file

@ -50,3 +50,15 @@ function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)ret
const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} <small>${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms</small>`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} <small>${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · '+tr('geography_and_latency.old_cuts_often'):''}</small>`})));
return `<h4 class="sub4">${tr('common.route')}</h4><div class="seg">${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}</div>${wr&&wr.cab?`<p class="note">${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}</p>`:''}`;}
function bestLat(a,b,f){const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;}
// The lowest one-way latency anything you could build gets between two cities (#273), the way bestLat() adds it up:
// your own fiber over land (×1.1), or the route of a cable that lands at both ends (your own cable in the low-latency
// design follows it at 0.9 or better). A sea route that no cable takes needs a survey, so it does not count.
// Built from the map alone, so it is worked out once per city.
const LATF=new Map();let LATC=null;
function latFloor(a,b){let D=LATF.get(a);if(!D){LATF.set(a,D=latFloor0(a));}return D[CIDX[b]];}
function latFloor0(a){const n=CITIES.length,D=new Float64Array(n).fill(Infinity),done=new Uint8Array(n);
if(!LATC){LATC=new Map();for(const c of CABLE_PAIRS){const k=Math.min(CIDX[c.a],CIDX[c.b])*4096+Math.max(CIDX[c.a],CIDX[c.b]),w=c.km*Math.min(0.9,CAB[c.cid].lat||1);if(!(LATC.get(k)<=w))LATC.set(k,w);}}
D[CIDX[a]]=0;for(;;){let u=-1,ud=Infinity;for(let i=0;i<n;i++)if(!done[i]&&D[i]<ud){u=i;ud=D[i];}if(u<0)break;done[u]=1;const U=CITIES[u],LU=lands(U);
for(let i=0;i<n;i++){if(done[i])continue;const V=CITIES[i],cw=LATC.get(Math.min(u,i)*4096+Math.max(u,i));
let w=lands(V).some(x=>LU.includes(x))?kmBetween(U.id,V.id)*1.1:Infinity;if(cw<w)w=cw;if(w<Infinity){const d=ud+w/200+0.05;if(d<D[i])D[i]=d;}}}
return D;}

View file

@ -129,5 +129,7 @@ function spawnOffer(){
if(Math.random()<(T.lv>=3?0.65:0.3))reqs.push(pick(pool));
if(T.lv>=3&&Math.random()<0.35){const more=pool.filter(k=>!reqs.includes(k));if(more.length)reqs.push(pick(more));}
const r2=Math.round(rate*(1+reqs.reduce((a,k)=>a+REQS[k].bonus,0)));
S.offers.push({id:uid(),city,city2,name,type:t,bw,rate:r2,reqs,latMax:T.lat?+(kmBetween(city,city2)/200*1.35).toFixed(1):null,exp:S.day+40});
// A latency ceiling must be one something you can build meets (#273), as diverse paths must be possible.
const latMax=T.lat?latMaxOf(city,city2):null;if(T.lat&&!(Math.min(latFloor(city,city2),bestLat(city,city2))<=latMax))return;
S.offers.push({id:uid(),city,city2,name,type:t,bw,rate:r2,reqs,latMax,exp:S.day+40});
}

View file

@ -2,7 +2,7 @@
function spend(c){if(S.cash<c){toast(tr('interface.not_enough_cash_wait_for_revenue'),'bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;}
const ACT={
linkCheck:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return;linkCheckModal(l);},
speed:({v})=>{v=+v;if(pzOn())return;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();},
speed:({v})=>{v=+v;if(pzOn()||UI.clockLocked)return;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();},
help:()=>showHelp(),
dash:()=>{if(!S||pzOn())return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();},
dashClose:()=>{$('dash').hidden=true;},
@ -34,8 +34,8 @@ const ACT={
meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}},
toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();},
phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;if($('modal').classList.contains('link-check'))closeModal();haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();},
phonePlay:()=>{if(pzOn())return;if(S&&!rule('clock'))return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();},
phoneSpeed:()=>{if(pzOn())return;if(S&&!rule('clock'))return;haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();},
phonePlay:()=>{if(pzOn()||UI.clockLocked)return;if(S&&!rule('clock'))return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();},
phoneSpeed:()=>{if(pzOn()||UI.clockLocked)return;if(S&&!rule('clock'))return;haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();},
install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;}
openModal(pitchHtml(false));},
pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();},

View file

@ -0,0 +1,10 @@
/* Step a port down one size: exchange ports, transit ports and PNIs. Upgrading was possible, downsizing meant leaving and rejoining.
A PNI stops at the smallest size the network sells (Tier 1s and closed CDNs: no 10G). */
Object.assign(ACT,{
downIx:({city})=>{const had=S.ixp[city];if(had===undefined||S.myIx[city]||!(had>0))return;
S.ixp[city]=had-1;toast(tr('ix_downgrade.port_downgraded_at_ix',{port:PORT[had-1].n,ix:esc(ixName(city))}),'good');sfx('click');after();},
downT:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t||!(t.tier>0))return;t.tier--;
toast(tr('ix_downgrade.transit_downgraded',{net:esc(NET[t.net].name),city:CITY[t.city].name,port:lagName(t.tier,t.n)}),'good');sfx('click');after();},
downP:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||!pniOn(p)||p.up||p.g1||!(p.tier>pniMin(p.net)))return;p.tier--;
toast(tr('ix_downgrade.pni_downgraded',{net:esc(NET[p.net].name),city:CITY[p.city].name,port:pniPN(p)}),'good');sfx('click');after();},
});

View file

@ -18,6 +18,7 @@ Object.assign(ACT,{
teToggle:()=>{if(!S.te)return;S.te.on=!S.te.on;after();},
trace:({city})=>traceModal(city),
traceRun:()=>{const f=$('trFrom'),t=$('trTo');traceModal(f&&f.value,t&&t.value);},
traceMode:({m})=>{if(!TR_MODES.includes(m))return;const f=$('trFrom'),t=$('trTo');sfx('click');traceModal(f&&f.value,t&&t.value,m);},
traceCopy:()=>{try{navigator.clipboard.writeText(UI.trText||'');toast(tr('route_script_and_tools.copied_paste_it_into_your_favourite'),'good');}catch(e){}},
share:()=>shareModal(),
shareDl:()=>shareFile(f=>{if(!f)return;const a=document.createElement('a');a.href=URL.createObjectURL(f);a.download=f.name;document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);track('share_download');}),

View file

@ -23,7 +23,7 @@ Object.assign(ACT,{
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S;
// An import is a new network next to the others: the one playing here is saved and kept.
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}
<div class="menu-list">

View file

@ -29,6 +29,6 @@ Object.assign(ACT,{
// No game on screen: the map stays empty behind the title.
function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();}
// Back from the title (or a puzzle) into a loaded network.
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}

View file

@ -8,7 +8,8 @@ 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;
// A locked clock's speed is not the player's: the one they left the game at stays saved.
if(st===S){if(!UI.clockLocked)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.at<f.wait){UI.lastSave=performance.now();return;}
UI.lastSave=performance.now();
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.

View file

@ -4,7 +4,8 @@ const SPEEDS=[0.5,1,2,4,8];
function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))return;if(!isPhone()||!S||!UI.started||pzOn()){tb.hidden=true;document.body.classList.toggle('sheet-open',pzOn()&&isPhone()&&!!UI.sel);return;}tb.hidden=false;
const open=UI.leftOpen&&!UI.sel,cur=UI.left||'goals',ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length;
const tab=(k,ic,l,cnt,red)=>`<button class="${open&&cur===k?'on':''}" data-act="phoneTab" data-args='{"t":"${k}"}' aria-label="${esc(l)}"><span class="ic" aria-hidden="true">${ic}</span>${esc(l)}${cnt?(cnt===' '?`<span class="cnt red dot"></span>`:`<span class="cnt${red?' red':''}">${cnt}</span>`):''}</button>`;
const h=(rule('clock')?`<button class="play${UI.speed?'':' paused'}" data-act="phonePlay" aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
// A locked clock's two buttons come from whatever locked it (HOOKS.tabbar), in the same two slots, so the tabs stay put.
const h=(rule('clock')?UI.clockLocked&&HOOKS.tabbar?HOOKS.tabbar():`<button class="play${UI.speed?'':' paused'}" data-act="phonePlay" aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
`<button data-act="phoneSpeed" aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${UI.speed===0.5?'½':(UI.lastSpeed||UI.speed||1)}×</span>${tr('common.speed')}</button>`:'')+
(()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length?' ':'',true)+tab('nets','🌐',tr('common.networks'),'');
if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;}

View file

@ -3,7 +3,8 @@ function fitHud(){const h=$('hud');if(!h)return;h.classList.remove('fit1','fit2'
for(const c of ['fit1','fit2','fit3']){if(h.offsetHeight<=row()*1.5)break;h.classList.add(c);}}
function renderHUD(){
// No clock (puzzles): there is no time to speed up, so the speed buttons go.
{const ck=!S||rule('clock');for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',UI.speed===v);b.hidden=!ck;}}}
// A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud).
{const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();}
$('muteBtn').style.opacity=UI.muted?.4:1;
if(!S)return;
if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;}

View file

@ -48,7 +48,7 @@ function cityPanel(c){
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="tag ${n.type}">${TYPE_L[n.type]}</span></div><div class="meta">${tr('city_panel.price_per_gbps_month_billed_on',{price:pr.toFixed(2)})}</div>${premOnlyAt(n,c)&&!t?`<div class="meta">${tr('city_panel.only_the_cn_too_premium_crossing')}</div>`:''}`;
if(t){const u=R.useT[t.id]||0,cap=lagCap(PORT[t.tier].g,t.n),tdown=t.down>S.day;
h+=`<div class="kv"><span>${lagName(t.tier,t.n)}${tdown?' · <b style="color:var(--bad)">'+tr('common.outage')+'</b>':''}</span><b>${fmtG(u)}</b></div><div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('t',t.id,t.pref)}${carryCtl(t)}${siteCtl('t',t.id,c,t.site)}${premOnlyAt(n,c)?`<p class="note">${tr('city_panel.only_the_cn_too_premium_crossing')}</p>`:premCity(n,c)?`<div class="btns">${btn(t.premium?tr('city_panel.cn_too_premium_on'):tr('city_panel.switch_to_cn_too_premium_x',{x:n.premium}),'togglePrem',{id:t.id},t.premium?'green sm':'sm')}</div>`:''}${(()=>{const top=transitTop([t.id],4);return top.length?`<div class="ttop"><div class="meta"><b>${tr('city_panel.top_destinations_on_this_port')}</b></div>${top.map(([id,v])=>`<div class="meta">${esc(NET[id].name)} · ${fmtG(v)} · <i>${esc(offTransitHint(id,c))}</i></div>`).join('')}</div>`:'';})()}<div class="meta">${tr('city_panel.95th_pct_p95_commit_commit_bill',{p95:fmtG(R.p95[t.id]||0),commit:fmtG(cap*.2),bill:fmt$(Math.max(R.p95[t.id]||0,PORT[t.tier].g*(t.n||1)*.2)*pr+PORT[t.tier].tmo*(t.n||1))})}</div>
<div class="btns">${PORT.map((P2,i)=>i>t.tier&&portShown(i)?btn((t.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}):tr('common.upgrade_port_cost_mo_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}),'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash<P2.setup*(t.n||1)||!portOk(c,i)):'').join('')}${(t.n||1)<LAG_MAX?btn(tr('common.lag_member_cost_mo_mo',{cost:fmt$(PORT[t.tier].setup),mo:fmt$(PORT[t.tier].tmo)}),'lagT',{id:t.id,d:1},'sm',S.cash<PORT[t.tier].setup||!portOk(c,t.tier)):''}${(t.n||1)>1?btn(tr('common.member'),'lagT',{id:t.id,d:-1},'ghost sm'):''}${btn(t.clean?tr('city_panel.clean_pipe_on'):tr('city_panel.clean_pipe_mo_mo_scrubs_ddos',{mo:fmt$(cleanMo(t))}),'cleanPipe',{id:t.id},t.clean?'green sm':'sm')}${btn(UI.confirm===t.id?tr('common.really_cancel'):tr('common.cancel'),'cancelTransit',{id:t.id},'ghost sm')}</div>`;}
<div class="btns">${PORT.map((P2,i)=>i>t.tier&&portShown(i)?btn((t.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}):tr('common.upgrade_port_cost_mo_mo',{port:P2.n,cost:fmt$(P2.setup*(t.n||1)),mo:fmt$(P2.tmo*(t.n||1))}),'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash<P2.setup*(t.n||1)||!portOk(c,i)):'').join('')}${t.tier>0?btn(tr('link_panels.downgrade_port_price',{port:PORT[t.tier-1].n,price:portMo(PORT[t.tier-1].tmo*(t.n||1))}),'downT',{id:t.id},'ghost sm'):''}${(t.n||1)<LAG_MAX?btn(tr('common.lag_member_cost_mo_mo',{cost:fmt$(PORT[t.tier].setup),mo:fmt$(PORT[t.tier].tmo)}),'lagT',{id:t.id,d:1},'sm',S.cash<PORT[t.tier].setup||!portOk(c,t.tier)):''}${(t.n||1)>1?btn(tr('common.member'),'lagT',{id:t.id,d:-1},'ghost sm'):''}${btn(t.clean?tr('city_panel.clean_pipe_on'):tr('city_panel.clean_pipe_mo_mo_scrubs_ddos',{mo:fmt$(cleanMo(t))}),'cleanPipe',{id:t.id},t.clean?'green sm':'sm')}${btn(UI.confirm===t.id?tr('common.really_cancel'):tr('common.cancel'),'cancelTransit',{id:t.id},'ghost sm')}</div>`;}
else h+=`<div class="btns">${PORT.map((P2,i)=>portShown(i)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(P2.setup),mo:fmt$(P2.tmo)}),'buyTransit',{city:c,net:n.id,tier:i},'sm',S.cash<P2.setup||!portOk(c,i)):'').join('')}</div>`;
h+=`</div></div>`;}
h+=`</section>`;

View file

@ -11,7 +11,7 @@ function pniValLine(n,c,v){
return `<div class="meta pval" title="${esc(tr('pni_list.saves_minus_cost',{saved:fmt$(Math.round(v.saved)),cost:fmt$(Math.round(v.cost))}))}">${tr('pni_list.n_here',{g:fmtG(v.want)})}: ${via} → ${tr('pni_list.with_port',{port:PORT[v.tier].n,val})}</div>`;}
function pniRow(c,n,pn,v,chk){let h=`<div class="row prow">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="tag ${n.pol}">${n.pol}</span>${v&&v.worth?` <span class="tag worth">⭐ ${tr('pni_list.worth_it')}</span>`:''}</div><div class="pchips">${pniChip(n.id,c)}</div>${v?pniValLine(n,c,v):''}`;
if(pn&&!pniOn(pn))h+=pniWait(pn,c);
else if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(pniG(pn),pn.n);h+=`<div class="kv"><span>${(pn.n||1)>1?`${pn.n}×${pniPN(pn)} LAG`:pniPN(pn)} PNI</span><b>${fmtG(u)}</b></div>${pn.up?`<div class="meta">${tr('city_panel.augment_on_order_port_about_n',{port:(pn.up.n>1?pn.up.n+'×':'')+(pn.up.g1?'1G':PORT[pn.up.tier].n),n:Math.max(0,pn.up.ready-S.day)})} ${btn(tr('common.chase_it'),'pniChase',{id:pn.id},'ghost sm')}</div>`:''}<div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.up&&pn.up.site==='ab'?'ab':pn.site)}<div class="btns">${PORT.map((P2,i)=>!pn.up&&!msfNope(n.id,c)&&(i>pn.tier||(pn.g1&&i===0))?btn((a=>(pn.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a))({port:P2.n,cost:fmt$((1500+P2.setup/2)*(pn.n||1)),mo:fmt$(P2.pni*(pn.n||1))}),'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${(pn.n||1)<LAG_MAX&&!pn.up&&!msfNope(n.id,c)?btn(tr('common.lag_member_cost_mo_mo',{cost:fmt$(1500+PORT[pn.tier].setup/2),mo:fmt$(PORT[pn.tier].pni)}),'lagP',{id:pn.id,d:1},'sm',S.cash<1500+PORT[pn.tier].setup/2):''}${(pn.n||1)>1?btn(tr('common.member'),'lagP',{id:pn.id,d:-1},'ghost sm'):''}${NET[n.id].cn?btn(pn.sacrif?tr('common.sacrificial_choke'):tr('city_panel.make_sacrificial_contains_floods_1_2'),'sacrif',{id:pn.id},pn.sacrif?'green sm':'sm'):''}${btn(UI.confirm===pn.id?tr('common.really_remove'):tr('common.remove'),'cancelPni',{id:pn.id},'ghost sm')}</div>`;}
else if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(pniG(pn),pn.n);h+=`<div class="kv"><span>${(pn.n||1)>1?`${pn.n}×${pniPN(pn)} LAG`:pniPN(pn)} PNI</span><b>${fmtG(u)}</b></div>${pn.up?`<div class="meta">${tr('city_panel.augment_on_order_port_about_n',{port:(pn.up.n>1?pn.up.n+'×':'')+(pn.up.g1?'1G':PORT[pn.up.tier].n),n:Math.max(0,pn.up.ready-S.day)})} ${btn(tr('common.chase_it'),'pniChase',{id:pn.id},'ghost sm')}</div>`:''}<div class="bar ${barCls(u/cap)}"><i style="width:${u/cap*100}%"></i></div>${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.up&&pn.up.site==='ab'?'ab':pn.site)}<div class="btns">${PORT.map((P2,i)=>!pn.up&&!msfNope(n.id,c)&&(i>pn.tier||(pn.g1&&i===0))?btn((a=>(pn.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a))({port:P2.n,cost:fmt$((1500+P2.setup/2)*(pn.n||1)),mo:fmt$(P2.pni*(pn.n||1))}),'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${!pn.up&&!pn.g1&&pn.tier>pniMin(n.id)&&!msfNope(n.id,c)?btn(tr('link_panels.downgrade_port_price',{port:PORT[pn.tier-1].n,price:portMo(PORT[pn.tier-1].pni*(pn.n||1))}),'downP',{id:pn.id},'ghost sm'):''}${(pn.n||1)<LAG_MAX&&!pn.up&&!msfNope(n.id,c)?btn(tr('common.lag_member_cost_mo_mo',{cost:fmt$(1500+PORT[pn.tier].setup/2),mo:fmt$(PORT[pn.tier].pni)}),'lagP',{id:pn.id,d:1},'sm',S.cash<1500+PORT[pn.tier].setup/2):''}${(pn.n||1)>1?btn(tr('common.member'),'lagP',{id:pn.id,d:-1},'ghost sm'):''}${NET[n.id].cn?btn(pn.sacrif?tr('common.sacrificial_choke'):tr('city_panel.make_sacrificial_contains_floods_1_2'),'sacrif',{id:pn.id},pn.sacrif?'green sm':'sm'):''}${btn(UI.confirm===pn.id?tr('common.really_remove'):tr('common.remove'),'cancelPni',{id:pn.id},'ghost sm')}</div>`;}
else{h+=chk.ok?`<div class="btns">${pniG1(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:'1G',cost:fmt$(PNI_G1_COST),mo:fmt$(Math.round(PORT[0].pni/2))}),'pni',{city:c,net:n.id,tier:-1},'sm',S.cash<PNI_G1_COST||!portOk(c,0)):''}${PORT.map((P2,i)=>portShown(i)&&i>=pniMin(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(1500+P2.setup/2),mo:fmt$(P2.pni)}),'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i)):'').join('')}</div><div class="meta">${pniEta(n.id)}${pniMin(n.id)?' · '+tr('city_panel.no_10g_net_starts_at_100g',{net:esc(n.name)}):pniG1(n.id)?' · '+tr('city_panel.sells_pnis_down_to_1g'):''}</div>${chk.fee?`<div class="meta">${tr('city_panel.paid_peering_price_mo_on_top',{price:fmt$(chk.fee)})}</div>`:''}`:`<div class="why">${esc(chk.why)}</div>`;}
return h+`</div></div>`;}
function pniListHtml(c){const f=UI.pniF||'all',az=UI.pniSort==='az',open=UI.pniOpen||{};

View file

@ -13,7 +13,7 @@ function ixBlock(c,multi){const city=ixCity(c),C=CITY[city],ix=ixName(c),X=XIXM[
for(const x of ad)h+=`<div class="row"><div class="grow"><div class="nm">${esc(x.n)} <span class="tag paid">${tr('common.auto_enrolled')}</span></div><div class="meta">${esc(x.blurb)} · ${tr('common.price_mo',{price:fmt$(x.mo)})}</div></div>${btn(UI.confirm==='dk'+c+x.n?tr('link_panels.lose_exclusive_benefits'):tr('common.opt_out'),'dkOptOut',{city:c,n:x.n},'ghost sm')}</div>`;}
if(isRemote(c))h+=`<p class="note">${trn('link_panels.remote_port_via_a_reseller_1',ixMembers(c).filter(noRemote).length)}</p>`;
if(mine){const f=S.myIx[c].fab|0,N=MYIX_FAB[f+1];h+=`<div class="kv"><span>${tr('link_panels.members_paying_you')}</span><b>${tr('link_panels.n_of_up_to_max_price',{n:S.myIx[c].members.length,max:myFab(c).max,price:fmt$(S.myIx[c].members.length*MYIX_FEE)})}</b></div>${N?`<div class="btns">${btn(N.lvl>lvl()?tr('link_panels.name_fabric_level_lv',{name:N.n,lv:N.lvl}):tr('link_panels.upgrade_fabric_to_name_cost_mo',{name:N.n,cost:fmt$(N.cost),mo:fmt$(N.mo)}),'myIxUp',{city:c},'pink sm',N.lvl>lvl()||S.cash<N.cost)}</div><p class="note">${tr('link_panels.a_bigger_fabric_carries_more_traffic')}</p>`:'<p class="note">'+tr('link_panels.biggest_fabric_money_can_buy')+'</p>'}`;}
else h+=`<div class="btns">${PORT.map((P2,i)=>i>S.ixp[c]&&portShown(i)?btn(tr('common.upgrade_port_price',{port:P2.n,price:portMo(ixPortMo(c,i)*((S.ixn||{})[c]||1))}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)):'').join('')}${S.pops[city]&&((S.ixn||{})[c]||1)<LAG_MAX?btn(tr('common.lag_member_price',{price:portMo(ixPortMo(c,S.ixp[c]))}),'lagIx',{city:c,d:1},'sm',S.cash<ixPortMo(c,S.ixp[c])):''}${((S.ixn||{})[c]||1)>1?btn(tr('common.member'),'lagIx',{city:c,d:-1},'ghost sm'):''}${btn(S.rs[c]?tr('link_panels.leave_route_server'):tr('link_panels.join_route_server'),'rs',{city:c},S.rs[c]?'ghost sm':'pink sm')}${S.rs[c]&&ppol()!=='open'?`<span class="meta">${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}</span>`:''}${btn(UI.confirm==='ix'+c?tr('common.really_leave'):tr('common.leave_ix'),'cancelIx',{city:c},'ghost sm')}</div>`;
else h+=`<div class="btns">${PORT.map((P2,i)=>i>S.ixp[c]&&portShown(i)?btn(tr('common.upgrade_port_price',{port:P2.n,price:portMo(ixPortMo(c,i)*((S.ixn||{})[c]||1))}),'buyIx',{city:c,tier:i},'sm',(!!S.pops[city]&&!portOk(city,i))||(!S.pops[city]&&i>1)):'').join('')}${S.pops[city]&&((S.ixn||{})[c]||1)<LAG_MAX?btn(tr('common.lag_member_price',{price:portMo(ixPortMo(c,S.ixp[c]))}),'lagIx',{city:c,d:1},'sm',S.cash<ixPortMo(c,S.ixp[c])):''}${((S.ixn||{})[c]||1)>1?btn(tr('common.member'),'lagIx',{city:c,d:-1},'ghost sm'):''}${S.ixp[c]>0?btn(tr('link_panels.downgrade_port_price',{port:PORT[S.ixp[c]-1].n,price:portMo(ixPortMo(c,S.ixp[c]-1)*((S.ixn||{})[c]||1))}),'downIx',{city:c},'ghost sm'):''}${btn(S.rs[c]?tr('link_panels.leave_route_server'):tr('link_panels.join_route_server'),'rs',{city:c},S.rs[c]?'ghost sm':'pink sm')}${S.rs[c]&&ppol()!=='open'?`<span class="meta">${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}</span>`:''}${btn(UI.confirm==='ix'+c?tr('common.really_leave'):tr('common.leave_ix'),'cancelIx',{city:c},'ghost sm')}</div>`;
h+=`<div style="margin-top:8px">`;
{const elig=mine?[]:ixMembers(c).filter(id=>!set.has(id)&&peerOk(id,'ix',c).ok);if(elig.length>1)h+=`<div class="btns">${btn(tr('link_panels.request_all_n_willing_peers',{n:elig.length}),'peerAll',{city:c},'pink sm')}</div>`;}
for(const id of ixMembers(c).sort((a,b)=>NSH[b]-NSH[a])){const n=NET[id],on=set.has(id),viaRs=on&&!S.peers[id+'@'+c]&&!mine,chk=peerOk(id,'ix',c);

View file

@ -1,7 +1,7 @@
// Keyboard focus moves into the modal, so Enter or Space can't keep pressing a hidden button behind it.
// The link check on phones sits above the tab bar and is not modal, so the tabs stay usable.
function openModal(html,cls=''){$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}}
function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;}
function openModal(html,cls=''){HOOKS.modal?.(true);$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}}
function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;HOOKS.modal?.(false);}
const NETWORK_NAMES=[
'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom',
'Mostly Online','Buffering & Sons','Lord of the Pings','The Ping Dynasty',

View file

@ -15,12 +15,14 @@ const pref=k=>typeof PREFS[k]==='boolean'?PREFS[k]:PREF_DEF[k];
// Quiet notifications: the player's choice once made, until then on in Best Effort only.
const quietOn=()=>typeof PREFS.quiet==='boolean'?PREFS.quiet:rulePreset()==='soft';
function setPref(k,v){if(!own(PREF_DEF,k))return;PREFS[k]=!!v;try{localStorage.setItem('sot-prefs',JSON.stringify(PREFS));}catch(e){}}
// Stop the clock for something the player must see. Nothing happens if the game is already paused.
function autoPause(){if(!S||!UI.speed)return false;UI.resumeSpeed=UI.speed;UI.speed=0;renderHUD();return true;}
// Stop the clock for something the player must see. Nothing happens if the game is already paused, or not the player's.
function autoPause(){if(!S||!UI.speed||UI.clockLocked)return false;UI.resumeSpeed=UI.speed;UI.speed=0;renderHUD();return true;}
// Put the clock back at a speed (a new game, a loaded or resumed one): unless it is locked, then it runs as the lock says.
function setSpeed(v){UI.speed=UI.clockLocked&&HOOKS.speed?HOOKS.speed():v;}
const resumeAct=()=>({l:tr('common.resume'),act:'speed',args:{v:UI.resumeSpeed||1}});
function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${segBtns(act,cur,opts)}</div></div>${note?`<p class="meta" style="margin:0 0 6px">${note}</p>`:''}`;
const onoff=k=>[[k+':1',tr('common.on')],[k+':0',tr('common.off')]],cur=k=>k+':'+((k==='quiet'?quietOn():pref(k))?1:0);
return `<div style="display:flex;align-items:center"><h2 style="font-size:26px">⚙️ ${tr('common.settings')}</h2><button class="x" data-act="settingsClose" aria-label="${tr('common.close')}">×</button></div><p class="tagline">${tr('settings.saved_on_this_device')}</p>
return `<div style="display:flex;align-items:center"><h2 style="font-size:26px">⚙️ ${tr('common.settings')}</h2><button class="x" data-act="settingsClose" aria-label="${tr('common.close')}">×</button></div><p class="tagline">${tr('settings.saved_on_this_device')}</p>${HOOKS.settings?HOOKS.settings():''}
<h3 class="sub4">${tr('settings.customers_and_alerts')}</h3>
${seg(tr('settings.pause_when_a_customer_is_furious'),'prefSet',cur('pauseFurious'),onoff('pauseFurious'),tr('settings.the_game_stops_so_you_can'))}
${seg(tr('settings.warn_when_a_customer_gets_unhappy'),'prefSet',cur('warnUnhappy'),onoff('warnUnhappy'),tr('settings.an_early_heads_up_below_60'))}

View file

@ -40,5 +40,5 @@ cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',canc
const ZMIN=0.35,ZMAX=16;
function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,ZMIN,ZMAX);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();}
cv.addEventListener('wheel',e=>{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false});
addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'&&(!S||rule('clock'))&&!pzOn()){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}});
addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'&&(!S||rule('clock'))&&!pzOn()&&!UI.clockLocked){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}});

View file

@ -9,15 +9,18 @@ function frame(now){
// 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){NOC.dirty=true;UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
if(NOC.peer)nocPump(now);
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(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;}
}
// 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.
function runClock(dt){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;}}}
/* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map
under it is work nobody sees, so it waits until the map shows again (and no payday money piles up meanwhile). */
function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c.parentNode.hidden)continue;
@ -39,7 +42,7 @@ function boot(data){
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv;
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
if(okSave){slotIn(UI.slot,stamp);UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
if(okSave){slotIn(UI.slot,stamp);UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}