Upstream/public/js/screens/map.js
jvanvik 931f59e11e Phase 3: trade/end-game client, bot simulator, first balance pass
Built:
- Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE.
- tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number.
- Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs).
- Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow.

Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots.

NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 20:24:41 +02:00

262 lines
15 KiB
JavaScript

'use strict';
/*
* Map screen: owns the canvas (render.js draws it), fetches GET /map by viewport into a chunk cache, and shows the
* tile info sheet. One /map request returns at most a 81 x 81 window (r <= 40), so the world is cut into 40 x 40
* chunks and only the chunks the viewport touches are fetched, again when the camera stops moving. Land tiles are
* implied by the API (only rural areas, incumbent sites and POPs are listed).
*/
(function () {
const { h, icon, openSheet, closeSheet, toast } = UI;
const R = UpstreamRules;
const F = UpstreamData.FORMULAS;
const CHUNK = 40, STALE_MS = 60000, RETRY_MS = 6000, MAX_PARALLEL = 2;
// ------------------------------------------------------------------ chunk store
class Store {
constructor() { this.chunks = new Map(); this.active = 0; this.errShown = 0; this.onChange = null; }
reset() { this.chunks.clear(); }
key(i, j) { return i + ',' + j; }
// Make sure every chunk touching the rect is loaded and fresh.
ensure(v, radius) {
const i0 = Math.floor(v.x0 / CHUNK), i1 = Math.floor(v.x1 / CHUNK), j0 = Math.floor(v.y0 / CHUNK), j1 = Math.floor(v.y1 / CHUNK);
const want = [];
for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
if (i * CHUNK > radius || (i + 1) * CHUNK - 1 < -radius || j * CHUNK > radius || (j + 1) * CHUNK - 1 < -radius) continue;
const c = this.chunks.get(this.key(i, j));
const now = Date.now();
if (!c || (c.state === 'ok' && now - c.at > STALE_MS) || (c.state === 'error' && now - c.at > RETRY_MS)) want.push([i, j]);
}
// nearest to the view centre first
want.sort((a, b) => Math.hypot((a[0] + 0.5) * CHUNK - v.cx, (a[1] + 0.5) * CHUNK - v.cy) - Math.hypot((b[0] + 0.5) * CHUNK - v.cx, (b[1] + 0.5) * CHUNK - v.cy));
for (const [i, j] of want) this.fetch(i, j);
}
async fetch(i, j) {
const k = this.key(i, j);
const prev = this.chunks.get(k);
if (prev && prev.state === 'loading') return;
if (this.active >= MAX_PARALLEL) { setTimeout(() => this.fetch(i, j), 120); return; }
const rec = prev || { specials: [], towns: [], map: new Map(), at: 0 };
rec.state = 'loading';
this.chunks.set(k, rec);
this.active++;
const x0 = i * CHUNK, y0 = j * CHUNK;
try {
const r = await App.api.get('/map', { x: x0 + CHUNK / 2, y: y0 + CHUNK / 2, r: CHUNK / 2 });
const inChunk = (o) => o.x >= x0 && o.x < x0 + CHUNK && o.y >= y0 && o.y < y0 + CHUNK;
rec.specials = r.specials.filter(inChunk);
rec.map = new Map(rec.specials.map((s) => [s.x * 4096 + s.y, s]));
rec.towns = r.towns.filter(inChunk);
rec.state = 'ok'; rec.at = Date.now();
} catch (e) {
rec.state = prev && prev.at ? 'ok' : 'error'; rec.at = Date.now(); // keep showing old data when a refresh fails
if (Date.now() - this.errShown > 8000) { this.errShown = Date.now(); toast(App.t('map.error'), 'error'); }
} finally {
this.active--;
if (this.onChange) this.onChange();
}
}
chunkAt(x, y) { return this.chunks.get(this.key(Math.floor(x / CHUNK), Math.floor(y / CHUNK))); }
special(x, y) { const c = this.chunkAt(x, y); return c ? c.map.get(x * 4096 + y) : undefined; }
townAt(x, y) { const c = this.chunkAt(x, y); return c ? c.towns.find((t) => t.x === x && t.y === y) : undefined; }
loaded(x, y) { const c = this.chunkAt(x, y); return !!c && c.state === 'ok'; }
forEachSpecial(x0, y0, x1, y1, fn) {
for (const c of this.chunks.values()) for (const s of c.specials) if (s.x >= x0 && s.x <= x1 && s.y >= y0 && s.y <= y1) fn(s);
}
townsInRect(x0, y0, x1, y1) {
const out = [];
for (const c of this.chunks.values()) for (const t of c.towns) if (t.x >= x0 && t.x <= x1 && t.y >= y0 && t.y <= y1) out.push(t);
return out;
}
// After a rename the capital on the map must not show a stale name.
patchTown(id, patch) { for (const c of this.chunks.values()) for (const t of c.towns) if (t.id === id) Object.assign(t, patch); }
}
// ------------------------------------------------------------------ screen
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own', offMoveTick = null;
const store = new Store();
let infoSheet = null;
const ownOperatorId = () => (App.state.operator ? App.state.operator.id : null);
const capital = () => App.state.towns.find((t) => t.isCapital) || App.state.towns[0] || null;
function updateCoords() {
if (!coordsEl || !view) return;
coordsEl.textContent = 'x ' + Math.round(view.cx) + ' · y ' + Math.round(view.cy);
}
function centreOnOwn() {
const c = App.state.towns.find((t) => t.id === App.state.townId) || capital();
if (!c) return;
view.setView(c.x, c.y, 30);
}
function setup() {
if (ready) return;
ready = true;
canvas = h('canvas', { class: 'map-canvas', tabindex: '0', role: 'application', 'aria-label': App.t('map.label') });
coordsEl = h('div', { class: 'map-coords mono', 'aria-hidden': 'true' });
legendEl = h('ul', { class: 'map-legend', 'aria-hidden': 'true' });
const zoomBtn = (name, label, f) => h('button', { class: 'map-btn', type: 'button', 'aria-label': label, onclick: f }, icon(name));
const controls = h('div', { class: 'map-controls' },
zoomBtn('plus', App.t('map.zoomIn'), () => view.zoomAt(view.w / 2, view.h / 2, 1.5)),
zoomBtn('minus', App.t('map.zoomOut'), () => view.zoomAt(view.w / 2, view.h / 2, 1 / 1.5)),
zoomBtn('locate', App.t('map.centre'), centreOnOwn));
controls.dataset.role = 'controls';
box.appendChild(canvas); box.appendChild(legendEl); box.appendChild(coordsEl); box.appendChild(controls);
const source = {
forEachSpecial: (a, b, c, d, fn) => store.forEachSpecial(a, b, c, d, fn),
townsInRect: (a, b, c, d) => store.townsInRect(a, b, c, d),
isOwn: (t) => t.owner.id === ownOperatorId(),
movements: () => moveLines(),
threatened: (t) => App.mil.moves.incoming.some((m) => m.to && m.to.townId === t.id),
myAllianceId: () => (App.state.operator ? App.state.operator.allianceId : null),
};
view = new MapRender.MapView(canvas, source, {
onTap: onTap,
onMoveEnd: (v) => { updateCoords(); store.ensure(v, App.state.world ? App.state.world.mapRadius : 50); },
});
view.labelFn = (t, own) => (own ? t.name : t.owner.name);
view.reachTiles = F.ruralReach;
store.onChange = () => view.invalidate();
new ResizeObserver(() => { if (visible && view.resize()) updateCoords(); }).observe(box);
// The camera moves are frequent; keep the coords chip in step cheaply.
canvas.addEventListener('pointermove', () => updateCoords());
canvas.addEventListener('wheel', () => updateCoords(), { passive: true });
drawLegend();
}
// Lines for the movements of the shared cache (App.mil.moves): yours, incoming and allied ones, with progress at draw time.
function moveLines() {
const mv = App.mil && App.mil.moves;
if (!mv) return [];
const now = App.now(), out = [];
const add = (m, kind) => {
if (!m.from || !m.to || m.from.x === undefined || m.to.x === undefined) return;
out.push({ from: m.from, to: m.to, kind, p: (now - m.departAt) / Math.max(1, m.arriveAt - m.departAt) });
};
for (const m of mv.outgoing) add(m, m.type === 'return' ? 'ret' : 'out');
for (const m of mv.incoming) add(m, 'in');
for (const m of mv.alliedIncoming || []) add(m, 'ally');
return out;
}
function drawLegend() {
UI.clear(legendEl);
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
legendEl.appendChild(item('you', App.t('map.legend.you')));
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
legendEl.appendChild(item('backbone', App.t('map.legend.backbone')));
legendEl.appendChild(item('mv-out', App.t('map.legend.out')));
legendEl.appendChild(item('mv-in', App.t('map.legend.in')));
}
// ------------------------------------------------------------------ tile info
function onTap(x, y) {
const w = App.state.world;
if (!w) return;
if (Math.abs(x) > w.mapRadius || Math.abs(y) > w.mapRadius) return;
showTile(x, y);
}
function showTile(x, y) {
view.setSelected(x, y);
const town = store.townAt(x, y);
const special = store.special(x, y);
const known = store.loaded(x, y);
const type = town ? 'pop' : special ? special.type : 'land';
const cap = capital();
const body = [];
const row = (label, value) => h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value }));
if (town) {
const own = town.owner.id === ownOperatorId();
body.push(h('div', { class: 'pill-row' },
own ? h('span', { class: 'pill accent', text: App.t('map.info.yours') }) : h('span', { class: 'pill', text: App.t('map.info.rival') }),
town.isCapital ? h('span', { class: 'pill', text: App.t('map.info.capital') }) : null,
town.owner.protected ? h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')) : null));
body.push(row(App.t('map.info.operator'), town.owner.name));
body.push(row(App.t('map.info.as'), UpstreamI18n.fmtAs(town.owner.asNumber)));
} else if (special && special.type === 'rural') {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.rural', { n: F.ruralReach, p: Math.round(F.ruralBonus * 100), res: App.resName(special.bonus) }) }));
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
} else if (special && special.type === 'incumbent') {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
} else if (special && special.type === 'backbone') {
const site = special.site || {};
const mine = !!(site.holder && site.holder.allianceId && site.holder.allianceId === (App.state.operator && App.state.operator.allianceId));
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.backbone', { max: site.maxLevel || UpstreamData.ENDGAME.maxLevel }) }));
body.push(h('div', { class: 'pill-row' },
site.holder ? h('span', { class: 'pill' + (mine ? ' accent' : '') }, '[' + site.holder.tag + '] ' + site.holder.name) : h('span', { class: 'pill dim', text: App.t('wld.incumbent') }),
h('span', { class: 'pill', text: App.t('wld.level', { n: site.level || 0, max: site.maxLevel || UpstreamData.ENDGAME.maxLevel }) })));
body.push(h('div', { class: 'bar wld-bar ' + (mine ? 'mine' : site.holder ? 'rival' : 'incumbent'), 'aria-hidden': 'true' }, (() => { const i = h('i'); i.style.setProperty('--p', String(site.maxLevel ? (site.level || 0) / site.maxLevel : 0)); return i; })()));
body.push(h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { closeSheet(); App.go('world', { site: site.index }); } }, icon('b-backbone_node'), App.t('map.info.openWorld')));
} else if (!known) {
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
} else {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
}
body.push(row('', App.t('map.info.coords', { x, y })));
if (App.openSend && App.state.towns.length && (town || (special && (special.type === 'incumbent' || (special.type === 'backbone' && !(special.site && special.site.holder && special.site.holder.allianceId === (App.state.operator && App.state.operator.allianceId))))) || (!special && known))) {
body.push(h('button', { class: 'btn wide' + (town && town.owner.id === ownOperatorId() ? '' : ' primary'), type: 'button', onclick: () => App.openSend({ x, y }) }, icon('target'), App.t('send.open')));
}
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
body.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
}
const title = town ? town.name : (type === 'backbone' && special.site && Number.isInteger(special.site.index) ? App.t('wld.site', { n: special.site.index + 1 }) : App.t('tile.' + type));
infoSheet = openSheet({
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : type === 'backbone' ? 'b-backbone_node' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
});
}
// ------------------------------------------------------------------ screen registration
App.registerScreen({
id: 'map', titleKey: 'screen.map', navKey: 'nav.map', icon: 'map', hud: true,
render(container) {
box = container;
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
App.on('movements', () => { if (visible && view) view.invalidate(); });
App.on('towns', () => { if (view) view.invalidate(); });
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
},
onShow(params) {
visible = true;
// marker positions move with the clock: redraw about once a second while any movement is on the wire
if (offMoveTick) offMoveTick();
let lastSec = 0;
offMoveTick = App.onTick((now) => {
const sec = Math.floor(now / 1000), mv = App.mil.moves;
if (sec !== lastSec && view && (mv.outgoing.length || mv.incoming.length || (mv.alliedIncoming || []).length)) { lastSec = sec; view.invalidate(); }
});
if (!App.state.world) { UI.clear(box); box.appendChild(h('p', { class: 'empty pad', text: App.t('map.noWorld') })); ready = false; return; }
setup();
view.setWorld(App.state.world.mapRadius);
const apply = () => {
if (params && Number.isFinite(params.x)) view.setView(params.x, params.y, params.zoom || 40);
else if (pendingFocus) { centreOnOwn(); pendingFocus = null; }
else view.setView(view.cx, view.cy);
updateCoords();
};
// the container was display:none until now: measure after layout
requestAnimationFrame(() => { if (view.resize()) apply(); else setTimeout(() => { view.resize(); apply(); }, 60); });
},
onHide() { visible = false; if (offMoveTick) offMoveTick(); offMoveTick = null; closeSheet(); },
onLang() {
if (!ready) return;
canvas.setAttribute('aria-label', App.t('map.label'));
drawLegend();
const labels = ['map.zoomIn', 'map.zoomOut', 'map.centre'];
box.querySelectorAll('.map-controls .map-btn').forEach((b, i) => b.setAttribute('aria-label', App.t(labels[i])));
},
});
}());