The page stays free while big networks play: ambient map at 30 fps, saves in the worker, less to carry back

The game plays exactly as before; only what holds the page changes.

* mapStill() tells three cases apart: still (drawn once a second), ambient (only the animation clock moved: drawn at
  most every 29 ms, so 30 fps on 60 and 120 Hz screens) and moving (camera, pointer, selection, network: every frame).
  The animations follow the clock, so they keep their speed.
* save() skips the storage write when the text is the one the slot already holds (SLOT.txt) and no write is on its
  way; leaving the page still writes. A big autosave that moved on is packed, turned into text, stamped and
  compressed in the route worker (rwSave(), rwGzip()); the page only writes what comes back. A lost worker hands its
  pending saves back to the page (rwSaveBack(), rwGzBack()).
* Less crosses back from the worker: R.efg stays there while R is its own last answer (RW.wR, efg 0), R.egDesc comes
  as 0 or as the entries that changed (rwDescOut()/rwDescIn()), what crossed each link travels as typed arrays decoded
  on demand (rwLOut()/rwLIn()), and the full ports (hotMap) come along with R. Every message is read in order
  (rwMsg()), so both sides always hold the same last answer.
* Idle frames build the diverse-paths map and the latency floors a millisecond at a time (diversityWarm(),
  latWarm()), before the first offer asks.
* Diagnostic info shows how fast days really come: speed asked, speed held, how long a day takes (15-day-pace.js).
* perf-bench: "The NOC intern's shift: opsDay()" and, in Chromium, "One game day in play: page time only", a day
  played with the real route worker counting only the time it holds the page.

Tests: frame-pacing, day-pace, save-size, persist, route-worker (efg as typed arrays, hotMap from the worker),
day-steps (a second page plays the worker: answers without R.egDesc, with only its changes, posts without R.efg,
renewal haggles answered through the worker), intern-dark-fiber-worker, webgl-zoom-sprites, speed.
This commit is contained in:
Antoine 2026-11-07 22:21:22 +01:00
parent d03dde6fcd
commit b9d6319302
No known key found for this signature in database
GPG key ID: 728FF1CE15732B05
22 changed files with 517 additions and 86 deletions

35
tests/day-pace.test.js Normal file
View file

@ -0,0 +1,35 @@
// How fast days really come with the route worker (src/game/88-days/15-day-pace.js), for Settings › Diagnostic info:
// the speed asked, the speed held from the starts of the last days, how long a day takes and the slowest. Measured
// only: the clock starts days as it always did.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('Diagnostic info says the speed asked, the speed held and how long a day takes', () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=8;");
assert.equal(ev('diagPace()'), 'days: x8 asked · measuring');
// A day every 400 ms (x8 asks one every 312.5), each taking 300 ms, one of them 700.
ev('for(let i=0;i<14;i++){const t=1000+i*400;paceStart(t);paceEnd(t+(i===10?700:300));}');
assert.equal(ev('diagPace()'), 'days: x8 asked · x6.3 held (one every 400 ms) · a day takes 333 ms, slowest 700');
// Another speed: the measure starts again.
ev('UI.speed=4;');
assert.equal(ev('diagPace()'), 'days: x4 asked · measuring');
ev('paceStart(9000);paceStart(9625);paceStart(10250);');
assert.match(ev('diagPace()'), /^days: x4 asked · x4\.0 held \(one every 625 ms\)/);
ev('UI.speed=0;');
assert.equal(ev('diagPace()'), 'days: paused');
assert.deepEqual(errors, []);
});
test('the clock with the worker feeds the measure and starts days as it always did', () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();autoPause=()=>false;UI.speed=8;");
// A stand-in worker day that ends at once: one day per 312.5 ms of clock, as before.
ev(`window.__n=0;rwOn=()=>true;RW.w={postMessage(){},terminate(){}};rwDay=()=>{__n++;S.day++;rwDayDone();};
for(let i=0;i<600;i++)runClock(1000/60);`);
assert.equal(ev('__n'), Math.floor(600 * 1000 / 60 / 312.5), 'one day per 312.5 ms of clock');
assert.equal(ev('PACE.st.length'), 13, 'the last days are measured');
assert.match(ev('diagPace()'), /^days: x8 asked · x\d+\.\d held/);
assert.deepEqual(errors, []);
});

View file

@ -1,7 +1,8 @@
// The day as steps (dayRun() in src/game/88-days/10-day-tick.js): every routing a day needs, its own and the
// recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so
// a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that
// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day.
// way must be the day dayTick() plays, move for move, R.egDesc left out of the answers that repeat it and R.efg out of
// the posts that would only send the worker its own, and a frame let through in the middle of each day.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
@ -9,11 +10,12 @@ const path = require('node:path');
const { load } = require('./harness');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
// The big network with an intern running every order, a failure and an event due soon, and its circuits on scenic
// routes, which read yesterday's R.efg. Ids come from Date.now(),
// The big network with an intern running every order, a failure and an event due soon, its circuits on scenic
// routes, which read yesterday's R.efg, and renewal haggles the sales desk answers (slRenRun() routes after them). Ids come from Date.now(),
// so the clock stands still in every page.
const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;
S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;
S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;S.slAuto.ren=true;window.__ren=0;{const f=slRenOne;slRenOne=function(){__ren++;return f.apply(this,arguments);};}
for(const b of S.biz.filter(b=>clOn(b)&&!BIZ_T[b.type].fiber).slice(0,20)){b.te=S.day+28;b.hag={rate:Math.round(b.rate*0.7),until:S.day+28};}
S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;
S.nextFail=S.day+3;S.nextEvent=S.day+5;for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';compute();__reseed(4242);`;
const open = (t, seed) => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
@ -25,18 +27,22 @@ function played(t) {
page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});');
wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
// Answers what is waiting, one message at a time; returns how many routings it served.
let rests = 0, trials = 0;
// kept: answers that left R.egDesc out, the page keeping the one it has; lean: posts that left R.efg out, the worker
// keeping its own.
let kept = 0, lean = 0, rests = 0, delta = 0, trials = 0;
const pump = () => { let n = 0; for (;;) {
if (page.ev('__later.length')) { rests++; page.ev('__later.shift()()'); continue; }
if (!page.ev('__q.length')) break;
if (page.ev('__q[0].efg===0')) lean++;
if (page.ev('!!__q[0].trial')) trials++;
wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out');
page.ev('rwDone(__a)'); n++; } return n; };
if (wk.ev('!!__out.R&&__out.R.egDesc===0')) kept++;
if (wk.ev('!!(__out.R&&__out.R.egDesc&&__out.R.egDesc.dK!==undefined)')) delta++; page.ev('rwMsg(__a)'); n++; } return n; };
// One message to the worker and its answer back (the trial test steps through a day with it).
const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); };
return { ...page, pump, pump1, rests: () => rests, trials: () => trials };
const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwMsg(__a)'); };
return { ...page, pump, pump1, kept: () => kept, lean: () => lean, rests: () => rests, delta: () => delta, trials: () => trials };
}
// R.egDesc too, key for key and in order.
// R.egDesc too, key for key and in order: the worker sends only what changed in it.
const STATE = "JSON.stringify({S,R:{served:R.served,demand:R.demand,rev:R.revMo,cost:R.costMo,load:R.load,useT:R.useT,usePni:R.usePni,egDesc:R.egDesc}})";
// Equal states, or which of their fields differ.
const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B = JSON.parse(b), d = [];
@ -46,8 +52,8 @@ const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B =
test('a day whose routings the worker answers is the day dayTick() plays', (t) => {
const ref = open(t, 777), p = played(t);
ref.ev(SETUP);
// The page itself never routes, the failure on day 3 (failureRun()) and the sales desk's trials (offerTrial())
// included: they are steps like the others, routed by the worker.
// The page itself never routes, the failure on day 3 (failureRun()), the sales desk's trials (offerTrial()) and its
// renewal answers included: they are steps like the others, routed by the worker.
p.ev('window.__pc=0;window.__tr=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};');
let served = 0, extra = 0;
for (let i = 0; i < 12; i++) {
@ -63,7 +69,11 @@ test('a day whose routings the worker answers is the day dayTick() plays', (t) =
assert.ok(ref.ev('S.inc.length') > 0 || ref.ev('S.stats.incidents') > 0, 'a failure happened');
assert.equal(p.ev('__pc'), 0, 'no routing on the page');
assert.ok(p.trials() > 0, `sales trials the worker ran: ${p.trials()}`);
assert.ok(p.ev('__ren') > 0 && p.ev('__ren') === ref.ev('__ren'), `renewal haggles the desk answered: ${p.ev('__ren')}`);
assert.ok(p.ev('S.ops.log.some(e=>e.r.some(([k])=>k==="caches"))'), 'the intern racked cache boxes');
assert.ok(p.kept() > 0 && p.kept() < served, `answers without R.egDesc: ${p.kept()} of ${served}`);
assert.ok(p.delta() > 0, `answers with only what changed in R.egDesc: ${p.delta()}`);
assert.ok(p.lean() > 0 && p.lean() < served, `posts without R.efg: ${p.lean()} of ${served}`);
// A frame through before the intern's shift, after each of the orders on duty (decommissioning aside), and after
// each job of an order (a generator's yields).
const orders = p.ev('OPS_ORDER.slice(0,-1).filter(k=>S.ops.on[k]).length');

View file

@ -1,8 +1,33 @@
// How long a day may run on the page between two frames (src/game/99-loop.js, rwGo()): half a frame, from 3 to 8 ms.
// The map's frame pacing (src/game/99-loop.js, mapStill()): while only the animation clock moves, the map is drawn at
// most 30 times a second; anything else that moves gets every frame; paused, it is drawn about once a second.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// A second of frames at 60 Hz (each() runs before every frame), and how many of them drew the map.
const second = (ev, each = '') => ev(`(()=>{let n=0;const d=draw;draw=t=>{n++;return d(t);};
try{for(let i=0;i<60;i++){window.__now=(window.__now||1000)+1000/60;${each};frame(__now);}}finally{draw=d;}return n;})()`);
test('ambient frames are drawn at most 30 times a second, the camera moving gets them all, paused about one', () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;ACT.launchBB({city:'fra'});closeModal();UI.anim='on';UI.speed=1;autoPause=()=>false;");
second(ev); // the land picture and the first frames settle
const ambient = second(ev);
assert.ok(ambient >= 28 && ambient <= 31, `ambient: ${ambient} draws`);
assert.equal(second(ev, 'cam.x+=0.5'), 60, 'the camera moving');
assert.equal(second(ev, "UI.hover=UI.hover==='fra'?null:'fra'"), 60, 'the pointer over a city and off it');
ev('UI.speed=0');
second(ev);
const paused = second(ev);
assert.ok(paused <= 2, `paused: ${paused} draws`);
ev("UI.anim='off';UI.speed=1");
second(ev);
assert.ok(second(ev) <= 2, 'animations off: nothing moves, nothing to draw');
assert.deepEqual(errors, []);
});
// A day's steps on the page take half a frame at most before letting one through (RW.budget, rwGo()): 8 ms on a 60 Hz
// screen, 3 ms on a 240 Hz one. One long frame (a big save, a tab switch) does not move it much.
test("a day's steps follow the screen: half a frame between two, from 3 to 8 ms", () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
@ -29,3 +54,41 @@ test("a device that cannot hold 50 frames a second gives a day half its frame, 3
});
// The diverse-paths map new offers ask about (60-requirements.js) is built a millisecond a frame, before the first one
// asks: the very map one go would build. One that asks halfway finishes it at once.
test('idle frames build the diverse-paths map in slices, the same map as in one go', () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
const sig = "JSON.stringify([diversityMap.key,diversityMap.links,diversityMap.adj])";
ev('diversityMap=null;DIVW=null;diversityPossible("fra","ams");');
const once = ev(sig);
ev('diversityMap=null;DIVW=null;');
let frames = 0;
for (; frames < 2000 && ev('!diversityMap'); frames++) ev('window.__now=(window.__now||1000)+4;diversityWarm(0.05);');
assert.ok(frames > 3, `built over several frames: ${frames}`);
assert.equal(ev(sig), once, 'the same map');
// Halfway, an offer asks: the rest is built at once, and it is still the same map.
ev('diversityMap=null;DIVW=null;diversityWarm(0.05);');
assert.equal(ev('!diversityMap&&!!DIVW'), true, 'half built');
assert.equal(ev('typeof diversityPossible("fra","ams")'), 'boolean');
assert.equal(ev(sig), once, 'finished at once, the same map');
assert.deepEqual(errors, []);
});
// The latency floors latency customers are offered against (80-geography-and-latency.js) are worked out ahead too, a
// few cities a frame, your POPs first: the same numbers as working one out when asked, even halfway through one.
test('idle frames work the latency floors out ahead, the same numbers as when asked', () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;ACT.buildPop({city:'ams'});");
const ref = ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(latFloor0(c))))");
ev('LATF.clear();LATW=null;');
let n = 0;
for (; n < 5000 && !(ev("LATF.has('fra')&&LATF.has('ams')&&LATF.has('nyc')")); n++) ev('latWarm(0.05)');
assert.ok(n > 3, `over several frames: ${n}`);
assert.equal(ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(LATF.get(c))))"), ref, 'the same floors');
// Halfway through a city, an offer asks about it: finished at once, the same numbers.
ev("LATF.clear();LATW=null;latWarm(0.01);");
const a = ev('LATW&&LATW.a');
assert.ok(a, 'a city half done');
assert.equal(ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor('${a}',b)))`), ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor0('${a}')[CIDX[b]]))`));
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,64 @@
// The intern's line system swap asks first whether a day without the fiber still serves everything (opsDark(),
// 95-standing-orders.js). That test routes the whole network: in play the route worker answers it, like a sales trial,
// so the shift never routes on the page. jsdom has no Worker: a second page plays it (rwServe()), messages cloned both
// ways. The shift played that way is the shift opsDay() plays; an action while the worker routes makes the page test again.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// tests/intern-optical-upgrade.test.js's network: a full, hot fiber Frankfurt–Amsterdam and the long way round through
// Paris on two waves, big enough (tier 4) to carry the day without the fiber, or not (tier 0).
const base = tier => "Date.now=()=>1.7e12;ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=6;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
"for(const c of ['ams','par'])ACT.buildPop({city:c});for(const c of ['fra','ams','par']){S.pops[c].rgen=mainRG(3);S.pops[c].routers=2;}ACT.launchBB({city:'ams'});" +
"S.transit=[];ACT.buyTransit({city:'fra',net:'cog',tier:2});" +
"S.links=[{id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(16).fill('zr4'),km:450,trench:'t1',ready:0,cut:0,mo:1,pairs:1}," +
`{id:'w1',a:'fra',b:'par',kind:'wave',tier:${tier},km:480,cut:0,mo:1},{id:'w2',a:'par',b:'ams',kind:'wave',tier:${tier},km:430,cut:0,mo:1}];compute();` +
"ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap.optup=0;closeModal();S.ops.on.optup=true;S.ops.p.optup={at:80};R.load.f=dfCap(S.links[0])*0.9";
const open = (t) => { const h = load(); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
// The page with a stand-in worker (tests/day-steps.test.js): what it posts waits until pump() hands it to the other page.
function played(t, tier) {
const page = open(t), wk = open(t);
page.ev(base(tier));
page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});');
page.ev('window.__pc=0;{const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};}');
wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
let dark = 0;
const one = () => { if (page.ev('!!(__q[0].trial&&__q[0].trial.dark)')) dark++; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwMsg(__a)'); };
const pump = () => { for (;;) { if (page.ev('__later.length')) { page.ev('__later.shift()()'); continue; } if (!page.ev('__q.length')) break; one(); } };
return { ...page, pump, one, dark: () => dark };
}
const STATE = "JSON.stringify({links:S.links,cash:S.cash,log:S.ops.log,spent:S.ops.spent,no:OPTUP_NO.get('f')??null,served:R.served})";
for (const [tier, sys] of [[4, 'roadm'], [0, 'lite']]) {
test(`the dark fiber test goes to the worker and plays as on the page (waves of tier ${tier}: ${sys})`, (t) => {
const ref = open(t), p = played(t, tier);
ref.ev(base(tier));
ref.ev('opsDay(S.day)');
p.ev('rwGo(opsRun(S.day))');
assert.equal(p.ev('!!(__q.length||__later.length)'), true, 'the shift waits for the worker');
p.pump();
assert.equal(p.ev('!!RW.job'), false, 'the shift is over');
assert.equal(p.ev(STATE), ref.ev(STATE));
assert.equal(p.ev('S.links[0].sys'), sys);
assert.equal(p.dark(), 1, 'the worker tested the fiber dark');
assert.equal(p.ev('__pc'), 0, 'no routing on the page');
assert.equal(p.ev("S.links[0].eqDown===undefined||S.links[0].eqDown>S.day"), true);
assert.deepEqual([...ref.errors, ...p.errors], []);
});
}
test('an action while the worker tests the fiber: the page tests it again on the game as it is', (t) => {
const ref = open(t), p = played(t, 4);
ref.ev(base(4));
ref.ev('opsDay(S.day)');
p.ev('rwGo(opsRun(S.day))');
// Up to the dark fiber's trial, then an action (it routes on the page, as always), then the worker's stale answer.
for (let i = 0; i < 50 && !p.ev('!!(__q[0]&&__q[0].trial&&__q[0].trial.dark)'); i++) { if (p.ev('__later.length')) p.ev('__later.shift()()'); else if (p.ev('__q.length')) p.one(); else break; }
assert.equal(p.ev('!!(__q[0].trial&&__q[0].trial.dark)'), true, 'the trial is in flight');
p.ev('__pc=0;after()');
p.pump();
assert.equal(p.ev('__pc'), 2, "the action's routing, and the test made again here");
assert.equal(p.ev(STATE), ref.ev(STATE));
assert.equal(p.ev('S.links[0].sys'), 'roadm');
assert.deepEqual([...ref.errors, ...p.errors], []);
});

View file

@ -47,9 +47,11 @@ test('a save too big for the browser is not retried every few seconds, but leavi
assert.equal(a.ev('__tries'), 3, 'tried again once the wait is over');
assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day'));
assert.equal(a.ev('UI.saveFail'), null);
a.ev('save()');
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time');
a.ev('__full=true;save();S=migrate(JSON.parse(JSON.stringify(S)));save()');
a.ev('S.cash++;save()');
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time the network changes');
a.ev('save();save()');
assert.equal(a.ev('__tries'), 4, 'and writes nothing while nothing changes');
a.ev('__full=true;S.cash++;save();S=migrate(JSON.parse(JSON.stringify(S)));S.cash++;save()');
assert.equal(a.ev('__tries'), 6, 'another game (a new state) tries at once');
});

View file

@ -15,11 +15,17 @@ const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.c
// 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);})()";
// R.efg, which the next day's routing reads: every link's sums, Map order included (they cross as typed arrays).
const EFG = "JSON.stringify(Object.entries(R.efg).map(([k,e])=>[k,[...e.t.g],e.t.v,e.t.n,e.t.d]))";
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);
const want = ev(SIG), efg = ev(EFG);
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(EFG), efg);
assert.equal(ev(SIG), want);
// Sent back to the worker after an action, a link's sums still clone whole.
assert.equal(ev("JSON.stringify(Object.entries(structuredClone(rwEfgOut(R.efg))).map(([k,t])=>[k,[...t.g],t.v,t.n,t.d]))"), efg);
assert.equal(ev('pniFlows(Object.keys(S.pops)[0])!==null'), true, 'the PNI list reads the unpacked flows');
assert.deepEqual(errors, []);
});
@ -30,10 +36,13 @@ test('the worker side routes what it is sent: same R as routing on the page', (t
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);
const fromWorker = ev(SIG), hot = ev('JSON.stringify(structuredClone(__got.hot))');
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);
// The full ports it found come along (the page no longer works them out again), key order included.
assert.equal(hot, ev('JSON.stringify(UI.hotMap)'));
assert.ok(Object.keys(JSON.parse(hot)).length > 5, 'some ports are full on the big network');
assert.deepEqual(errors, []);
});

View file

@ -11,7 +11,7 @@ const refuse = name => `window.__err=${lit(name)};{const P=Object.getPrototypeOf
test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});UI.saveFail=null;" + refuse('QuotaExceededError'));
ev('save()');
ev('S.cash++;save()');
const toasts = () => [...dom.window.document.querySelectorAll('.toast')].filter(t => /not being saved/.test(t.textContent));
assert.equal(toasts().length, 1, 'one warning');
assert.match(toasts()[0].textContent, /too big for this browser/);
@ -31,7 +31,8 @@ test('#176 a save that does not fit tells the player once, with Export, and the
test('#176 storage that is blocked altogether gets its own advice', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';save()');
// The game moves on first: a save of the very text the slot already holds writes nothing.
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';S.cash+=1;save()');
assert.match(dom.window.document.body.textContent, /private window/);
assert.deepEqual(errors, []);
});
@ -126,3 +127,95 @@ test('#176 a damaged compressed save is kept, marked damaged, and the player is
assert.equal(ev('!!UI.started'), false);
assert.deepEqual(errors, []);
});
// A big network's autosave is compressed in the route worker (rwGzip()), not on the page: deflating it there held the
// page about as long as writing it plain. jsdom has no Worker: a second page answers as the worker, messages cloned
// both ways. A save as the page closes stays plain, and a worker lost mid-job leaves its job to the page.
test('a big autosave is compressed in the route worker and loads back; a closing save stays plain', async () => {
const a = load({ gzip: true }), w = load({ gzip: true });
for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone;
a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()");
const len = a.ev('JSON.stringify(packSave(S)).length');
assert.ok(len >= a.ev('GZ_BG') && len < a.ev('GZ_MIN'), `between the two thresholds: ${len}`);
a.ev("window.__q=[];window.__pz=0;const gp=gzPipe;gzPipe=(...x)=>{__pz++;return gp(...x);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});");
w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};');
const pump = async () => { for (let k = 0; k < 200; k++) {
while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); }
while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); }
if (a.ev("(slotRaw(UI.slot)||'').startsWith(GZ)&&!UI.gzBusy")) return; await new Promise((r) => setTimeout(r, 5)); } };
// Closing: plain text, at once.
a.ev('save(true)');
assert.equal(a.ev('slotRaw(UI.slot)[0]'), '{', 'a save as the page closes is written plain');
// The autosave: compressed by the worker.
a.ev("S.name='Worker Zip';save()");
assert.equal(a.ev('__q.length'), 1, 'the text went to the worker');
await pump();
assert.ok(a.ev("slotRaw(UI.slot).startsWith(GZ)"), 'stored compressed');
assert.equal(a.ev('__pz'), 0, 'nothing was deflated on the page');
a.ev("gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length].join('|');})");
await settle(a.ev, '!!window.__t');
assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length].join('|')"));
// The worker lost while it compresses: the page compresses that save itself.
a.ev("__pz=0;S.name='Page Zip';save();rwKill()");
await settle(a.ev, "!UI.gzBusy&&__pz>0", 'compressed on the page');
a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>window.__t=JSON.parse(t).name)");
await settle(a.ev, '!!window.__t');
assert.equal(a.ev('__t'), 'Page Zip');
assert.deepEqual(a.errors, []);
assert.deepEqual(w.errors, []);
});
// A big network that moved on since its last save is packed, turned into text and compressed by the route worker
// (rwSave()): the page copies the game over and writes what comes back. A paused game (same day) is still compared on
// the page, so an unchanged one is not written again. The worker lost mid-save: the next frame saves again, here.
test('a big game that moved on is saved by the route worker, a paused one is still compared on the page', async () => {
const a = load({ gzip: true }), w = load({ gzip: true });
for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone;
a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()");
a.ev("window.__q=[];window.__pk=0;const pk=packBiz;packBiz=b=>{__pk++;return pk(b);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});");
w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};');
const pump = async (cond) => { for (let k = 0; k < 300; k++) {
while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); }
while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); }
if (a.ev(cond)) return; await new Promise((r) => setTimeout(r, 5)); } assert.fail('never: ' + cond); };
// The first save of the session is made here, and tells the slot which day it holds.
a.ev('save()'); await pump("!UI.gzBusy&&(slotRaw(UI.slot)||'').startsWith(GZ)");
// A day later: the whole save goes to the worker.
a.ev("__pk=0;S.day++;S.name='Moved On';save()");
assert.equal(a.ev('__q.length&&!!__q[0].sv&&!!__q[0].S'), true, 'the game went to the worker');
await pump("!UI.gzBusy&&SLOT.day[UI.slot]===S.day");
assert.equal(a.ev('__pk'), 0, 'nothing was packed on the page');
a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length,!!j.sv].join('|');})");
await settle(a.ev, '!!window.__t');
assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length,true].join('|')"), 'the slot holds the game, stamped');
assert.equal(a.ev('SLOT.txt[UI.slot]===JSON.stringify(packSave(S))'), true, 'the slot knows its text');
a.ev('__pk=0');
// Paused, nothing changed: compared on the page and not written again.
a.ev("__pk=0;window.__w=0;const sp=slotPut;slotPut=(...x)=>{__w++;return sp(...x);};save()");
assert.equal(a.ev('__q.length'), 0, 'nothing went to the worker');
assert.ok(a.ev('__pk') > 0, 'packed here, to compare');
assert.equal(a.ev('__w'), 0, 'the same game is not written again');
// The worker lost while it saves: the next frame saves again.
a.ev("S.day++;save();rwKill()");
await settle(a.ev, '!UI.gzBusy');
assert.equal(a.ev('UI.lastSave'), 0, 'the next frame saves again');
assert.deepEqual(a.errors, []);
assert.deepEqual(w.errors, []);
});
// Loaded from a big slot, the game's first save once it moves on already goes to the worker: the slot knows its day.
test('the first save after loading a big slot goes to the route worker once the game moves on', async () => {
const a = load({ gzip: true });
a.ev(bigBiz + ';' + huge);
a.ev('save(true)');
await settle(a.ev, "(slotRaw(UI.slot)||'').startsWith(GZ)");
const b = load({ gzip: true, storage: { 'sot-save-v1': a.ev('slotRaw(UI.slot)') } });
await settle(b.ev, 'UI.started===true');
b.dom.window.structuredClone = globalThis.structuredClone;
b.ev("window.__q=[];rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){}});");
assert.equal(b.ev('SLOT.big[UI.slot]===true&&SLOT.day[UI.slot]===S.day'), true, 'the slot knows its day and size');
b.ev('S.day++;save()');
assert.equal(b.ev('__q.length===1&&!!__q[0].sv'), true, 'the whole save went to the worker');
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);
});

View file

@ -195,7 +195,9 @@ test('the map is only redrawn when something on it can have changed', () => {
assert.ok(frame('', 1100) > 0, 'and once a second anyway');
assert.ok(frame('WL.key=null') > 0, 'the land picture catching up after a zoom or resize redraws');
ev('UI.speed=1');
assert.ok(frame() > 0 && frame() > 0, 'with the clock running every frame moves');
// Only the animation clock moves: ambient, drawn at most 30 times a second (tests/frame-pacing.test.js).
const run = [frame(), frame(), frame(), frame()].filter((n) => n > 0).length;
assert.ok(run >= 2 && run < 4, `with the clock running the map moves, every other frame at 60 Hz (${run} of 4)`);
ev("ACT.animSet({v:'off'})");
frame(); frame();
assert.equal(frame(), 0, 'with animations off the running map stands still between days');

View file

@ -68,14 +68,15 @@ test('a still map is drawn again when the zoom comes to rest, so the stretched p
const { ev, errors } = open();
ev(STUB);
// Animations off: the loop skips frames while nothing changes.
// mapStill() says how the map stands (MAP_MOVING, MAP_AMBIENT, MAP_STILL; 99-loop.js), not just whether it is still.
ev(`cam.z=1;draw(__T);mapStill(0,__T);UI.drawnAt=__T;cam.z=1.3;__T+=16;mapStill(0,__T);draw(__T);UI.drawnAt=__T;`);
ev(`__T+=16`);
assert.equal(ev('mapStill(0,__T)'), true, 'nothing moved since the last frame');
assert.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'nothing moved since the last frame');
ev(`__T+=300`);
assert.equal(ev('mapStill(0,__T)'), false, 'the zoom has rested: one more frame');
assert.equal(ev('mapStill(0,__T)'), ev('MAP_MOVING'), 'the zoom has rested: one more frame');
ev(`draw(__T);UI.drawnAt=__T;__T+=16`);
assert.equal(ev('ZH.f'), 1);
assert.equal(ev('mapStill(0,__T)'), true, 'and then the map stays still again');
assert.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'and then the map stays still again');
assert.deepEqual(errors, []);
});