feedback7: merge fb7-hud — HP-bar readouts (#303 / #378 / #383: ammo cells, 伺夜's wolf-shadow pips, 斩业星熊's 我执 bar), #302 renderer abort, #292 held skill cue, #334 atlas slots, #354 梓兰's per-card frost

- Grok review: MERGE (no defect). Golden unchanged (union OK); broad node --test 5327 (5326 pass, 0 fail, 1 skipped); lint 0 errors.
This commit is contained in:
sganggs committed 2026-10-08 20:29:27 +08:00
commit 7d6fefe8f5
33 files changed
+1751 -77

No files matched your search

+349
View File
@@ -0,0 +1,349 @@
// test/render/hud-readouts.test.js — the HP-bar readouts, client side (R22-HUD; PR #303 and #378 by @IceCodeNew, PR #383
// by @Convey123, folded into one change): render/interp.js carries b.snap `ammo` [[id, left, magazine]], `wolves`
// [[id, left, max]] and `neg` [[id, fill]] beside the unit tuples and samples them from the older snapshot; render/units.js
// draws the ammo skill's segmented yellow bar in place of the SP bar, 伺夜's 狼影 as a row of diamonds and the 我执 pool
// as the red bar over the drained HP bar; an ammo skill has no standing aura (headless fake PIXI, test/render/fakepixi.js).
// The server side is test/sim/hud-readouts.test.js and test/content/op_hsgma2.test.js.
// Run: node --test test/render/hud-readouts.test.js
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { installFakePixi, fakeViewCtx } from './fakepixi.js';
import { presetCamera } from '../../public/js/render/projection.js';
import { SnapshotBuffer, normalizeSnapshot } from '../../public/js/render/interp.js';
import { renderInfo } from '../../public/js/render/app/info.js';
import { UF } from '../../shared/constants.js';
import { makeBattle, enemyRec } from '../helpers/battleHarness.js';
import { unitInfo } from '../../server/sim/snapshot.js';
let fake, FX, UnitView, COLORS, AMMO_BAR, WOLF_PIPS;
before(async () => {
fake = installFakePixi();
FX = await import('../../public/js/render/fx.js');
({ UnitView, AMMO_BAR, WOLF_PIPS } = await import('../../public/js/render/units.js'));
({ COLORS } = await import('../../public/js/render/style.js'));
});
after(() => { FX?.setSimProjectileSpeeds(null); fake.restore(); });
const cam = () => presetCamera('normal', { width: 1280, height: 720 });
const tuple = (id, hp = 1000, extra = {}) => [id, 5, 10, hp, 1000, extra.sp ?? 0, extra.spMax ?? 0, extra.flags ?? 0, 0];
const view = (info = {}, extra = {}) => new UnitView(fakeViewCtx(fake.P, { cam, ...extra }),
{ id: 1, side: 'ally', kind: 'op', defId: 'char_x', tier: 3, x: 5, y: 10, maxHp: 1000, dir: 'RIGHT', ...info });
const sample = (o = {}) => ({ x: 5, y: 10, hp: 1000, maxHp: 1000, sp: 0, spMax: 0, flags: 0, anim: 0, vx: 0, vy: 0, ...o });
const frames = (v, n = 2) => { for (let i = 0; i < n; i++) v.update(1 / 60, cam(), i / 60); };
const barWidth = (v) => v.hpBg.width - 2;
describe('interp: ammo / wolves / neg', () => {
test('sampled from the older snapshot (they step at snapshot boundaries) and cleared by a snapshot without them', () => {
const buf = new SnapshotBuffer({ delay: 0 });
buf.push({ t: 1, units: [tuple(1), tuple(2)], ammo: [[1, 13, 14]], wolves: [[2, 2, 3]], neg: [[2, 0.25]] }, 0);
buf.push({ t: 2, units: [tuple(1), tuple(2)], ammo: [[1, 12, 14]], wolves: [[2, 1, 3]], neg: [[2, 0.5]] }, 0.5);
buf.push({ t: 3, units: [tuple(1), tuple(2)] }, 1);
// between the first two snapshots nothing slides: a round, a 狼影 or a share of the pool is not halfway
const out = buf.sample(1.99);
assert.deepEqual([out.get(1).ammo, out.get(1).wolves, out.get(1).neg], [[13, 14], null, 0]);
assert.deepEqual([out.get(2).ammo, out.get(2).wolves, out.get(2).neg], [null, [2, 3], 0.25]);
buf.sample(2, out);
assert.deepEqual([out.get(1).ammo, out.get(2).wolves, out.get(2).neg], [[12, 14], [1, 3], 0.5]);
// a snapshot without the lists takes the readouts off the reused sample objects
buf.sample(3, out);
assert.deepEqual([out.get(1).ammo, out.get(2).wolves, out.get(2).neg], [null, null, 0]);
});
test('malformed rows are dropped: fractions, negatives, a count above its maximum, a maximum under 1, unknown ids, junk', () => {
const s = normalizeSnapshot({
t: 1, units: [tuple(1), tuple(2), tuple(3)],
ammo: [[1, 13, 14], [2, -1, 14], [2, 2, 1], [2, 1.5, 4], [9, 1, 2], [3, 15, 14], null, 'x', [3, 0, 0]],
wolves: [[2, 3, 3], [1, 2.5, 3], [1, 4, 3], [3, 1, 0], [9, 1, 3]],
neg: [[1, 0.4], [2, 0], [3, -1], [3, 'x'], [9, 0.5], [2, 5], null],
});
assert.deepEqual([...s.ammo], [[1, [13, 14]]]);
assert.deepEqual([...s.wolves], [[2, [3, 3]]]);
assert.deepEqual([...s.neg], [[1, 0.4], [2, 1]], 'a share above 1 is a full pool; 0 / negative / non-numbers are no pool');
const none = normalizeSnapshot({ t: 1, units: [tuple(1)] });
assert.deepEqual([none.ammo, none.wolves, none.neg], [null, null, null]);
assert.equal(none.units.get(1).length, 9, 'the tuples are never widened by the readouts');
});
});
describe('UnitView: the ammo skill\'s segmented bar', () => {
test('replaces the SP bar while the magazine runs: a yellow cell per round, the fill is rounds left / magazine, a thin cut at every boundary', () => {
const v = view();
v.sync(sample({ flags: UF.SKILL, sp: 22.3, spMax: 24, ammo: [13, 14] }));
frames(v);
const bw = barWidth(v);
assert.equal(v.spBg.visible && v.spFill.visible, true);
assert.equal(v.spFill.tint, COLORS.ammo);
assert.ok(Math.abs(v.spFill.width - bw * 13 / 14) < 1e-9, 'rounds left over the magazine, exactly (not the 0.1-rounded SP)');
const cuts = v.ammoCuts.filter((c) => c.visible);
assert.equal(cuts.length, 13, 'one cut per boundary of 14 cells');
const step = bw / 14, x0 = v.spFill.position.x;
cuts.forEach((c, i) => {
assert.ok(Math.abs(c.position.x - (x0 + (i + 1) * step - 0.5)) < 1e-9, `cut ${i + 1} on the boundary`);
assert.equal(c.width, 1);
assert.equal(c.height, v.spFill.height);
assert.equal(c.position.y, v.spFill.position.y);
assert.equal(c.tint, COLORS.hpBack);
});
assert.ok(v.spFill.height > v.hpFill.height * 0.6, 'taller than the plain SP bar (the HP bar\'s thickness × AMMO_BAR.height)');
assert.ok(Math.abs(v.spFill.height - Math.max(2, v.hpFill.height * AMMO_BAR.height)) < 1e-9);
// a round is spent: the fill loses 1/14 and the cuts stay
v.sync(sample({ flags: UF.SKILL, sp: 20.6, spMax: 24, ammo: [12, 14] }));
frames(v);
assert.ok(Math.abs(v.spFill.width - bw * 12 / 14) < 1e-9);
assert.equal(v.ammoCuts.filter((c) => c.visible).length, 13);
// the last round, then the magazine ends: the plain SP bar is back (cyan, no cuts)
v.sync(sample({ flags: UF.SKILL, ammo: [0, 14], sp: 0, spMax: 24 }));
frames(v);
assert.equal(v.spFill.width, 0);
v.sync(sample({ flags: 0, sp: 6, spMax: 24, ammo: null }));
frames(v);
assert.equal(v.ammoCuts.filter((c) => c.visible).length, 0, 'no cuts without a magazine');
assert.notEqual(v.spFill.tint, COLORS.ammo);
assert.ok(Math.abs(v.spFill.width - bw * 6 / 24) < 1e-9, 'the SP fraction of the tuple');
v.destroy();
});
test('a magazine needs no SP cost to show; a dense one keeps its exact fill and draws no cuts under AMMO_BAR.minCell px; an enemy never has the bar', () => {
const v = view();
v.sync(sample({ flags: UF.SKILL, ammo: [20, 40] })); // spMax 0: an auto skill with no SP cost
frames(v);
const bw = barWidth(v);
assert.equal(v.spFill.visible, true, 'the bar shows without an SP cost');
assert.ok(Math.abs(v.spFill.width - bw / 2) < 1e-9);
const cell = bw / 40;
assert.equal(v.ammoCuts.filter((c) => c.visible).length, cell >= AMMO_BAR.minCell ? 39 : 0, `${cell.toFixed(2)} px cells`);
v.sync(sample({ flags: UF.SKILL, ammo: [20, 400] }));
frames(v);
assert.equal(v.ammoCuts.filter((c) => c.visible).length, 0, 'under 2 px a cell: no cuts');
assert.ok(Math.abs(v.spFill.width - bw * 20 / 400) < 1e-9, 'the fill is still exact');
v.destroy();
const e = view({ id: 2, side: 'enemy', kind: 'enemy', defId: 'enemy_x' });
e.sync(sample({ hp: 500, flags: UF.SKILL, ammo: [3, 4] }));
frames(e);
assert.equal(e.spFill.visible, false, 'enemies have no SP bar, and so no magazine');
assert.equal(e.ammoCuts.filter((c) => c.visible).length, 0);
e.destroy();
});
test('the prep view draws no bars, so no cells either', () => {
const v = view({}, {});
v.prep = true;
v.sync(sample({ flags: UF.SKILL, ammo: [5, 14] }));
frames(v);
assert.equal(v.spFill.visible, false);
assert.equal(v.ammoCuts.filter((c) => c.visible).length, 0);
v.destroy();
});
});
describe('UnitView: 伺夜\'s 狼影 pips', () => {
const pack = (extra = {}) => view({ kind: 'token', defId: 'token_10028_vigil_wolf', ...extra });
test('one diamond per 狼影 the talent allows under the HP bar, the first ones lit for the shadows left', () => {
const v = pack();
v.sync(sample({ wolves: [2, 3] }));
frames(v);
const r = v._wolfPips;
assert.equal(r.root.visible, true);
assert.equal(r.lit.length, 3);
assert.deepEqual(r.lit.map((d) => d.alpha), [1, 1, WOLF_PIPS.dim]);
assert.ok(r.lit.every((d) => d.visible && d.tint === COLORS.wolf && Math.abs(d.rotation - Math.PI / 4) < 1e-9), 'pale diamonds');
assert.ok(r.back.every((d) => d.visible && d.tint === COLORS.hpBack), 'on a dark backing');
assert.ok(r.lit[0].position.y > v.hpBg.position.y, 'below the HP bar');
assert.ok(r.lit[0].position.x > v.hpFill.position.x && r.lit[2].position.x < v.hpFill.position.x + barWidth(v), 'inside the bar\'s span');
assert.ok(r.lit[1].position.x > r.lit[0].position.x && r.lit[2].position.x > r.lit[1].position.x, 'left to right');
assert.equal(v.spFill.visible, false, 'not an SP bar or a skill indicator');
// a 狼影 is spent: the last lit one dims; one is gained: it lights again
v.sync(sample({ wolves: [1, 3] }));
frames(v);
assert.deepEqual(r.lit.map((d) => d.alpha), [1, WOLF_PIPS.dim, WOLF_PIPS.dim]);
v.sync(sample({ wolves: [3, 3] }));
frames(v);
assert.deepEqual(r.lit.map((d) => d.alpha), [1, 1, 1]);
// a smaller maximum hides the surplus diamonds
v.sync(sample({ wolves: [1, 2] }));
frames(v);
assert.equal(r.lit.filter((d) => d.visible).length, 2);
v.destroy();
});
test('hidden without a count (an older snapshot cannot leave stale pips), in the prep view, and for enemies', () => {
const v = pack();
v.sync(sample({ wolves: [2, 3] }));
frames(v);
assert.equal(v._wolfPips.root.visible, true);
v.sync(sample({}));
frames(v);
assert.equal(v._wolfPips.root.visible, false, 'no row in the snapshot: no pips');
v.sync(sample({ wolves: [2, 3] }));
v.prep = true;
frames(v);
assert.equal(v._wolfPips.root.visible, false, 'the prep board draws no bars');
v.destroy();
const e = view({ id: 2, side: 'enemy', kind: 'enemy', defId: 'enemy_x' });
e.sync(sample({ hp: 500, wolves: [2, 3] }));
frames(e);
assert.equal(e._wolfPips, null, 'only allies carry the row');
e.destroy();
});
test('the element gauge row moves down below the pips (and below the SP bar when there is one)', () => {
const plain = view();
plain.sync(sample({ el: 'burn', elFill: 0.4, elUntil: 0, elDur: 0 }));
frames(plain);
const v = pack();
v.sync(sample({ wolves: [2, 3], el: 'burn', elFill: 0.4, elUntil: 0, elDur: 0 }));
frames(v);
const pipsBottom = v._wolfPips.back[0].position.y + (v._wolfPips.back[0].width * Math.SQRT2) / 2;
assert.ok(v._elBar.bg.position.y - v._elBar.bg.height / 2 >= pipsBottom - 1e-6, 'the gauge row starts under the pips');
assert.ok(v._elBar.bg.position.y > plain._elBar.bg.position.y + 4, 'and so sits lower than without pips');
plain.destroy();
v.destroy();
});
});
describe('UnitView: the 我执 pool as the red bar', () => {
const ego = (extra = {}) => view({ defId: 'char_1044_hsgma2', tier: 6, ...extra });
test('drawn over the drained HP bar from its left edge: width = the bar × the pool\'s share, the pool\'s red, gone with the pool', () => {
const v = ego();
v.sync(sample({ hp: 1 }));
frames(v);
assert.equal(v.negFill.visible, false, 'no pool, no red bar');
assert.equal(v.negFill.tint, COLORS.hpNeg);
v.sync(sample({ hp: 1, neg: 0.5 }));
frames(v);
assert.equal(v.negFill.visible, true);
assert.ok(Math.abs(v.negFill.width - barWidth(v) * 0.5) < 1e-9, 'half the pool: half the bar');
assert.equal(v.negFill.position.x, v.hpFill.position.x, 'from the bar\'s left edge');
assert.equal(v.negFill.position.y, v.hpFill.position.y);
assert.equal(v.negFill.height, v.hpFill.height);
assert.ok(v.hpFill.width < 1, 'the green bar is drained meanwhile');
v.sync(sample({ hp: 1, neg: 1 }));
frames(v);
assert.ok(Math.abs(v.negFill.width - barWidth(v)) < 1e-9, 'a full pool fills the bar');
v.sync(sample({ hp: 600, neg: 0 }));
frames(v);
assert.equal(v.negFill.visible, false, 'she left 我执');
v.destroy();
});
test('not in the prep view, and gone once she falls', () => {
const p = ego();
p.prep = true;
p.sync(sample({ hp: 1, neg: 0.6 }));
frames(p);
assert.equal(p.negFill.visible, false);
p.destroy();
const v = ego();
v.sync(sample({ hp: 1, neg: 1 }));
frames(v);
assert.equal(v.negFill.visible, true);
v.die();
for (let i = 0; i < 300; i++) v.update(1 / 60, cam(), i / 60);
assert.equal(v.alive, false);
assert.equal(v.negFill.visible, false, 'no bars for a knocked-out operator');
v.destroy();
});
});
describe('an ammo skill has no standing aura', () => {
const unit = (id, info) => ({ id, x: 3, y: 10, z: 0, hover: 0, _headTiles: 1.2, alive: true, destroyed: false, isEnemy: false, maxHp: 3000, info, onHit() {} });
const makeFx = (views) => {
const ctx = fakeViewCtx(fake.P);
const map = new Map(views.map((v) => [v.id, v]));
const c = presetCamera('normal', { width: 1600, height: 900 });
return new FX.FxSystem({
P: fake.P, layers: ctx.layers, cam: () => c, heightAt: () => 0, settings: { quality: 'high', damageNumbers: true },
timeScale: () => 2, loadLevel: () => 0, subProfOf: () => null, view: (id) => map.get(id) || null,
screenSize: () => ({ width: 1600, height: 900 }), fieldTop: () => 120,
});
};
test('UnitInfo.ammoSkill: the activation burst plays, the ground glow and hex do not (a plain skill keeps both)', () => {
const magazine = unit(1, { defId: 'char_x', ammoSkill: true }), plain = unit(2, { defId: 'char_y' });
const fx = makeFx([magazine, plain]);
fx.skill(magazine, true);
assert.ok(fx.parts.length > 0 && fx.rings.length > 0, 'the cast itself is still shown');
assert.equal(fx.auras.size, 0, 'no glow and hex under a magazine');
fx.skill(magazine, false);
fx.skill(plain, true);
assert.equal(fx.auras.size, 1, 'a plain skill keeps its aura');
fx.destroy();
});
test('the flag travels: unitInfo (ammo skills of allies only) → renderInfo', () => {
const h = makeBattle({
defs: { enemies: { enemy_dummy: enemyRec({ key: 'enemy_dummy', hp: 1e7, speed: 0 }) } }, timeLimit: 30, seed: 7,
units: [{ chessId: 'chess_char_1_01_a', row: 10, col: 3 }, { chessId: 'chess_char_1_02_a', row: 11, col: 3 }],
enemies: [{ key: 'enemy_dummy', pos: [10, 5] }],
});
h.run(0.5);
assert.equal(renderInfo(unitInfo(h.unit('chess_char_1_01_a'))).ammoSkill, true);
assert.equal(renderInfo(unitInfo(h.unit('chess_char_1_02_a'))).ammoSkill, undefined);
assert.equal(renderInfo(unitInfo(h.enemy('enemy_dummy'))).ammoSkill, undefined);
assert.equal(renderInfo({ id: 1, ammoSkill: 'yes' }).ammoSkill, undefined, 'only a real true counts');
});
});
describe('the chain: sim → snapshot → SnapshotBuffer → UnitView', () => {
test('隐现 S2: 14 cells, 13 after the first round, one more gone per attack; no aura; the plain SP bar after the last round', () => {
const h = makeBattle({
defs: { enemies: { enemy_dummy: enemyRec({ key: 'enemy_dummy', hp: 1e7, speed: 0 }) } },
units: [{ chessId: 'chess_char_1_01_a', row: 10, col: 3 }],
enemies: [{ key: 'enemy_dummy', pos: [10, 5] }],
timeLimit: 200, seed: 7,
});
const u = h.unit('chess_char_1_01_a');
assert.ok(h.runUntil(() => u.skill.active, 80));
const v = new UnitView(fakeViewCtx(fake.P, { cam }), renderInfo(unitInfo(u)));
const buffer = new SnapshotBuffer({ delay: 0 });
const show = () => {
const snap = h.b.snapshot();
buffer.push(snap, snap.t);
v.sync(buffer.sample(snap.t).get(u.id), snap.t);
v.update(1 / 60, cam(), h.b.time);
};
show();
const bw = barWidth(v);
assert.equal(u.skill.ammoLeft, 13, 'the activation tick already fired the first round');
assert.ok(Math.abs(v.spFill.width - bw * 13 / 14) < 1e-9);
assert.equal(v.ammoCuts.filter((c) => c.visible).length, 13);
const left = u.skill.ammoLeft;
assert.ok(h.runUntil(() => u.skill.ammoLeft < left && u.skill.active, 10));
show();
assert.ok(Math.abs(v.spFill.width - bw * 12 / 14) < 1e-9, 'one attack removes exactly one round');
assert.ok(h.runUntil(() => !u.skill.active, 60));
show();
show();
assert.equal(v.ammoCuts.filter((c) => c.visible).length, 0, 'the magazine is spent: the plain SP bar is back');
assert.notEqual(v.spFill.tint, COLORS.ammo);
v.destroy();
});
test('伺夜\'s placed pack: the pips follow 2 → 3 → 2 and are gone when the pack falls', () => {
const h = makeBattle({
units: [{ chessId: 'chess_char_3_19_a', row: 12, col: 3, uid: 1 }, { kind: 'token', tokenId: 'token_10028_vigil_wolf', ownerUid: 1, row: 11, col: 5, uid: 2 }],
timeLimit: 120, defs: { enemies: { enemy_d: enemyRec({ key: 'enemy_d', hp: 1e9, speed: 0, atk: 0 }) } }, enemies: [{ key: 'enemy_d', pos: [1, 1] }],
});
h.run(0.2);
const w = h.b.allyUnits.find((x) => x.defId === 'token_10028_vigil_wolf');
const v = new UnitView(fakeViewCtx(fake.P, { cam }), renderInfo(unitInfo(w)));
const buffer = new SnapshotBuffer({ delay: 0 });
const lit = () => {
const snap = h.b.snapshot();
buffer.push(snap, snap.t);
v.sync(buffer.sample(snap.t).get(w.id), snap.t);
v.update(1 / 60, cam(), h.b.time);
return v._wolfPips ? v._wolfPips.lit.filter((d) => d.visible && d.alpha === 1).length : 0;
};
assert.equal(lit(), 2);
h.run(25);
assert.equal(lit(), 3);
h.b.dealDamage(null, w, { amount: 1e9, type: 'true' });
h.step(); // (a snapshot of the same game time as the last one would be dropped as a duplicate)
assert.equal(lit(), 2);
v.destroy();
});
});
+343
View File
@@ -0,0 +1,343 @@
// Real renderer startup and cancellation, without downloaded art.
// RENDER_E2E=1 node --test test/render/initialization.browser.test.js
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const OUT = path.join(ROOT, 'test/e2e/out');
const CHROME = process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const skip = process.env.RENDER_E2E === '1' && existsSync(CHROME) ? false : 'set RENDER_E2E=1 (needs Chrome)';
const HTML = `<!doctype html><html><head><link rel="stylesheet" href="/css/theme.css"><link rel="stylesheet" href="/css/screens/game.css"></head>
<body style="margin:0"><div id="host" style="position:relative;width:1000px;height:650px"></div><div id="hooks"></div></body></html>`;
// These wrappers keep the real browser/Pixi behavior and record resources owned by each view.
function trackBrowserResources() {
const state = window.__initialization = { apps: [], observers: [], listeners: [], calls: 0, settled: 0 };
const timers = new Map();
const set = window.setTimeout.bind(window), clear = window.clearTimeout.bind(window);
window.setTimeout = (fn, ms, ...args) => {
const id = set(() => { timers.delete(id); fn(...args); }, ms);
if (ms === 12000) timers.set(id, () => fn(...args));
return id;
};
window.clearTimeout = (id) => { timers.delete(id); clear(id); };
state.expire = () => {
for (const [id, fn] of [...timers]) { clear(id); timers.delete(id); fn(); }
};
const NativeObserver = window.ResizeObserver;
window.ResizeObserver = class extends NativeObserver {
constructor(fn) { super(fn); this.targets = new Set(); state.observers.push(this); }
observe(target, ...args) { this.targets.add(target); return super.observe(target, ...args); }
unobserve(target) { this.targets.delete(target); return super.unobserve(target); }
disconnect() { this.targets.clear(); return super.disconnect(); }
};
const add = EventTarget.prototype.addEventListener, remove = EventTarget.prototype.removeEventListener;
const tracked = (target, type) => target instanceof HTMLCanvasElement ||
(target === document && type === 'visibilitychange') || (target === window && type === 'resize');
const capture = (opts) => typeof opts === 'boolean' ? opts : !!opts?.capture;
EventTarget.prototype.addEventListener = function (type, fn, opts) {
if (tracked(this, type) && !state.listeners.some((r) => r.target === this && r.type === type && r.fn === fn && r.capture === capture(opts))) {
state.listeners.push({ target: this, type, fn, capture: capture(opts) });
}
return add.call(this, type, fn, opts);
};
EventTarget.prototype.removeEventListener = function (type, fn, opts) {
state.listeners = state.listeners.filter((r) => !(r.target === this && r.type === type && r.fn === fn && r.capture === capture(opts)));
return remove.call(this, type, fn, opts);
};
state.snapshot = () => ({
apps: state.apps.map(({ app, ticker, canvas }) => ({ destroyed: app.renderer === null, ticking: ticker.started, attached: canvas.isConnected })),
observers: state.observers.filter((r) => r.targets.size).length,
listeners: state.listeners.map((r) => r.type),
canvases: document.querySelectorAll('#host canvas').length,
fallbacks: document.querySelectorAll('#host .ff').length,
});
}
function trackPixiApplications() {
const Application = PIXI.Application;
PIXI.Application = class extends Application {
constructor(...args) {
super(...args);
window.__initialization.apps.push({ app: this, ticker: this.ticker, canvas: this.view });
}
};
}
const FACTORY_WRAPPER = `export * from '/js/render/app.js?implementation';
import { createFieldView as create } from '/js/render/app.js?implementation';
export async function createFieldView(...args) {
window.__initialization.calls++;
if (window.__initialization.ignoreSignal) args[1] = { ...args[1], signal: undefined };
try { return await create(...args); }
finally { window.__initialization.settled++; }
}`;
describe('field initialization in headless Chrome', { skip }, () => {
let srv, browser, pixi;
before(async () => {
const puppeteer = (await import('puppeteer-core')).default;
const { startServer } = await import('../../server/index.js');
srv = await startServer({ port: 0, host: '127.0.0.1', quiet: true });
browser = await puppeteer.launch({ executablePath: CHROME, headless: true, args: ['--no-first-run'] });
pixi = readFileSync(path.join(ROOT, 'public/vendor/pixi.min.js'), 'utf8') + `\n;(${trackPixiApplications.toString()})();`;
});
after(async () => { await browser?.close(); await srv?.close(); });
async function open(t, { holdPixi = false } = {}) {
const page = await browser.newPage();
t.after(() => page.close());
const errors = [];
page.on('pageerror', (err) => errors.push(err.message));
await page.setViewport({ width: 1100, height: 750 });
await page.evaluateOnNewDocument(trackBrowserResources);
await page.setRequestInterception(true);
let releasePixi;
const requested = new Promise((resolve) => {
page.on('request', (request) => {
const url = new URL(request.url());
if (url.pathname === '/initialization-test') return request.respond({ status: 200, contentType: 'text/html', body: HTML });
if (url.pathname === '/js/render/app.js' && !url.search) return request.respond({ status: 200, contentType: 'text/javascript', body: FACTORY_WRAPPER });
if (url.pathname === '/vendor/pixi.min.js') {
releasePixi = () => request.respond({ status: 200, contentType: 'text/javascript', body: pixi });
resolve();
if (!holdPixi) return releasePixi();
return;
}
return request.continue();
});
});
await page.goto(`http://127.0.0.1:${srv.port}/initialization-test?board=2d`);
// Empty manifests prevent optional local art requests while preserving the real asset store.
await page.evaluate(async () => {
const { assets } = await import('/js/assets.js');
assets.seed({ version: 1, chars: {}, enemies: {}, tokens: {}, items: {} });
assets.seedLocal({ version: 1, files: {} });
const { data } = await import('/js/data.js');
await data.load('stages');
window.__initialization.stage = data.list('stages')[0];
window.__initialization.host = document.getElementById('host');
});
return { page, errors, requested, release: () => releasePixi() };
}
async function start(page) {
await page.evaluate(async () => {
const { mountFieldView } = await import('/js/ui/fieldHost.js');
const s = window.__initialization;
s.mount = mountFieldView(s.host).then((view) => {
s.view = view;
view.setStage(s.stage);
view.setPrep({ board: [], hand: [], temp: [] }, { editable: true });
s.clicks = [];
view.on('tileClick', (click) => s.clicks.push([click.row, click.col]));
});
});
}
async function pixiFinished(page) {
await page.evaluate(async () => {
const { ensurePixi } = await import('/js/render/app/pixi.js');
await ensurePixi();
await new Promise(requestAnimationFrame);
});
}
async function clickFallback(page) {
await page.waitForSelector('#host .ff-tile--floor');
const tile = await page.$eval('#host .ff-tile--floor', (element) => {
const r = element.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2, row: +element.dataset.row, col: +element.dataset.col };
});
await page.mouse.click(tile.x, tile.y);
return [tile.row, tile.col];
}
test('successful startup owns one running app and destroy releases its browser resources', async (t) => {
const { page, errors } = await open(t);
await start(page);
await page.waitForFunction(() => window.__initialization.view?.kind === 'engine');
const mounted = await page.evaluate(() => window.__initialization.snapshot());
assert.equal(mounted.canvases, 1);
assert.deepEqual(mounted.apps, [{ destroyed: false, ticking: true, attached: true }]);
assert.equal(mounted.observers, 1);
assert.ok(mounted.listeners.includes('pointerdown'));
assert.ok(mounted.listeners.includes('visibilitychange'));
const destroyed = await page.evaluate(() => {
const s = window.__initialization;
s.view.destroy(); s.view.destroy();
return s.snapshot();
});
assert.deepEqual(destroyed, { apps: [{ destroyed: true, ticking: false, attached: false }], observers: 0, listeners: [], canvases: 0, fallbacks: 0 });
assert.deepEqual(errors, []);
});
for (const ignoreSignal of [false, true]) test(`a timed-out Pixi load cannot cover the clickable fallback (${ignoreSignal ? 'legacy factory ignores cancellation' : 'cancellable factory'})`, async (t) => {
const { page, errors, requested, release } = await open(t, { holdPixi: true });
await page.evaluate((value) => { window.__initialization.ignoreSignal = value; }, ignoreSignal);
await start(page);
await requested;
await page.evaluate(() => window.__initialization.expire());
await page.waitForFunction(() => window.__initialization.view?.kind === 'fallback');
const target = await clickFallback(page);
assert.deepEqual(await page.evaluate(() => window.__initialization.clicks), [target]);
await release();
await pixiFinished(page);
await page.waitForFunction(() => window.__initialization.settled === 1);
await clickFallback(page);
const late = await page.evaluate(() => ({ ...window.__initialization.snapshot(), clicks: window.__initialization.clicks }));
assert.deepEqual(late.clicks, [target, target], 'real pointer input still reaches the fallback after Pixi finishes');
assert.equal(late.canvases, 0, 'the abandoned engine must not append an orphan canvas');
assert.equal(late.fallbacks, 1);
assert.ok(late.apps.every((app) => app.destroyed && !app.ticking && !app.attached));
assert.deepEqual(late.listeners, []);
assert.equal(late.observers, 1, 'only the fallback observes the host');
if (!ignoreSignal) {
mkdirSync(OUT, { recursive: true });
await page.screenshot({ path: path.join(OUT, 'render-initialization-fallback.png') });
}
const destroyed = await page.evaluate(() => { window.__initialization.view.destroy(); return window.__initialization.snapshot(); });
assert.equal(destroyed.observers, 0);
assert.equal(destroyed.canvases, 0);
assert.equal(destroyed.fallbacks, 0);
assert.deepEqual(errors, []);
});
test('timeout during board-art startup immediately releases the allocated app and permits a fresh engine', async (t) => {
const { page, errors } = await open(t);
await page.evaluate(async () => {
const { assets } = await import('/js/assets.js');
const s = window.__initialization, local = assets.local.bind(assets);
assets.local = () => {
if (!s.apps.length) return local();
assets.local = local;
s.artBlocked = true;
return new Promise((resolve) => { s.releaseArt = async () => resolve(await local()); });
};
});
await start(page);
await page.waitForFunction(() => window.__initialization.artBlocked);
const allocated = await page.evaluate(() => window.__initialization.snapshot());
assert.deepEqual(allocated.apps, [{ destroyed: false, ticking: true, attached: true }]);
await page.evaluate(() => window.__initialization.expire());
await page.waitForFunction(() => window.__initialization.view?.kind === 'fallback');
const cancelled = await page.evaluate(() => window.__initialization.snapshot());
assert.deepEqual(cancelled.apps, [{ destroyed: true, ticking: false, attached: false }], 'cancellation frees the real renderer before the delayed art resolves');
assert.equal(cancelled.canvases, 0);
assert.equal(cancelled.observers, 1);
assert.deepEqual(cancelled.listeners, []);
const target = await clickFallback(page);
assert.deepEqual(await page.evaluate(() => window.__initialization.clicks), [target]);
await page.evaluate(async () => {
const s = window.__initialization;
await s.releaseArt();
s.view.destroy();
s.view = null;
});
await page.waitForFunction(() => window.__initialization.settled === 1);
await start(page);
await page.waitForFunction(() => window.__initialization.view?.kind === 'engine');
const replacement = await page.evaluate(async () => {
await new Promise(requestAnimationFrame);
const s = window.__initialization, app = s.view.raw.debug.app;
app.renderer.render(app.stage);
return s.snapshot();
});
assert.deepEqual(replacement.apps, [
{ destroyed: true, ticking: false, attached: false },
{ destroyed: false, ticking: true, attached: true },
], 'a replacement engine can render with the surviving shared caches');
assert.equal(replacement.canvases, 1);
const destroyed = await page.evaluate(() => { window.__initialization.view.destroy(); return window.__initialization.snapshot(); });
assert.ok(destroyed.apps.every((app) => app.destroyed && !app.ticking && !app.attached));
assert.equal(destroyed.observers, 0);
assert.deepEqual(destroyed.listeners, []);
assert.equal(destroyed.canvases, 0);
assert.deepEqual(errors, []);
});
test('a setup exception releases partial resources without removing another host child', async (t) => {
const { page, errors } = await open(t);
await page.evaluate(async () => {
const { assets } = await import('/js/assets.js');
const s = window.__initialization, subscribe = assets.onChange.bind(assets);
s.sibling = document.createElement('span');
s.sibling.textContent = 'Existing host content';
s.host.appendChild(s.sibling);
// Fail after input and resize resources exist, while the real view is still being built.
assets.onChange = (fn) => {
if (s.observers.some((observer) => observer.targets.has(s.host))) {
assets.onChange = subscribe;
throw new Error('asset subscription unavailable');
}
return subscribe(fn);
};
});
await start(page);
await page.waitForFunction(() => window.__initialization.view?.kind === 'fallback');
const failed = await page.evaluate(() => ({ ...window.__initialization.snapshot(), sibling: window.__initialization.sibling.isConnected }));
assert.deepEqual(failed.apps, [{ destroyed: true, ticking: false, attached: false }]);
assert.equal(failed.sibling, true, 'failed initialization only cleans up its own resources');
assert.equal(failed.canvases, 0);
assert.equal(failed.observers, 1);
assert.deepEqual(failed.listeners, []);
const target = await clickFallback(page);
assert.deepEqual(await page.evaluate(() => window.__initialization.clicks), [target]);
const destroyed = await page.evaluate(() => { window.__initialization.view.destroy(); return window.__initialization.snapshot(); });
assert.equal(destroyed.observers, 0);
assert.equal(destroyed.fallbacks, 0);
assert.deepEqual(errors, []);
});
test('unmount during startup cannot erase a newer hook mount on the same host', async (t) => {
const { page, errors, requested, release } = await open(t, { holdPixi: true });
await page.evaluate(async () => {
const { h, render } = await import('/vendor/preact.module.js');
const { useFieldView } = await import('/js/ui/fieldHost.js');
const s = window.__initialization;
function Field() { s.hook = useFieldView({ current: s.host }); return null; }
s.renderHook = (key) => render(key ? h(Field, { key }) : null, document.getElementById('hooks'));
s.renderHook('first');
});
await requested;
await page.evaluate(() => {
const s = window.__initialization;
s.renderHook(null);
window.__SP_RENDER__ = 'fallback';
s.renderHook('second');
});
await page.waitForFunction(() => window.__initialization.hook?.kind === 'fallback');
await page.evaluate(() => {
const s = window.__initialization;
s.current = s.hook.view;
s.current.setStage(s.stage);
s.current.setPrep({ board: [], hand: [], temp: [] }, { editable: true });
s.clicks = [];
s.current.on('tileClick', (click) => s.clicks.push([click.row, click.col]));
s.expire();
});
await release();
await pixiFinished(page);
await page.waitForFunction(() => window.__initialization.settled === 1);
const late = await page.evaluate(() => ({ ...window.__initialization.snapshot(), current: window.__SP_VIEW__ === window.__initialization.current }));
assert.equal(late.fallbacks, 1, 'the old mount must not clear the newer view from the shared host');
assert.equal(late.canvases, 0);
assert.equal(late.current, true);
assert.ok(late.apps.every((app) => app.destroyed && !app.ticking && !app.attached));
const target = await clickFallback(page);
assert.deepEqual(await page.evaluate(() => window.__initialization.clicks), [target]);
const destroyed = await page.evaluate(() => {
window.__initialization.renderHook(null);
return { ...window.__initialization.snapshot(), current: window.__SP_VIEW__ };
});
assert.equal(destroyed.current, null);
assert.equal(destroyed.observers, 0);
assert.equal(destroyed.canvases, 0);
assert.equal(destroyed.fallbacks, 0);
assert.deepEqual(destroyed.listeners, []);
assert.deepEqual(errors, []);
});
});
+71
View File
@@ -279,6 +279,77 @@ describe('enemy preview pen figures (lod idle)', () => {
});
});
// The impostor refreshes of a frame are spread evenly over the interval (app.js impostorSlot: each frame the impostor
// units take slots 0, 1, 2 … in update order): a frame refreshes ⌊n/k⌋ or ⌈n/k⌉ of n units. With a random phase per
// unit, the busiest frame did 20–66% more refreshes than that (16–48 units, intervals 2–6) — the frame-time peaks of a
// crowded battle on a slow device.
describe('impostor refresh slots', () => {
/** n pen figures (lod idle: interval 3) in one context; `slotOf(frame, i)` gives view i its slot, or null: no slots. */
async function crowd(n, slotOf) {
let frame = 0;
let i = 0;
const atlas = {
alloc: (w, h) => ({ w, h, tex: new fake.P.Texture(), clip: false }),
free() {}, park(o) { o.visible = false; }, unpark(o) { o.visible = true; }, draw() {},
};
const ctx = fakeViewCtx(fake.P, {
assets: store({ spine: true }), cam, frameNo: () => frame, impostors: atlas,
renderer: { resolution: 1, render() {} },
...(slotOf ? { impostorSlot: () => slotOf(frame, i) } : {}),
});
const views = [];
for (let k = 0; k < n; k++) {
views.push(new UnitView(ctx, { id: `e:${k}`, side: 'enemy', kind: 'enemy', defId: 'enemy_1007_slime', tier: 1, x: 9, y: 15, maxHp: 1, facing: -1 }, { prep: true, lod: 'idle' }));
}
await tick(); await tick();
const refreshed = views.map(() => []);
views.forEach((v, k) => {
assert.ok(v.spineReady, 'spine ready');
const upd = v.actor.update.bind(v.actor);
v.actor.update = (dt) => { refreshed[k].push(frame); return upd(dt); };
});
const step = () => { views.forEach((v, k) => { i = k; v.update(1 / 60, cam(), frame / 60); }); frame++; };
return { step, refreshed, frames: () => frame };
}
const perFrame = (refreshed, from, to) => {
const c = new Map();
for (const list of refreshed) for (const f of list) if (f >= from && f < to) c.set(f, (c.get(f) || 0) + 1);
return Array.from({ length: to - from }, (_, j) => c.get(from + j) || 0);
};
test('slots in update order: every frame refreshes ⌊n/3⌋ or ⌈n/3⌉ units, each unit every 3rd frame', async () => {
for (const n of [7, 16, 24]) {
const { step, refreshed } = await crowd(n, (frame, k) => k);
for (let f = 0; f < 31; f++) step();
// frame 0: every new impostor is drawn once (dirty); from frame 1 on, the interval rules
const counts = perFrame(refreshed, 1, 31);
assert.ok(counts.every((c) => c === Math.floor(n / 3) || c === Math.ceil(n / 3)), `${n} units: ${counts.join(' ')}`);
for (const list of refreshed) {
const after = list.filter((f) => f >= 1);
assert.equal(after.length, 10, `each unit refreshed 10 times in 30 frames (${after.join(',')})`);
assert.ok(after.every((f, j) => j === 0 || f - after[j - 1] === 3), 'exactly every 3rd frame');
}
}
});
test('a slot that moves with the frame never starves a unit: refreshed at least every 2 intervals', async () => {
// (frame + slot) % 3 is never 0: the turn alone would never come
const { step, refreshed } = await crowd(3, (frame) => 4 - (frame % 3));
for (let f = 0; f < 31; f++) step();
for (const list of refreshed) {
const after = list.filter((f) => f >= 1);
assert.ok(after.length >= 5, `refreshed ${after.length} times`);
assert.ok([0, ...after].every((f, j, a) => j === 0 || f - a[j - 1] <= 6), `gaps ≤ 6 frames (${after.join(',')})`);
}
});
test('without slots (a context that has none) the random phase still refreshes every 3rd frame', async () => {
const { step, refreshed } = await crowd(5, null);
for (let f = 0; f < 31; f++) step();
for (const list of refreshed) assert.equal(list.filter((f) => f >= 1).length, 10);
});
});
// Player report 2026-10-05: 「无人机等飞行单位贴图位置明显偏低」, and the follow-up "绝对不止 0.35" with an official
// screenshot of 帝国炮火先兆者 over a tile (PR #211 by @xcdoge; the owner's decision of 2026-10-06). The lift is the
// official client's own single constant — Vector3(0, 0.35, 0) written by Torappu.Battle.CharacterAnimator's constructor