From 3d832df102d68ba6ecb0a8b81d9a8e4b70c84c81 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:38:34 +0000 Subject: [PATCH 1/3] A worker for phones (phase 2): LodPool.count counts a worker at its measured cost, a worker lives in its page's memory class Measured in headless Chromium after the cold scenario a worker holds 29-40 MB (heap and buffers); it was counted as 400 MB, so a phone got none. Now 45 MB each within a third of the budget; the page's budget goes to the worker with the land (small caches there too). iPhone profile, CPU 4x slower: the 3x3 around the camera 39.8 -> 11.0 s, the whole land not within the scenario -> 52.6 s. tools/wcount.test.mjs, tools/wcost.bench.mjs; mem.test counts the threads of LodPool itself. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01UiczdsWP38p6ohAsRYayXG --- build/notes.mjs | 8 ++++++++ docs/ARCHITECTURE.md | 8 ++++++++ docs/WORLDGEN.md | 5 +++-- src/game/32_land.js | 19 ++++++++++++++----- src/game/34_settle.js | 4 ++-- tools/mem.test.mjs | 6 +++--- tools/wcost.bench.mjs | 35 +++++++++++++++++++++++++++++++++++ tools/wcount.test.mjs | 37 +++++++++++++++++++++++++++++++++++++ 8 files changed, 110 insertions(+), 12 deletions(-) create mode 100644 tools/wcost.bench.mjs create mode 100644 tools/wcount.test.mjs diff --git a/build/notes.mjs b/build/notes.mjs index d080365d9..89564a5fb 100644 --- a/build/notes.mjs +++ b/build/notes.mjs @@ -3,6 +3,14 @@ // and once after an update ("What's new"). A PR adds its entry under the number it expects; the merge queue (tools/queue.mjs) // gives it the number it really gets and writes this file. export const NOTES = { + 482: { + ru: ['📱 Телефоны получили помощника: мир теперь строит отдельный поток и на телефоне. Раньше поток считался как 400 МБ памяти, и телефону не доставалось ни одного; замер показал 30–45 МБ', + '⏱️ На iPhone с медленным в 4 раза процессором (эмуляция) земля вокруг после прыжка на 60 км готова за 11 с вместо 40, а вся земля за 53 с (раньше не успевала), памяти занято не больше', + '🧠 Поток живёт в классе памяти своей страницы: на телефоне он держит меньше планов городов, а картинка та же байт в байт. Если страница падала от нехватки памяти, потоков становится меньше'], + en: ['📱 Phones got a helper: the world is now built by a thread of its own on a phone too. A thread used to be counted as 400 MB of memory, so a phone got none; measured, it takes 30–45 MB', + '⏱️ On an iPhone with a 4× slower processor (emulated) the land around after a 60 km jump is ready in 11 s instead of 40, and the whole land in 53 s (it did not finish before), with no more memory taken', + '🧠 The thread lives in its page\'s memory class: on a phone it keeps fewer town plans, and the picture is the same byte for byte. A page that ran out of memory gets fewer threads'], + }, 481: { ru: ["🏘️ Посёлки с участками, как их строят по брошюрам и нормам: таунхаусы с парковкой у входа и садиком за домом (как в Дубае и Подмосковье), таунхаусы с гаражами на заднем проезде (США, английские мьюз), террасы с палисадниками и общими стоянками (Англия, Нидерланды, Германия), американский пригород с газонами и гаражами, коттеджный посёлок за глухим забором с охраной", "🥒 Садовые товарищества (СНТ): участки от 6 соток на гравийных проездах, сетка между соседями, дом в 5 м от улицы, грядки, теплица, сарай, туалет в глубине участка, бочка для воды. У ворот сторожка, правление, водонапорная башня, пожарный пруд, контейнерная площадка и магазин", diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a26b056d4..26f74d9d3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -691,6 +691,14 @@ Design and migration: `docs/WORLDGEN.md`. steep step fails), `tools/navi.test.mjs` (outside the towns that grew: no route off the net, no car on a walker's way; inside a grown town, where a road is not always met by a street yet, the routes that cross the bare plan are counted by the one ratchet left, `TOWNS`, until the towns' own rule closes it). +- **A thread is counted at what it measurably holds, and lives in its page's memory class.** How many workers a device gets follows + the cores and the memory a worker really costs (its heap, buffers and thread after the `cold` scenario, measured in Chromium), never a + guess: counted as 400 MB, a worker never reached a phone, which then made every column, far tile and town plan on its main thread. A + worker takes its page's budget with the land, so the caches of a small device are small there too and its tiles stay the same bytes; + a page that died for memory starts with a smaller budget and so with fewer workers. Before an optimisation is built, its gain is + measured: a generator-only worker script would have saved ~8 MB of a worker's 29–40 MB. Tests: `tools/wcount.test.mjs` (the table of + devices, more memory never means fewer workers, a small worker's caches and bytes), `tools/wcost.bench.mjs` (memory and the `cold` + times with an iPhone's profile). ## Robustness diff --git a/docs/WORLDGEN.md b/docs/WORLDGEN.md index db7734d1c..81f651f14 100644 --- a/docs/WORLDGEN.md +++ b/docs/WORLDGEN.md @@ -139,7 +139,8 @@ service-worker shim) would remove the copies; the copies are KBs, so it is not t Today a phone gets no workers and plans everything on the main thread; parallelism alone cannot fix it. The design answers with: - **A bounded cone** (section 3): the lever that works with 0 workers. -- **A planner worker that is not a copy of the game.** The levels M, R and D need only utilities and generator code (files 00–39 without +- **A planner worker that is not a copy of the game.** (Measured in phase 2: the code is only ~16 MB of a worker's 29–40 MB, so this was not built; phones got their worker by counting it at its measured cost.) + The plan was: the levels M, R and D need only utilities and generator code (files 00–39 without items, meshes or renderer). Built as its own small worker script (about 5 to 10 MB in memory instead of about 50 MB), it fits a phone's budget, so a phone gets one planner worker and the main thread never plans. - **Time slices.** A chunk of any level must fit 8 ms on the reference desktop thread and 30 ms on the low-end profile. If a level's chunk @@ -184,7 +185,7 @@ bytes. |---|---|---|---| | 0 | (perf thread, in progress) settlement planning shared by the workers and cached; bytes identical | no | `cold` with 1–6 workers | | 1 | **Frame** (build 427+, done): `Lv` levels with sizes and declared reads (`src/game/30_lv.js`), the key hash RNG `lvHash`/`lvRnd`, the padding audit, the cone ratchet on today's generator (`tools/lv.test.mjs`, `tools/cone.test.mjs`). The store with single flight and the IndexedDB cache come from phase 0 under `Lv.key` | no | the cone ratchet | -| 2 | **Planner worker** script (levels M–D only) so phones get one; time slices | no | `cold` on the low-end profile, 0 vs 1 worker | +| 2 | **A worker for phones** (build 482, all worlds, bytes identical): measured first in headless Chromium after the `cold` scenario, a worker holds 29–40 MB (JS heap and buffers; the code ~16 MB of it, the rest the towns' plans, roads, railways and street lots it made). A script of the generator alone would save ~8 MB per worker and needs the game's top-level wiring split (`G`, registrations, the ship and fall jobs workers also run): not built. The lever was the count: a worker was counted as 400 MB, so a phone (budget 140–480 MB) got none; now `LodPool.count` counts 45 MB and lets the workers take a third of the budget, and a worker takes its page's budget with the land (`Mem.small` there too: the small caches). An iPhone emulated with the CPU 4× slower: the 3×3 around the camera 39.8 → 11.0 s, the whole land not within the scenario → 52.6 s, the page's memory no higher (`tools/wcost.bench.mjs`). Time slices: still open | no | `tools/wcount.test.mjs`, `cold` on the iPhone profile, 0 vs 1 worker | | 3a | **Coarse decisions without the finer levels** (build 431, gw 57, done): town and airport sites, the ends and lines of roads and footpaths read `Terr.natC`, the land without the lava flows; no volcano traces its flows for them. Of 1489 towns and 2445 road lines in five worlds none moved and one line changed; `Terr.nat` of the first look −38…−52 %, the first look ~1.15 → ~0.83 s (node, 3 worlds). Measured against gw 56 (interchanges planned by nodes, build 430), which had grown the cone by 40–56 % (settlement cells 387–432 → 559–636, `Terr.nat` 135–183k → 165–280k, first look up to 1.9 s): gw 57 takes `Terr.nat` to 105–141k and the first look back to 0.85–1.1 s; the cells stay (phase 5). The ceilings of `tools/cone.known.json` were set again from gw 57 | gw 57 | the cone ratchet | | 5a | **The roads of one settlement** (build after 433, all worlds, bytes identical): an edge is one object per pair of cells (`Roads.pair`), and the edges that end in a settlement (`Roads.ends`) read only the cells between it and its partners. `fork`, `greater` and `Roads.into` (the streets a town plan joins) used a scan of `own()` over 7×7 cells, which read 13×13 cells around each end. Cells of the first look 567/636/559 → 429/481/461; golden, xing, drive and rail unchanged. Anton's two scenes (a desert by home, the walls of a canyon 510 m out) join the cone ratchet as rings of far tiles | no | the cone ratchet | | 5b | **Declared reach for the railways** (gw 61): a railway loop stays within its region's towns ±R ± `RL_REACH` (3000 cells; 1036 loops of 8 worlds measured at most 2482, none dropped) or is not built, `Rail.cand` skips regions whose box misses the query, and `make` asks `Air.site` only of the regions its box meets (an airport lies wholly in its region). Cells of the first look 429/481/461 → 379/181/345, rings of Anton's two scenes 611/591 → 482/467. Tried and dropped: a road reading the greater roads at its ends as their provisional lines (`line0`, no fork) cut 2–6 % more cells but gave 5 more clashes at two roundabouts of seed 5 (xing): the fork of a lesser road must see the finished greater road | gw 61 | the cone ratchet, `tools/rail.mjs test` | diff --git a/src/game/32_land.js b/src/game/32_land.js index 5c2183d8f..927066a43 100644 --- a/src/game/32_land.js +++ b/src/game/32_land.js @@ -53,14 +53,23 @@ const LEAD = { t: 1.2, max: 192, v0: 12, vref: 40, jump: 3000 }; // here, no: // until it has passed. The driver looks for walls and brakes for missing land over its whole stopping distance, far beyond the // 3×3 and the exact ring (RIDE). step: cells between the points of the way, side: cells to each side, every: cells moved before the band is renewed. const RIDE = { step: 16, side: 16, every: 32, old: 1000 }; +const WK_MB = 45; // what one worker costs, MB (its heap, buffers and thread after the cold scenario, tools/wcost.bench.mjs) const LodPool = { ws: null, ok: false, seq: 0, nid: 0, jobs: new Map(), ms: 0, cnt: 0, + // How many workers: the cores (half of them, less one for the page) and the memory. A worker is a second copy of the game and of its + // caches, so it is counted at what it holds, measured in headless Chromium after the cold scenario (tools/wcost.bench.mjs): its JS heap + // and buffers 29 MB with the caches of a small device (it takes its page's budget with the land, so Mem.small holds there too), 25 to + // 40 MB with full ones (the code, then the towns' plans, roads, railways and street lots it made). The workers may take up to a third of + // the budget on top of it. Up to build 481 a worker was counted as 400 MB: a phone (budget 140 to 480 MB) got none and made every + // column, far tile and town plan on its main thread (an iPhone emulated with the CPU 4× slower: the 3×3 around the camera after 39.8 s, + // the whole land not within the scenario; with one worker 11.0 s and 52.6 s, and the page held no more memory). A page that died for + // memory starts with a smaller budget (Mem.lvl): an iPhone keeps its worker after one death (260 → 169 MB) and has none after two. + count(hc, mb) { return Math.min(clamp((hc >> 1) - 1, 1, 6), Math.floor(mb / 3 / WK_MB)); }, init() { this.ws = []; if (IN_WORKER || !SELF_SRC || typeof Worker === 'undefined' || store.get('nowork', 0)) return; try { - // a worker is a second copy of the game (about 50 MB): a device with little memory builds far tiles on the main thread, as before - const hc = navigator.hardwareConcurrency || 4, n = Math.min(clamp((hc >> 1) - 1, 1, 6), Math.floor(Mem.budget / 400)); if (n < 1) return; + const n = this.count(navigator.hardwareConcurrency || 4, Mem.budget); if (n < 1) return; const url = URL.createObjectURL(new Blob([SELF_SRC], { type: 'text/javascript' })); for (let i = 0; i < n; i++) { const w = new Worker(url); w.busy = 0; w.gb = 0; w.lb = 0; w.ll = 0; w.onmessage = e => this.done(w, e.data); w.onerror = e => { if (e && e.preventDefault) e.preventDefault(); Log.add('worker', 'far tiles: ' + (e && e.message || 'error') + (e && e.lineno ? ' @' + e.lineno : '')); Guard.fail('worker:far tiles', new Error((e && e.message || 'error') + (e && e.lineno ? ' @' + e.lineno : ''))); this.fail(); }; this.ws.push(w); } this.ok = true; @@ -72,7 +81,7 @@ const LodPool = { if (!this.ws) this.init(); if (!this.ok || !L.inf || L.opt.hole) return false; if (!L.pid) { - const m = L.meta, sp = m.spawn, msg = { t: 'land', st: StShare.all(L.T), fr: FarShare.all(L.T), id: L.pid = ++this.nid, seed: L.seed, opt: L.opt, pal: L.pal.slice(1), sx: L.lot.sx, sz: L.lot.sz, meta: { ox: m.ox, oz: m.oz, nf: m.nf, fh: m.fh, box: m.box, trees: m.trees, flora: m.flora || null, outs: m.outs || null, spawn: { x: sp.x, y: sp.y - L.ly, z: sp.z, yaw: sp.yaw } } }; + const m = L.meta, sp = m.spawn, msg = { t: 'land', mb: Mem.budget, st: StShare.all(L.T), fr: FarShare.all(L.T), id: L.pid = ++this.nid, seed: L.seed, opt: L.opt, pal: L.pal.slice(1), sx: L.lot.sx, sz: L.lot.sz, meta: { ox: m.ox, oz: m.oz, nf: m.nf, fh: m.fh, box: m.box, trees: m.trees, flora: m.flora || null, outs: m.outs || null, spawn: { x: sp.x, y: sp.y - L.ly, z: sp.z, yaw: sp.yaw } } }; L.wpal = L.pal.length; FarCache.begin(msg); StShare.begin(L); FarShare.begin(L); try { for (const w of this.ws) w.postMessage(msg); } catch (e) { this.fail(); return false; } } @@ -140,7 +149,7 @@ const LodPool = { lands: new Map(), gland(id) { return this.lands.get(id) || null; }, serve(m) { - if (m.t === 'land') { StShare.pre = m.st || null; const pal = m.pal || [], L = new Land(m.seed, { pal: [null], sx: m.sx, sz: m.sz, meta: m.meta }, pal, m.opt); L.meta.outs = m.meta.outs; L.gsent = pal.length + 1; StShare.pre = null; L.T._stOut = StShare.on ? StShare.since(L.T, m.st) : null; FarShare.put(L.T, m.fr); L.T._frOut = FarShare.on ? [] : null; this.lands.set(m.id, L); return null; } // gsent: the colours the page knows + if (m.t === 'land') { if (m.mb) Mem.budget = m.mb; StShare.pre = m.st || null; const pal = m.pal || [], L = new Land(m.seed, { pal: [null], sx: m.sx, sz: m.sz, meta: m.meta }, pal, m.opt); L.meta.outs = m.meta.outs; L.gsent = pal.length + 1; StShare.pre = null; L.T._stOut = StShare.on ? StShare.since(L.T, m.st) : null; FarShare.put(L.T, m.fr); L.T._frOut = FarShare.on ? [] : null; this.lands.set(m.id, L); return null; } // gsent: the colours the page knows if (m.t === 'gen') { // a column of exact voxels; bad: the page makes it itself (a colour the page does not have yet, the lava of a volcano, a failure) const L = this.gland(m.id), t0 = now(); let col = null; let why = !L ? 'land' : L.gsick || (!L.lot.blk && L.lotCol(m.cx, m.cz) ? 'lot' : ''); // the blocks of the home lot are the page's (Land.lotCol) @@ -571,7 +580,7 @@ class Land { if (s.shop) furnishShop(w); else furnishWorld(w, s.P); if (!s.flora) s.flora = (w.meta && w.meta.flora || []).map(t => Object.assign({}, t, { x: t.x + s.x0, y: LG, R: Math.ceil(Sp.reach(t.sp, t.H)) })); s.map = new Uint16Array(w.pal.length); for (let i = 1; i < w.pal.length; i++) s.map[i] = this.bid(w.pal[i][0], w.pal[i][1]); - this.slru.push(s); if (this.slru.length > 6) { const o = this.slru.shift(); o.w = null; o.map = null; } + this.slru.push(s); if (this.slru.length > (Mem.small() ? 3 : 6)) { const o = this.slru.shift(); o.w = null; o.map = null; } } return s.w; } diff --git a/src/game/34_settle.js b/src/game/34_settle.js index 1c000926c..22f1a7e0c 100644 --- a/src/game/34_settle.js +++ b/src/game/34_settle.js @@ -606,7 +606,7 @@ const Settle = { for (const b of P.bld) { const m = b.shop ? 10 : 0; add(b, b.x0 - m, b.z0 - m, b.x1 + m, b.z1 + m); } // a shop reaches out: its terrace and sign stand on the pavement (47_venue.js) for (const b of P.boxes) add(b, b[0], b[2], b[3], b[5]); for (const t of P.trees) { const r = t.rr || 12; add(t, t.x - r, t.z - r, t.x + r, t.z + r); } - this.lru.push(s); const keep = !IN_WORKER && typeof Mem !== 'undefined' && Mem.small() ? 8 : 14; while (this.lru.length > keep) this.lru.shift().plan = null; // a city plan is a few MB: a phone keeps fewer (travelling fast visits one city after another) + this.lru.push(s); const keep = typeof Mem !== 'undefined' && Mem.small() ? 8 : 14; while (this.lru.length > keep) this.lru.shift().plan = null; // a city plan is a few MB: a phone keeps fewer (travelling fast visits one city after another) return P; }, @@ -1019,7 +1019,7 @@ const Settle = { return s.fr = this.farUse(L, r); }, frl: [], - farKeep() { return !IN_WORKER && typeof Mem !== 'undefined' && Mem.small() ? 16 : 48; }, + farKeep() { return typeof Mem !== 'undefined' && Mem.small() ? 16 : 48; }, // (a worker has its page's budget: LodPool.serve 'land') // the record of plan P: plain data, no ids of this land farRec(L, s, P) { const pal = [], pk = new Map(), key = id => { if (!id) return 0; let i = pk.get(id); if (i === undefined) { pal.push(L.pal[id]); pk.set(id, i = pal.length); } return i; }; diff --git a/tools/mem.test.mjs b/tools/mem.test.mjs index 55d8770ee..7c6d37785 100644 --- a/tools/mem.test.mjs +++ b/tools/mem.test.mjs @@ -2,7 +2,7 @@ // The built game in headless Chrome, on the screen of a phone. A phone kills a page that takes too much memory (the page // "reloads by itself"), so the big things are counted and held to budgets: // 1. the start screen: bytes of vertex buffers, drawn catalog models, worker threads; -// 2. a phone (its user agent, no deviceMemory): the small budget, no worker with a copy of the game (the few MB mesher worker is there), small shadow maps; +// 2. a phone (its user agent, no deviceMemory): the small budget, one worker with a copy of the game (the few MB mesher worker is there too), small shadow maps; // 3. standing in the world: the count of the game (Mem) against the budget, and against the real buffers of the context; // 4. the quality gives way to memory: started far too high, it comes down until the count fits the budget of the phone; // 5. a flight of a kilometre down the street and back: nothing grows (columns, furniture batches, buffers, lots, drawn models); @@ -62,7 +62,7 @@ async function open(phone) { try { for(;performance.now()-t<20000;){ w.update(p.x,p.y,p.z,60,w.fx,w.fz); if(w._idle) break; await new Promise(r=>setTimeout(r,0)); } } finally { R.frame=f; } return w._idle })()`; const load = async () => { await until(LOAD, 'the world in view'); await sleep(800); await until(LOAD, 'the world in view'); }; const stat = () => ev(`(()=>{ const w=G.Walk.w, M=window.__M, L=G.Lib, m=G.Mem; let cols=0, lods=0; if(w){ cols=w.cols.size; for(const k of w.lods) lods+=k.size; } - if (w) m.world = w.mem(); return { mem: m.mb(), world: m.world/${MB}, gpu: m.gpu/${MB}, buf: M.buf/${MB}, nbuf: M.nbuf, workers: M.workers - (G.MeshW.w ? 1 : 0), meshw: G.MeshW.w ? 1 : 0, budget: m.budget, models: L.live.length, lib: L.mem()/${MB}, cols, lods, fb: w?w.fb.size:0, groups: w?w.groups.size:0, slots: w?w.slots.size:0, insts: w?w.insts.filter(Boolean).length:0, q: G.Quality.cur(), shadow: G.Shadow.size }; })()`); + if (w) m.world = w.mem(); return { mem: m.mb(), world: m.world/${MB}, gpu: m.gpu/${MB}, buf: M.buf/${MB}, nbuf: M.nbuf, workers: G.LodPool.ws ? G.LodPool.ws.length : 0, meshw: G.MeshW.w ? 1 : 0, budget: m.budget, models: L.live.length, lib: L.mem()/${MB}, cols, lods, fb: w?w.fb.size:0, groups: w?w.groups.size:0, slots: w?w.slots.size:0, insts: w?w.insts.filter(Boolean).length:0, q: G.Quality.cur(), shadow: G.Shadow.size }; })()`); // lodC: the far rings as wide as they get at this quality on this screen, fixed from the start (in the game they widen over the first seconds) const play = async (q, lodC = 64) => { await ev('G.Game.play(); 1'); await until('!!G.Walk.w && !!G.Walk.hud', 'the world'); await sleep(3000); await ev(`(()=>{ G.Quality.lock = ${q}; Object.defineProperty(G.Walk.w, 'lodC', { get: () => ${lodC}, set() {} }); return 1 })()`); await sleep(1500); await load(); }; return { page, ev, until, load, load1: () => until(LOAD, 'a stop of the flight'), stat, play, errs }; @@ -124,7 +124,7 @@ try { const T = await open(true); let s = await T.stat(); show('2. phone, start screen', s); check(s.budget <= LIMIT.phoneFit, `the budget of a phone: ${r1(s.budget)} MB`); - check(s.workers === 0, `no worker thread with a copy of the game on a phone: ${s.workers} (the small mesher worker of the Rust core is there: ${s.meshw})`); + check(s.workers === 1, `one worker thread with a copy of the game on a phone (counted at what it holds, LodPool.count; tools/wcount.test.mjs): ${s.workers} (the small mesher worker of the Rust core is there: ${s.meshw})`); // far too high a quality, with the far cubes as fine as the screen of a real phone asks for (the test window is small) await T.play(9, 240); await T.ev('G.Quality.memTest = true; 1'); await T.load(); s = await T.stat(); show('4. phone, q 9', s); diff --git a/tools/wcost.bench.mjs b/tools/wcost.bench.mjs new file mode 100644 index 000000000..48f403f79 --- /dev/null +++ b/tools/wcost.bench.mjs @@ -0,0 +1,35 @@ +// What a far-tile worker costs and gives (LodPool.count, 32_land.js): headless Chromium, the renderer's PSS (all its threads, workers +// included) on the start screen and after the cold scenario (98_perf.js: a jump 60 km away, seconds until the land under the camera, the +// 3×3 around and everything is made), with the workers the build decides on, or none (NW=0: localStorage hsh.nowork). +// node tools/wcost.bench.mjs [a.html b.html …] PHONE=1: an iPhone (Mem: a phone, budget 260 MB) CORES (default 8) REP (1) +// THROTTLE=4: the page's main thread 4× slower (CDP Emulation.setCPUThrottlingRate; the workers run at full speed) +import './chrome.mjs'; +import puppeteer from 'puppeteer-core'; +import fs from 'node:fs'; +import path from 'node:path'; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const htmls = process.argv.slice(2); if (!htmls.length) htmls.push('index.html'); +const PHONE = !!process.env.PHONE, CORES = +(process.env.CORES || 8), REP = +(process.env.REP || 1), THR = +(process.env.THROTTLE || 1), NW0 = process.env.NW === '0'; +const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1'; +async function once(html) { + const browser = await puppeteer.launch({ executablePath: process.env.CHROME || '/opt/pw-browsers/chromium', headless: 'new', protocolTimeout: 0, args: ['--ignore-gpu-blocklist', '--enable-webgl', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--no-sandbox', '--window-size=960,600'] }); + try { + const page = await browser.newPage(); await page.setViewport({ width: 960, height: 600 }); + if (PHONE) { await page.setUserAgent(IPHONE); await page.evaluateOnNewDocument(() => Object.defineProperty(Navigator.prototype, 'deviceMemory', { get: () => undefined })); } // Safari has no deviceMemory + await page.evaluateOnNewDocument(nw0 => { localStorage.setItem('hsh.lang', '"en"'); if (nw0) localStorage.setItem('hsh.nowork', '1'); }, NW0); + await page.evaluateOnNewDocument(c => Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => c }), CORES); + await page.goto('file://' + path.resolve(html)); + for (let i = 0; i < 240 && !await page.evaluate('!!(window.G && G.UIStart && G.UIStart.demo)').catch(() => false); i++) await sleep(500); + const pss = () => { let r = 0; for (const p of fs.readdirSync('/proc').filter(p => /^\d+$/.test(p))) { try { const c = fs.readFileSync(`/proc/${p}/cmdline`, 'utf8'); if (!c.includes('--type=renderer') || c.includes('extension')) continue; r += +/Pss:\s+(\d+)/.exec(fs.readFileSync(`/proc/${p}/smaps_rollup`, 'utf8'))[1]; } catch (e) {} } return Math.round(r / 1024); }; + await sleep(5000); + const env = await page.evaluate(() => ({ nw: G.LodPool.ws ? G.LodPool.ws.length : 0, mb: Math.round(G.Mem.budget), phone: G.Mem.phone })); + const p0 = pss(); + if (THR > 1) { const c = await page.createCDPSession(); await c.send('Emulation.setCPUThrottlingRate', { rate: THR }); } + const res = await page.evaluate(() => G.Perf.run(['cold'], {})); + const r = res.find(x => x.name === 'cold') || {}; + // each worker's own memory: its JS heap and the buffers outside it (typed arrays), after a collection + const wk = []; for (const w of page.workers()) { try { await w.client.send('HeapProfiler.collectGarbage').catch(() => {}); const h = await w.client.send('Runtime.getHeapUsage'); const mb = Math.round((h.totalSize + (h.backingStorageSize || 0)) / 1048576); if (mb > 3) wk.push(mb); } catch (e) {} } + return { html: path.basename(html), ...env, pss0: p0, pss1: pss(), workerMB: wk, ready: r.ready, work: r.work }; + } finally { await browser.close(); } +} +for (let i = 0; i < REP; i++) for (const h of htmls) console.log(JSON.stringify(await once(h))); diff --git a/tools/wcount.test.mjs b/tools/wcount.test.mjs new file mode 100644 index 000000000..06d0e53bc --- /dev/null +++ b/tools/wcount.test.mjs @@ -0,0 +1,37 @@ +// How many far-tile workers a device gets (LodPool.count, 32_land.js) and the memory class a worker lives in (docs/WORLDGEN.md phase 2). +// A worker costs what it holds: measured in headless Chromium (tools/wcost.bench.mjs) its JS heap and buffers after the cold scenario are +// ~29 MB with the caches of a small device and 25 to 40 MB with full ones, plus its thread. Up to build 481 one was counted as 400 MB, so a +// phone (budget 140 to 480 MB) got none and made every column, far tile and town plan on its main thread (iPhone emulated, CPU ×4: the 3×3 +// around the camera 39.8 s, the whole land not made at all; with one worker 11.0 s and 52.6 s). +// · the table of devices: a phone gets one worker at its first budget, and none once it has died for memory twice; +// · a worker takes its page's budget with the land (Mem.small there too), keeps the small caches, and its tiles and columns are the +// same bytes as a worker with full caches. +// node tools/wcount.test.mjs +import { game } from './gen/load.mjs'; +const { land, fnv } = await import('./gen/lib.mjs'); +const W = await game(); let fails = 0, n = 0; +const ok = (c, m) => { n++; if (!c) { fails++; console.log('FAIL ' + (typeof m === 'function' ? m() : m)); } }; +const C = (hc, mb) => W.LodPool.count(hc, mb); +// [what, cores, budget, workers]: budgets as Mem.init gives them (an iPhone 260, then ×0.65 for each death; Android deviceMemory × 70 in 140..480) +for (const [what, hc, mb, want] of [['iPhone', 6, 260, 1], ['iPhone after a death', 6, 169, 1], ['iPhone after two deaths', 6, 110, 0], ['Android 2 GB', 8, 140, 1], ['Android 4 GB', 8, 280, 2], + ['Android 8 GB', 8, 480, 3], ['laptop 4 cores', 4, 1600, 1], ['laptop 8 cores', 8, 2048, 3], ['desktop 16 cores', 16, 3200, 6], ['desktop, 3 deaths', 16, 3200 * .65 ** 3, 6], ['desktop, 6 deaths', 16, 3200 * .65 ** 6, 1], ['one core', 1, 2048, 1]]) + ok(C(hc, mb) === want, () => `${what} (${hc} cores, budget ${Math.round(mb)} MB): ${C(hc, mb)} workers, want ${want}`); +for (let mb = 100; mb < 4000; mb += 10) ok(C(8, mb) <= C(8, mb + 10), () => `more memory, fewer workers: budget ${mb} → ${C(8, mb)}, ${mb + 10} → ${C(8, mb + 10)}`); +// a worker in its page's memory class +const spec = { seed: 20261202, site: ['town'], biome: 'desert' }, L = land(W, spec).L, m = L.meta, sp = m.spawn; +const msg = mb => ({ t: 'land', id: 1, mb, st: W.StShare.all(L.T), seed: L.seed, opt: L.opt, pal: L.pal.slice(1), sx: L.lot.sx, sz: L.lot.sz, meta: { ox: m.ox, oz: m.oz, nf: m.nf, box: m.box, trees: m.trees, flora: m.flora || null, outs: m.outs || null, spawn: { x: sp.x, y: sp.y - L.ly, z: sp.z, yaw: sp.yaw } } }); +const jobs = []; let j = 0; +for (let k = 0; k <= 4; k++) { const sz = 32 * (2 << k); for (let dz = -1; dz <= 1; dz++) for (let dx = -1; dx <= 1; dx++) jobs.push({ t: 'lod', id: 1, j: ++j, k, tx: Math.floor(sp.x / sz) + dx, tz: Math.floor(sp.z / sz) + dz, f: 0 }); } +for (const [x, z] of [[9, 13], [-14, 6], [30, -20], [3, 40], [60, 60], [-40, 25]]) jobs.push({ t: 'gen', id: 1, j: ++j, cx: x, cz: z, T: 0 }); +const run = async mb => { const K = await game(); K.LodPool.serve(structuredClone(msg(mb))); const h = fnv(); let lru = 0; + for (const q of jobs) { const r = K.LodPool.serve(structuredClone(q)); lru = Math.max(lru, K.Settle.lru.length); + if (r.d) { for (const f of ['nq', 'ns', 'no', 'nt', 'x0', 'z0', 'y0', 'y1']) h(r.d[f] | 0); for (const f of ['buf', 'sbuf', 'gbuf']) if (r.d[f]) { const u = new Uint8Array(r.d[f].buffer || r.d[f]); for (let i = 0; i < u.length; i++) h(u[i]); } } + if (r.ch) for (const c of r.ch) if (typeof c === 'number') h(c); else for (let i = 0; i < c.length; i++) h(c[i]); } + return { K, h: h.hex(), lru, far: K.Settle.farKeep() }; }; +const big = await run(2048), small = await run(200), old = await run(0); +ok(!big.K.Mem.small() && small.K.Mem.small(), () => `the worker's memory class: budget 2048 → small ${big.K.Mem.small()}, budget 200 → small ${small.K.Mem.small()}`); +ok(small.lru <= 8 && small.far === 16 && big.far === 48, () => `caches of a small worker: plans ${small.lru} (want ≤ 8), far records ${small.far} (want 16; a big one ${big.far}, want 48)`); +ok(small.h === big.h, () => `a small worker made other bytes: ${small.h} vs ${big.h}`); +ok(old.h === big.h, () => `a land message without a budget (an older page) made other bytes: ${old.h} vs ${big.h}`); +console.log(fails ? `${fails} of ${n} checks failed` : `OK ${n} checks (tiles ${small.h}, far records kept ${small.far} / ${big.far})`); +process.exit(fails ? 1 : 0); From 571951f6c19d6384dc31a5082c8899f28dcdfa94 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 21:08:33 +0000 Subject: [PATCH 2/3] Towns with an estate plan again: STR, dropped by the version floor, was still read by the estates (every such town threw); undef.test finds any undeclared name in the whole source; farrec.test builds its third world above the floor Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01UiczdsWP38p6ohAsRYayXG --- docs/ARCHITECTURE.md | 6 ++++++ src/game/34_settle.js | 4 ++-- tools/farrec.test.mjs | 2 +- tools/undef.test.mjs | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 tools/undef.test.mjs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 26f74d9d3..38e86ea51 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -709,6 +709,12 @@ Design and migration: `docs/WORLDGEN.md`. - **No loop dies from one system's error.** `frame()` (`src/game/99_main.js`) asks for its next frame in `finally`; `Bg.step` runs its parts (`Bg.parts`: world, own body, animations, network) each in its own `try`, so a throwing world never stops the network step that heals the shared state. Each error goes to `Guard.fail` (below), logged once a second per kind. Test: `tools/netride.test.mjs` parts 2 and 3. +- **Every name the code uses is declared, checked over the whole source and not where it happens to run.** Two PRs that are each + right can land as a game that is wrong: the version floor dropped the constant `STR` (always true since), the estates, written before, + still read it in a new place; git merged them cleanly, the bundle built, and every town with an estate threw while it was planned + (build 481: its far tiles and columns never came). A name that is missing fails only when its line runs, so the test reads the whole + game as the build puts it together and fails on any free name that is not a global of the browser or the language. Test: + `tools/undef.test.mjs` (it found `STR`; the merge queue runs it on the combined state). - **Every key the code reads from a constant table exists.** `LAMP.rev` had slipped into a comment (build 378) and the one branch that reads it threw at night for every reversing car. Test: `tools/config.test.mjs` checks each `NAME.key` read in `src/game` against the table on `window.G` (all-caps, data only), and draws every lamp state of a real car. diff --git a/src/game/34_settle.js b/src/game/34_settle.js index 22f1a7e0c..b3585f4f5 100644 --- a/src/game/34_settle.js +++ b/src/game/34_settle.js @@ -448,10 +448,10 @@ const Settle = { // kampongs, each laid out at once behind its own gate on the land Weave.grow kept for it (WV.est), before any lot of the town; their lanes are streets of the town (lane level, `lw`: the // full width of one, or of an alley without sidewalks) if (VD && typeof Estate !== 'undefined' && Estate.on(L)) { - const lp = al => STR ? cp(Object.assign({}, SP[2], al ? { sw: 0 } : {})) : null; + const lp = al => cp(Object.assign({}, SP[2], al ? { sw: 0 } : {})); Estate.place(P, s, { A, st, wv: VD, resat, sf: SF, lane: (ax, az, bx, bz, al) => road(ax, az, bx, bz, RW[2], al ? 0 : SW ? Math.max(0, SW - 1) : 0, ROAD, lp(al)), // (asphalt, in a village too: the developer paves them) - lw: al => 2 * ((STR ? SP[2].w : RW[2]) + (al || !SW ? 0 : STR ? SP[2].sw : Math.max(0, SW - 1))) + 3, + lw: al => 2 * (SP[2].w + (al || !SW ? 0 : SP[2].sw)) + 3, clear: (x0, z0, x1, z1) => { // the streets on the land of an estate are taken up: their asphalt, lamps, benches, trees and pieces for (let z = z0; z <= z1; z++) for (let x = x0; x <= x1; x++) { const q = z * S + x; m[q] = 0; if (own) own[q] = 0; } const In = (x, z) => x >= x0 - 1 && x <= x1 + 1 && z >= z0 - 1 && z <= z1 + 1; diff --git a/tools/farrec.test.mjs b/tools/farrec.test.mjs index c78a8f552..09a866719 100644 --- a/tools/farrec.test.mjs +++ b/tools/farrec.test.mjs @@ -5,7 +5,7 @@ // node tools/farrec.test.mjs import { game } from './gen/load.mjs'; const { house, land, fnv, hashArr } = await import('./gen/lib.mjs'); -const WORLDS = [[{ seed: 20261202, site: ['town'], biome: 'desert' }, null], [{ seed: 20261129, site: ['town'], relief: ['canyon'] }, [55, 2641]], [{ seed: 20261201, type: 'cottage', site: ['town', 'river'], biome: 'meadow', gh: 2, gl: 2, gw: 9 }, null]]; +const WORLDS = [[{ seed: 20261202, site: ['town'], biome: 'desert' }, null], [{ seed: 20261129, site: ['town'], relief: ['canyon'] }, [55, 2641]], [{ seed: 20261201, type: 'cottage', site: ['town', 'river'], biome: 'meadow' }, null]]; let bad = 0, n = 0; const fail = m => { bad++; console.log('FAIL', m); }, t0 = performance.now(); const mk = async (spec, farOn) => { const W = await game(), L = land(W, spec, house(W, spec)).L; W.Settle.farOn = farOn; return { W, L }; }; const hash = d => { const f = fnv(); for (const b of [d.buf, d.sbuf, d.gbuf]) if (b) hashArr(new Uint8Array(b.buffer || b), f); f(d.nq | 0); f(d.ns | 0); f(d.no | 0); f(d.nt | 0); return f.hex(); }; diff --git a/tools/undef.test.mjs b/tools/undef.test.mjs new file mode 100644 index 000000000..682065947 --- /dev/null +++ b/tools/undef.test.mjs @@ -0,0 +1,35 @@ +// No name of the game is used without being declared (a free identifier that is not a global of the browser or of JavaScript). +// Two PRs that are each right can land as a game that is wrong: one took a constant away (the version floor of build 449 dropped +// `STR`, always true since), the other, written before, still read it in a new place (the estates of gw 72). Git merged them cleanly, the +// bundle built, the page loaded, and every town with an estate threw "STR is not defined" while it was planned: the far tiles and the +// columns over it never came. Such a name only fails when its line runs, so it is looked for in the whole source instead: the game as +// the build puts it together (tools/gen/load.mjs), its scopes worked out by terser, every free name checked against the list below. +// node tools/undef.test.mjs +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { source, ROOT } from './gen/load.mjs'; +const terser = await import(pathToFileURL(path.join(ROOT, 'node_modules/terser/main.js'))); +// what the browser, a worker and the language give +const KNOWN = new Set(`undefined NaN Infinity globalThis window self document navigator location history screen localStorage sessionStorage indexedDB IDBKeyRange crypto performance console + Object Function Array String Number Boolean BigInt Symbol Math JSON Date RegExp Error Promise Proxy Map Set WeakMap Intl WebAssembly + ArrayBuffer DataView Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array + parseInt isNaN isFinite structuredClone atob btoa queueMicrotask setTimeout clearTimeout setInterval clearInterval requestAnimationFrame + addEventListener removeEventListener postMessage fetch prompt confirm matchMedia getComputedStyle devicePixelRatio innerWidth innerHeight + Worker MessageChannel Blob File URL Response AbortController WebSocket TextEncoder TextDecoder CompressionStream DecompressionStream + MutationObserver ResizeObserver IntersectionObserver Audio OfflineAudioContext MediaStream RTCPeerConnection RTCRtpReceiver + XRWebGLLayer GPUTextureUsage GPUBufferUsage GPUMapMode`.split(/\s+/).filter(Boolean)); +export function freeNames(code) { + return terser.minify(code, { parse: {}, compress: false, mangle: false, format: { ast: true, code: false } }).then(r => { if (r.error) throw r.error; r.ast.figure_out_scope({}); return [...r.ast.globals.values()]; }); +} +let src = await source(); const cut = src.lastIndexOf('\n;globalThis.__W = {'); if (cut < 0) throw new Error('the loader no longer ends with the list of exposed names (tools/gen/load.mjs)'); +// (the kernels the build carries and the loader leaves out, read behind typeof: declared here as the build's head declares them) +src = src.slice(0, cut).replace("'use strict';", "'use strict';const FALL_B64='',LIGHT_B64='';") + '\n})();'; +const t0 = Date.now(), lines = src.split('\n'), files = []; lines.forEach((l, i) => { const m = /^\/\/ ---- (\S+) ----$/.exec(l); if (m) files.push([i, m[1]]); }); +const where = line => { let f = null; for (const e of files) { if (e[0] < line) f = e; else break; } return f ? `${f[1]}:${line - f[0] - 1}` : `line ${line}`; }; +const bad = []; +for (const d of await freeNames(src)) if (!KNOWN.has(d.name)) bad.push(`${d.name} (${[...new Set(d.references.map(r => where(r.start.line)))].slice(0, 4).join(', ')})`); +// the check itself: a name nobody declared is found, a declared one and a known global are not +const self = (await freeNames('(()=>{ const a = 1; const f = b => a + b + Math.PI + gone; f(2); })();')).map(d => d.name).join(); +if (self !== 'Math,gone') bad.push(`the check itself: found "${self}" in the sample, want "Math,gone"`); +if (bad.length) { for (const b of bad) console.log('✗ used and never declared: ' + b); console.log(`${bad.length} names of the game are not declared anywhere`); process.exit(1); } +console.log(`OK every name the game uses is declared or a known global (${KNOWN.size} known), ${Date.now() - t0} ms`); From e1f8d9857d80e9fa450f704d84dfb3cbacc03b18 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 21:11:12 +0000 Subject: [PATCH 3/3] Notes of build 482: the estates fix Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01UiczdsWP38p6ohAsRYayXG --- build/notes.mjs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/build/notes.mjs b/build/notes.mjs index 89564a5fb..6e5b6a74b 100644 --- a/build/notes.mjs +++ b/build/notes.mjs @@ -6,10 +6,12 @@ export const NOTES = { 482: { ru: ['📱 Телефоны получили помощника: мир теперь строит отдельный поток и на телефоне. Раньше поток считался как 400 МБ памяти, и телефону не доставалось ни одного; замер показал 30–45 МБ', '⏱️ На iPhone с медленным в 4 раза процессором (эмуляция) земля вокруг после прыжка на 60 км готова за 11 с вместо 40, а вся земля за 53 с (раньше не успевала), памяти занято не больше', - '🧠 Поток живёт в классе памяти своей страницы: на телефоне он держит меньше планов городов, а картинка та же байт в байт. Если страница падала от нехватки памяти, потоков становится меньше'], + '🧠 Поток живёт в классе памяти своей страницы: на телефоне он держит меньше планов городов, а картинка та же байт в байт. Если страница падала от нехватки памяти, потоков становится меньше', + '🏘️ Исправлено: города с жилыми посёлками (сборка 481) не строились, план такого города падал с ошибкой, и земля над ним не появлялась. Новый тест находит любое необъявленное имя во всём коде игры'], en: ['📱 Phones got a helper: the world is now built by a thread of its own on a phone too. A thread used to be counted as 400 MB of memory, so a phone got none; measured, it takes 30–45 MB', '⏱️ On an iPhone with a 4× slower processor (emulated) the land around after a 60 km jump is ready in 11 s instead of 40, and the whole land in 53 s (it did not finish before), with no more memory taken', - '🧠 The thread lives in its page\'s memory class: on a phone it keeps fewer town plans, and the picture is the same byte for byte. A page that ran out of memory gets fewer threads'], + '🧠 The thread lives in its page\'s memory class: on a phone it keeps fewer town plans, and the picture is the same byte for byte. A page that ran out of memory gets fewer threads', + '🏘️ Fixed: towns with estates (build 481) were not built, the plan of such a town threw an error and the land over it never came. A new test finds any undeclared name in the whole code of the game'], }, 481: { ru: ["🏘️ Посёлки с участками, как их строят по брошюрам и нормам: таунхаусы с парковкой у входа и садиком за домом (как в Дубае и Подмосковье), таунхаусы с гаражами на заднем проезде (США, английские мьюз), террасы с палисадниками и общими стоянками (Англия, Нидерланды, Германия), американский пригород с газонами и гаражами, коттеджный посёлок за глухим забором с охраной",