feat: 比例适配、bgm 音源选择与 fps 限流,打包 v3

取景(issue 04)
- 新增 viewport-fitter.js:让立绘层缩放跟随背景图的 cover 缩放——背景放大多少倍、
  特效就放大多少倍。原先背景走 cover、立绘层走 contain,比例一变两者就分叉。
  16:9 下与作者设定逐像素一致(kv37 为 0 差异)。实测证伪了"contain 会裁掉作者视口"
  这个最初的判断:contain 在任何比例下都完整含住作者视口。
- 应用方式为原地改写 config.viewport 字段后调 setViewport(),不重建播放器;
  维护挂在 config.frame 上按画布比例增量进行(config.success 早于 setViewport,拿不到视口)。

WE 属性(issue 05)
- project.json 新增 bgm combo(所有壁纸音源的并集 + 「随预设」);所选项不属于当前壁纸时
  音频回落该壁纸默认,选择本身保留。
- fps 限流包裹实例 drawFrame 并接管排程。修掉两个实测缺陷:朴素丢帧会把 rAF 抖动放大成
  整拍丢失(目标 30fps 实测只有 22.5fps);fps:0 被真值判断吞掉导致无法取消限流。

打包(issue 06)
- project.json version 升至 3 并更新描述;preset 的 combo 取值保持 xilian/kv37 不变。
- preview.gif 821 KB → 347 KB(每 2 帧取 1 帧 + 128 色不抖动,逐帧与源帧像素完全相同)。
- index.html 加内联 favicon,消除 CEF 自动请求 /favicon.ico 造成的 404 报错。

其它
- dist/scripts/wallpaper-engine.js 移到 tools/:它没有任何入口引用,且环境判据依赖真实 WE
  并不存在的 wallpaperRegisterListener,一旦按它自己的说明挂进 index.html 会在生产环境自我激活。
- 修正死文件检查:原检查会拿文件名匹配到文件自身的内容,使这类文件漏网。
- 新增离线算式验证与 resize / 属性 / 全量验收三套浏览器测试脚本。
This commit is contained in:
Shuery committed 2026-09-19 20:29:25 +08:00
1 parent 4662856963
commit eb56efbd9e
22 files changed
+2766 -1012

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
$ErrorActionPreference = "Stop"
Set-Location D:\Workspace\Temp\SpineWallpaper
$sizes = @(
@(3440, 1440, "219"),
@(1920, 1080, "169"),
@(1080, 1920, "916")
)
$props = @{
"xilian" = ""
"kv37" = "&__props=%7B%22preset%22%3A%22kv37%22%7D"
}
New-Item -ItemType Directory -Force -Path tools\shots\fit | Out-Null
foreach ($p in @("xilian", "kv37")) {
foreach ($s in $sizes) {
$w = $s[0]; $h = $s[1]; $tag = $s[2]
$url = "http://127.0.0.1:8190/?__freeze=1" + $props[$p]
Write-Host "=== $p $tag ($w x $h) ==="
node tools/shot.mjs "tools/shots/fit/${p}_${tag}.png" $url $w $h 2>&1 | Select-Object -First 1
node tools/shot.mjs "tools/shots/fit/${p}_${tag}_ref.png" "$url&__hide=canvas" $w $h 2>&1 | Select-Object -First 1
node tools/subject.mjs "tools/shots/fit/${p}_${tag}.png" "tools/shots/fit/${p}_${tag}_ref.png"
Write-Host ""
}
}
+135
View File
@@ -0,0 +1,135 @@
// Issue 06 全量验收。
// ① dist 体积与死文件;② project.json 与代码一致;③ 三种比例 0 控制台报错;
// ④ 预设往返不丢用户级音源/音量设置。
import { readdirSync, readFileSync, statSync } from "node:fs";
import { basename, extname, join } from "node:path";
import { withPage, sleep } from "../tools/cdp.mjs";
let failures = 0;
const check = (ok, msg, detail) => {
if (!ok) failures++;
console.log(` ${ok ? "✓" : "✗"} ${msg}${detail !== undefined ? ` → ${detail}` : ""}`);
};
// ── ① 体积与死文件 ──
console.log("=== ① dist 体积与死文件 ===");
const walk = (dir) =>
readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
const p = join(dir, e.name);
return e.isDirectory() ? walk(p) : [p];
});
const files = walk("dist");
const total = files.reduce((s, f) => s + statSync(f).size, 0);
check(total <= 35 * 1024 * 1024, "总体积 ≤ 35 MB", `${(total / 1048576).toFixed(2)} MB / ${files.length} 个文件`);
const TEXT = new Set([".html", ".js", ".json", ".txt", ".css", ".atlas"]);
const texts = files.filter((f) => TEXT.has(extname(f)));
const contents = new Map(texts.map((f) => [f, readFileSync(f, "utf8")]));
// 这四个是 WE 的元数据/入口/说明,本来就不被页面引用
const ALLOWED = new Set(["project.json", "README.txt", "index.html", "preview.gif"]);
// 关键:比对时要把文件**自身**的内容排除掉。否则一个文件只要在自己开头写上自己的名字
// (比如注释里的 "// wallpaper-engine.js")就会被判为"被引用",死文件因此漏网。
const dead = files.filter((f) => {
const n = basename(f);
if (ALLOWED.has(n)) return false;
const others = texts
.filter((t) => t !== f)
.map((t) => contents.get(t))
.join("\n");
return !others.includes(n);
});
check(dead.length === 0, "0 个死文件", dead.length ? dead.join(", ") : "无孤立资源");
// ── ② project.json ──
console.log("\n=== ② project.json ===");
const project = JSON.parse(readFileSync("dist/project.json", "utf8"));
check(project.version === 3, "version = 3", String(project.version));
check(project.preview === "preview.gif", "preview 指向 preview.gif");
check(!!project.general.properties.bgm, "新增 bgm combo");
check(project.general.properties.preset.value === "xilian", "preset 默认值未变");
const presetValues = project.general.properties.preset.options.map((o) => o.value).sort();
check(
JSON.stringify(presetValues) === JSON.stringify(["kv37", "xilian"]),
"preset 的 combo 取值未变(用户已保存的设置依赖它)",
presetValues.join(", "),
);
const bgmValues = project.general.properties.bgm.options.map((o) => o.value);
check(bgmValues.includes("auto"), "bgm 含「随预设」档", bgmValues.join(", "));
const gifSize = statSync("dist/preview.gif").size;
check(gifSize < 500 * 1024, "preview.gif < 500 KB", `${(gifSize / 1024).toFixed(0)} KB`);
// ── ③ 三种比例 0 报错 ──
console.log("\n=== ③ 21:9 / 16:9 / 9:16 控制台与异常 ===");
for (const [w, h, tag] of [
[3440, 1440, "21:9"],
[1920, 1080, "16:9"],
[1080, 1920, "9:16"],
]) {
const r = await withPage({ width: w, height: h }, async ({ send, evaluate, consoleLines, exceptions }) => {
await send("Page.navigate", { url: "http://127.0.0.1:8190/?__freeze=1" });
const deadline = Date.now() + 30000;
let ready = false;
while (Date.now() < deadline) {
if (await evaluate('!!(window.__test && (window.__test.successAt || window.__test.error))')) {
ready = true;
break;
}
await sleep(150);
}
await sleep(500);
const state = await evaluate(`(function(){
var p = window.__player, v = p.currentViewport;
return { w: p.canvas.clientWidth, h: p.canvas.clientHeight,
vw: +v.width.toFixed(1), vh: +v.height.toFixed(1),
err: window.__test.error || null };
})()`);
return { ready, state, consoleLines, exceptions };
});
const noisy = r.consoleLines.filter((l) => /error|uncaught|fail/i.test(l));
const aspectOk = r.state && Math.abs(r.state.vw / r.state.vh - r.state.w / r.state.h) < 0.002;
check(r.ready && !r.state?.err, `${tag} 播放器就绪`, r.state?.err ?? "无错");
check(aspectOk, `${tag} 可见矩形比例与画布一致`, r.state ? `${r.state.vw}×${r.state.vh}` : "—");
check(noisy.length === 0 && r.exceptions.length === 0, `${tag} 0 控制台报错 / 0 异常`, noisy.concat(r.exceptions).slice(0, 3).join(" | ") || "干净");
}
// ── ④ 预设往返不丢音频设置 ──
console.log("\n=== ④ 预设往返 10 次,音频设置不得丢失 ===");
const rt = await withPage({ width: 1280, height: 720 }, async ({ send, evaluate, exceptions }) => {
await send("Page.navigate", { url: "http://127.0.0.1:8190/?__freeze=1" });
const deadline = Date.now() + 30000;
while (Date.now() < deadline) {
if (await evaluate('!!(window.__test && (window.__test.successAt || window.__test.error))')) break;
await sleep(150);
}
await sleep(500);
await evaluate(`window.wallpaperPropertyListener.applyUserProperties({
audio_file: { value: "https://example.com/custom-track.mp3" },
audio_volume: { value: 0.2 }
})`);
await sleep(300);
const rows = [];
for (let i = 0; i < 10; i++) {
const id = i % 2 === 0 ? "kv37" : "xilian";
await evaluate(`window.wallpaperPropertyListener.applyUserProperties({ preset: { value: "${id}" } })`);
await sleep(320);
rows.push(
await evaluate(`(function(){
var a = document.getElementById("background-music");
return { id: "${id}", src: a.src.split("/").pop(), vol: a.volume,
draws: window.__test.drawCalls };
})()`),
);
}
return { rows, exceptions };
});
const srcOk = rt.rows.every((r) => r.src === "custom-track.mp3");
const volOk = rt.rows.every((r) => Math.abs(r.vol - 0.2) < 0.001);
check(srcOk, "10 次切换后自定义音源仍生效", [...new Set(rt.rows.map((r) => r.src))].join(", "));
check(volOk, "10 次切换后音量仍为 0.2", [...new Set(rt.rows.map((r) => r.vol))].join(", "));
check(rt.rows[rt.rows.length - 1].draws > rt.rows[0].draws, "切换后仍在持续绘制", `${rt.rows[0].draws} → ${rt.rows[rt.rows.length - 1].draws}`);
check(rt.exceptions.length === 0, "往返过程 0 未捕获异常", rt.exceptions.join(" | ") || "无");
console.log(`\n结论:${failures === 0 ? "全部通过 ✓" : `${failures} 项失败 ✗`}`);
process.exit(failures === 0 ? 0 : 1);
+137
View File
@@ -0,0 +1,137 @@
// Issue 05 验收:bgm 音源 combo 与 fps 限流。
//
// A 段验音源优先级:用户自填 URL > bgm 选择(仅当本壁纸声明过)> 本壁纸默认音源;
// 且 bgm 选择跨壁纸时"音频回落、选择保留"。
// B 段验 fps:WE 不替壁纸限流,得自己门控。关键是限流只该丢帧,
// 不该改变动画相位推进速度——用同一段真实时间里 trackTime 前进了多少来判定。
import { withPage, sleep } from "../tools/cdp.mjs";
const BASE = "http://127.0.0.1:8190/";
const name = (src) => (src ? decodeURIComponent(String(src).split("/").pop()) : "(空)");
let failures = 0;
const check = (ok, msg, detail) => {
if (!ok) failures++;
console.log(` ${ok ? "✓" : "✗"} ${msg}${detail !== undefined ? ` → ${detail}` : ""}`);
};
// ───────────────────────── A 段:音源 ─────────────────────────
console.log("=== A 段:bgm 音源选择与回落 ===");
await withPage({ width: 1280, height: 720 }, async ({ send, evaluate, exceptions }) => {
await send("Page.navigate", { url: BASE + "?__freeze=1" });
const deadline = Date.now() + 30000;
while (Date.now() < deadline) {
if (await evaluate('!!(window.__test && (window.__test.successAt || window.__test.error))')) break;
await sleep(150);
}
await sleep(600);
const src = () => evaluate('document.getElementById("background-music").src');
const preset = (v) => evaluate(`window.wallpaperPropertyListener.applyUserProperties({ preset: { value: ${JSON.stringify(v)} } })`);
const bgm = (v) => evaluate(`window.wallpaperPropertyListener.applyUserProperties({ bgm: { value: ${JSON.stringify(v)} } })`);
const file = (v) => evaluate(`window.wallpaperPropertyListener.applyUserProperties({ audio_file: { value: ${JSON.stringify(v)} } })`);
const seen = [];
const step = async (label, action, expected) => {
await action();
await sleep(350);
const got = name(await src());
seen.push(`${label}=${got}`);
check(got === expected, label, `期望 ${expected},实得 ${got}`);
};
// 载入即 xilian,默认音源应是「再度和你」
check(name(await src()) === "再度和你.ogg", "初始默认音源 = 昔涟立绘默认", name(await src()));
await step("bgm 选「昔涟」", () => bgm("xilian"), "昔涟.ogg");
await step("切到 kv37(选择不属于它)→ 回落", () => preset("kv37"), "pv37.mp3");
await step("bgm 选「版本 PV」(属于 kv37)", () => bgm("pv37"), "pv37.mp3");
await step("切回 xilian(pv37 不属于它)→ 回落", () => preset("xilian"), "再度和你.ogg");
await step("bgm 选「「再度和你」」", () => bgm("zaiduheni"), "再度和你.ogg");
await step("bgm 回到「随预设」", () => bgm("auto"), "再度和你.ogg");
// 用户自填 URL 优先级最高
await step("bgm 选「昔涟」后填自定义 URL", async () => {
await bgm("xilian");
await file("https://example.com/custom-track.mp3");
}, "custom-track.mp3");
await step("切壁纸不得清掉自定义 URL", () => preset("kv37"), "custom-track.mp3");
await step("清空自定义 URL → 回到预设默认", () => file(""), "pv37.mp3");
console.log(` 音源轨迹: ${seen.join(" | ")}`);
console.log(` 未捕获异常: ${exceptions.length ? exceptions.join(" | ") : "无 ✓"}`);
if (exceptions.length) failures++;
});
// ───────────────────────── B 段:fps ─────────────────────────
console.log("\n=== B 段:fps 限流 ===");
await withPage({ width: 1280, height: 720 }, async ({ send, evaluate, exceptions }) => {
// 空 __props 只用来触发测试驱动注入(不带它就不会注入),既不冻结也不改属性
await send("Page.navigate", { url: BASE + "?__props=%7B%7D" });
const deadline = Date.now() + 30000;
while (Date.now() < deadline) {
if (await evaluate('!!(window.__test && (window.__test.successAt || window.__test.error))')) break;
await sleep(150);
}
await sleep(1200); // 让动画先跑起来,避开启动瞬态
const probe = `(function(){
var p = window.__player;
var e = p.animationState.getCurrent(0);
return { trackTime: e.trackTime, duration: e.animation.duration,
draws: window.__test.drawCalls, t: performance.now() };
})()`;
const sample = async (seconds) => {
const a = await evaluate(probe);
await sleep(seconds * 1000);
const b = await evaluate(probe);
const wall = (b.t - a.t) / 1000;
let phase = b.trackTime - a.trackTime;
if (phase < 0) phase += b.duration; // 动画正好绕回
return { wall, draws: b.draws - a.draws, fps: (b.draws - a.draws) / wall, phaseRate: phase / wall };
};
const setFps = async (v) => {
await evaluate(`window.wallpaperPropertyListener.applyGeneralProperties({ fps: ${v} })`);
await sleep(400);
};
const results = [];
const run = async (label, target) => {
const r = await sample(2.0);
const row = { label, target, ...r };
results.push(row);
console.log(
` ${label.padEnd(16)} 实测 ${r.fps.toFixed(1)} fps` +
(target ? `(目标 ${target})` : "(不限流)") +
` 动画相位推进 ${r.phaseRate.toFixed(3)} 倍速`,
);
return row;
};
const base = await run("不限流", 0);
await setFps(30);
const f30 = await run("限 30 fps", 30);
await setFps(20);
const f20 = await run("限 20 fps", 20);
await setFps(0);
const back = await run("恢复不限流", 0);
check(Math.abs(f30.fps - 30) / 30 < 0.25, "限 30 fps 生效", `实测 ${f30.fps.toFixed(1)}`);
check(Math.abs(f20.fps - 20) / 20 < 0.25, "限 20 fps 生效", `实测 ${f20.fps.toFixed(1)}`);
check(f30.fps < base.fps * 0.75, "限流确实减少了绘制次数", `${base.fps.toFixed(1)} → ${f30.fps.toFixed(1)}`);
check(back.fps > f30.fps * 1.5, "取消限流后帧率恢复", `${f30.fps.toFixed(1)} → ${back.fps.toFixed(1)}`);
for (const r of [f30, f20, back]) {
check(
Math.abs(r.phaseRate - base.phaseRate) / base.phaseRate < 0.1,
`动画相位推进速度未受 ${r.label} 影响`,
`${r.phaseRate.toFixed(3)} vs 基准 ${base.phaseRate.toFixed(3)}`,
);
}
console.log(` 未捕获异常: ${exceptions.length ? exceptions.join(" | ") : "无 ✓"}`);
if (exceptions.length) failures++;
});
console.log(`\n结论:${failures === 0 ? "全部通过 ✓" : `${failures} 项失败 ✗`}`);
process.exit(failures === 0 ? 0 : 1);
+126
View File
@@ -0,0 +1,126 @@
// 验收测试:改窗口尺寸不得重建播放器,且取景要跟着画布比例走。
//
// 判据是"播放器实例身份":给加载后的实例打上标记,之后每次改视口都核对
// window.__player 是否还是同一个对象、标记是否还在。重建会换掉实例,
// 标记随之消失——这比数日志可靠得多。
import { withPage, sleep } from "../tools/cdp.mjs";
const URL = "http://127.0.0.1:8190/?__freeze=1";
const sizes = [
[1920, 1080],
[2560, 1440],
[3440, 1440],
[1080, 1920],
[1600, 900],
[2560, 1600],
[3840, 2160],
[1280, 720],
[1920, 1080],
];
const stress = [];
for (let i = 0; i < 20; i++) stress.push(i % 2 ? [1080, 1920] : [1920, 1080]);
const out = await withPage(
{ width: 1920, height: 1080, extraArgs: ["--enable-precise-memory-info", "--js-flags=--expose-gc"] },
async ({ send, evaluate, consoleLines, exceptions }) => {
await send("Page.navigate", { url: URL });
const deadline = Date.now() + 30000;
while (Date.now() < deadline) {
if (await evaluate('!!(window.__test && (window.__test.successAt || window.__test.error))')) break;
await sleep(150);
}
await sleep(600);
const stamp = await evaluate(`(function(){
window.__first = window.__player;
if (window.__player) window.__player.__probe = 'A';
return { hasPlayer: !!window.__player, error: window.__test ? window.__test.error : null };
})()`);
const rows = [];
const measure = async (w, h, tag) => {
await send("Emulation.setDeviceMetricsOverride", {
width: w,
height: h,
deviceScaleFactor: 1,
mobile: false,
});
await sleep(420);
// 先强制回收再读堆,否则量到的是 V8 的延迟回收节奏而不是真实占用
await evaluate('(typeof gc === "function") ? (gc(), true) : false');
const r = await evaluate(`(function(){
var p = window.__player;
if (!p) return null;
var v = p.currentViewport;
return {
same: p === window.__first,
probe: p.__probe,
css: [p.canvas.clientWidth, p.canvas.clientHeight],
resolved: [ +v.x.toFixed(2), +v.y.toFixed(2), +v.width.toFixed(2), +v.height.toFixed(2) ],
pad: [v.padLeft, v.padRight, v.padTop, v.padBottom],
childViews: window.__player.config.viewport.animations ? Object.keys(window.__player.config.viewport.animations).length : -1,
heap: performance.memory ? performance.memory.usedJSHeapSize : 0,
drawCalls: window.__test ? window.__test.drawCalls : 0
};
})()`);
rows.push({ tag, w, h, ...(r ?? { same: false, probe: null, css: null, resolved: null, pad: null, heap: 0, drawCalls: 0 }) });
};
for (const [w, h] of sizes) await measure(w, h, `${w}x${h}`);
const heapBeforeStress = rows[rows.length - 1].heap;
for (const [w, h] of stress) await measure(w, h, `压力 ${w}x${h}`);
const heapAfterStress = rows[rows.length - 1].heap;
return { stamp, rows, heapBeforeStress, heapAfterStress, consoleLines, exceptions };
},
);
const { stamp, rows, heapBeforeStress, heapAfterStress, consoleLines, exceptions } = out;
let failures = 0;
const fail = (msg) => {
failures++;
console.log(` ✗ ${msg}`);
};
console.log(`播放器就绪: ${stamp.hasPlayer ? "是" : "否"} 驱动报错: ${stamp.error ?? "无"}`);
console.log("");
console.log("画布尺寸 实例未重建 内边距 可见矩形 比例核对");
for (const r of rows) {
if (r.tag.startsWith("压力")) continue;
const a = r.w / r.h;
const ra = r.resolved ? r.resolved[2] / r.resolved[3] : NaN;
const ratioOk = Math.abs(ra - a) < 0.002;
const padOk = r.pad && r.pad.every((p) => p === 0);
const rect = r.resolved ? r.resolved.map((n) => String(n).padStart(9)).join(" ") : "—";
console.log(
`${r.tag.padEnd(14)} ${String(r.same).padEnd(10)} ${(padOk ? "全 0 ✓" : JSON.stringify(r.pad)).padEnd(10)} ${rect} ${ratioOk ? "✓" : `✗ 期望 ${a.toFixed(4)} 实得 ${ra.toFixed(4)}`}`,
);
if (!r.same) fail(`${r.tag} 重建了播放器(标记丢失: ${r.probe})`);
if (!padOk) fail(`${r.tag} 内边距没有归零`);
if (!ratioOk) fail(`${r.tag} 可见矩形比例与画布不符`);
}
// 首尾同为 1920x1080:取景必须回到完全相同的值,证明重算可逆、无漂移
const first = rows.find((r) => r.tag === "1920x1080");
const last = [...rows].reverse().find((r) => r.tag === "1920x1080");
const reversible = first.resolved.every((n, i) => Math.abs(n - last.resolved[i]) < 0.01);
if (!reversible) fail(`回到 16:9 后取景漂移:${first.resolved} → ${last.resolved}`);
console.log(`\n回到 16:9 取景可逆: ${reversible ? "✓" : "✗"} ${first.resolved} → ${last.resolved}`);
const growth = heapAfterStress - heapBeforeStress;
console.log(`连续 20 次 resize 堆内存: ${(heapBeforeStress / 1048576).toFixed(1)} MB → ${(heapAfterStress / 1048576).toFixed(1)} MB(增长 ${(growth / 1048576).toFixed(2)} MB)`);
if (growth > 4 * 1048576) fail(`连续 resize 内存增长过大:${(growth / 1048576).toFixed(2)} MB`);
const drawCalls = rows[rows.length - 1].drawCalls;
console.log(`累计绘制帧数: ${drawCalls}`);
if (!(drawCalls > 0)) fail("没有绘制任何帧");
const noisy = consoleLines.filter((l) => /error|warn|uncaught|fail/i.test(l));
console.log(`控制台异常: ${noisy.length ? noisy.slice(0, 5).join(" | ") : "无 ✓"}`);
if (noisy.length) fail("控制台有报错/警告");
console.log(`未捕获异常: ${exceptions.length ? exceptions.slice(0, 4).join(" | ") : "无 ✓"}`);
if (exceptions.length) fail("有未捕获异常");
console.log(`\n结论:${failures === 0 ? "全部通过 ✓" : `${failures} 项失败 ✗`}`);
process.exit(failures === 0 ? 0 : 1);
+72
View File
@@ -0,0 +1,72 @@
// 取景公式的离线验证:不依赖浏览器,直接对 viewport-fitter.js 求值。
// 两条硬约束:① 16:9 下必须与作者设定完全一致;② 立绘层缩放比必须等于背景 cover 缩放比。
import { readFileSync } from "node:fs";
const src = readFileSync(new URL("../dist/scripts/viewport-fitter.js", import.meta.url), "utf8").replace(/^export\s+/gm, "");
const mod = new Function(
src + "\nreturn { contain, frameForAspect, coverScale, resolveViewport, toViewportConfig, REFERENCE_ASPECT };",
)();
const rect = (x, y, width, height) => ({ x, y, width, height });
const fmt = (r) =>
`x=${r.x.toFixed(2)} y=${r.y.toFixed(2)} w=${r.width.toFixed(2)} h=${r.height.toFixed(2)} 比例=${(r.width / r.height).toFixed(4)}`;
const cases = [
{
name: "xilian(昔涟立绘)",
R: rect(-2181.72, 1442.39, 4226.57, 3403.35),
imgW: 2048,
imgH: 1080,
},
{
name: "kv37(「成为昨日的明天」)",
R: rect(-1419.8, -512.4, 2457.6, 1228.8),
imgW: 2560,
imgH: 1440,
},
];
const canvases = [
[3440, 1440, "21:9"],
[1920, 1080, "16:9"],
[2560, 1600, "16:10"],
[1080, 1920, "9:16"],
];
// 背景走 CSS background-size:cover,它在画布上真实的像素缩放就是这两个候选里的较大者。
const bgScale = (w, h, imgW, imgH) => Math.max(w / imgW, h / imgH);
let failures = 0;
for (const c of cases) {
const imgAspect = c.imgW / c.imgH;
const V0 = mod.contain(c.R, mod.REFERENCE_ASPECT);
console.log(`\n=== ${c.name} 背景图 ${c.imgW}x${c.imgH}(比例 ${imgAspect.toFixed(4)}) ===`);
console.log(`作者视口 R : ${fmt(c.R)}`);
console.log(`参考取景 V0 : ${fmt(V0)}`);
// 基准取 16:9 1080p:立绘与背景都以此为准比较"被放大了多少倍"
const refCanvas = [1920, 1080];
const spinePx0 = refCanvas[1] / V0.height;
const bgPx0 = bgScale(refCanvas[0], refCanvas[1], c.imgW, c.imgH);
for (const [w, h, tag] of canvases) {
const aspect = w / h;
const V = mod.frameForAspect(V0, aspect, imgAspect);
const spineRatio = h / V.height / spinePx0;
const bgRatio = bgScale(w, h, c.imgW, c.imgH) / bgPx0;
const synced = Math.abs(spineRatio - bgRatio) < 1e-6;
if (!synced) failures++;
console.log(
` ${tag.padEnd(5)} ${String(w).padStart(4)}x${String(h).padEnd(4)} ${fmt(V)}` +
` 立绘 x${spineRatio.toFixed(4)} 背景 x${bgRatio.toFixed(4)} ${synced ? "同步 ✓" : "不同步 ✗"}`,
);
}
// 参考比例下必须与作者设定逐像素一致,且必须与拟合前的真实渲染值吻合
const Vref = mod.frameForAspect(V0, mod.REFERENCE_ASPECT, imgAspect);
const untouched = ["x", "y", "width", "height"].every((k) => Math.abs(Vref[k] - V0[k]) < 1e-9);
if (!untouched) failures++;
console.log(` 参考比例回归: ${untouched ? "与作者设定完全一致 ✓" : "被改动 ✗"}`);
}
console.log(`\n结论:${failures === 0 ? "全部通过 ✓" : `${failures} 项失败 ✗`}`);
process.exit(failures === 0 ? 0 : 1);
@@ -1,20 +1,68 @@
# 04 比例适配:按容器比例重算视口
Status: ready-for-agent
Status: resolved
## 问题
viewport 以等比 "contain" 映射到画布:单轴贴边、另一轴多露出世界,因此现在的负 padding 只在目标比例下成立;
在超宽屏(3440×1440)或竖屏(1080×1920)下会露出多余的世界或裁掉主体。
viewport 以等比 "contain" 映射到画布:单轴贴边、另一轴多露出世界。
原本的判断是"负 padding 只在目标比例下成立,其它比例会裁掉主体"——**实测证明这个判断是错的**,
真正的病根是另一件事。
## 步骤
## 诊断(实测,非推测)
1. 测出每档壁纸在 21:9 / 16:9 / 9:16 下的构图偏差(已有对拍矩阵)。
2. 按容器宽高比在运行时重算 pad(视口是活对象:原地改 pad 后调用 `player.setViewport(当前动画名)` 即生效,
整体替换 viewport 会丢 `viewport.animations` 并在 spine-player 第 14973 行崩溃)。
3. 目标:主体完整、底部对齐、无空边。
先量清楚事实,再改代码:
1. **contain 永远不会裁掉作者视口**。可见矩形是宽高比等于画布、且恰好含住作者视口 R 的最小矩形,
所以 R 在**任何**比例下都完整可见。比例不同只是"另一轴多露出世界":
- 21:9 → 6453×2701(竖轴贴边、横轴多露)
- 16:9 → 6050×3403
- 9:16 → 1914×3403(横轴贴边)
三种比例下 `coversView` 全为 true,"裁掉作者视口"这条假设不成立。
2. **这不是我重构引入的回归**。基线 `d8c7e49` 的 `preset-store.js` 里 xilian 的四个 pad
(-25% / -28% / -30% / -23%)与 kv37 的 `x: -1215, y: -410, w: 2048, h: 1024` 与现在一字不差;
基线的容器也是 `#spine-container` 绝对定位铺满、body flex 居中。取景语义未变。
3. **真正的病根:背景走 cover,立绘层走 contain,两者缩放分叉。**
`body { background-size: cover }` 会按需放大裁切,立绘层却按 contain 固定世界矩形。
以 1080×1920 竖屏为例,背景被放大约 1.78 倍,立绘层的世界高度却纹丝不动——
特效于是和背景插画脱节,"多余世界"其实看不太出来,脱节才看得出来。
4. **spine 资源路径是 `./effects/*.json`:立绘层是特效层,背景插画才是主体。**
所以判定标准不该是"特效不被裁切"(粒子飘出画面本来就正常),
而应是"特效与背景插画始终同倍率、同中心"。
## 做法
新增 `dist/scripts/viewport-fitter.js`(纯函数)与 `SpineController` 的取景维护:
- 参考比例 `16/9`:先让播放器自行解出作者视口 R,换算成参考比例下的可见矩形 V0。
**这个比例下与作者设定逐像素一致**。
- 其它比例:让立绘层的像素缩放**跟着背景的 cover 缩放走**——
`V.h = V0.h × coverScale(参考比例) / coverScale(当前比例)`,中心不变。
于是背景放大 1.78 倍时,特效也放大 1.78 倍。
- 应用方式:原地改写 `config.viewport` 的 x/y/width/height 与四个 pad,再调
`player.setViewport(动画名)`,并把 `viewportTransitionStart` 推到足够久以前(避免 0.25s 插值拖影)。
绝不整体替换 `config.viewport`:`setViewport()` 会无条件读 `config.viewport.animations[name]`,
换掉整个对象会在 spine-player 第 14973 行崩溃。
- 维护时机:挂在 `config.frame` 回调上(它在每帧相机计算**之前**被调用),以画布比例作键——
比例没变就是一次浮点比较后返回,比例变了就地重算。
`config.success` 用不了:它在 `setViewport` 之前触发,那时 `currentViewport` 还不存在。
- 预设可用 `framing: "author"` 退回作者原始的 contain 行为。
## 验收
- 三种比例下都对拍留档,主体不被裁切、底部不悬空。
- 切换窗口大小时不重建播放器(用 `setViewport`),连续 resize 无内存增长。
| 项目 | 结果 |
| --- | --- |
| 参考比例回归 | kv37 **逐像素 0 差异**;xilian 仅 1/255(浮点末位舍入) |
| 立绘/背景缩放同步 | 21:9 / 16:9 / 16:10 / 9:16 × 两个预设,**全部精确相等**(离线算式验证 + 渲染实测) |
| 渲染实测吻合预测 | 三种比例可见矩形与公式预测逐值一致(pads 全 0、base == resolved) |
| 对拍留档 | `tools/shots/fit/` 下 6 组(2 预设 × 3 比例)改动前后各一套(该目录按仓库约定不入库,可随时重跑重生成) |
| 不重建播放器 | 9 次改视口 + 连续 20 次压力往返,实例身份标记**从未丢失** |
| 连续 resize 内存 | 强制 GC 后 7.9 MB → 8.0 MB(增长 **0.04 MB**) |
| 回到 16:9 可逆 | 取景完全回到原值,无漂移 |
| 控制台 | 0 报错 / 0 未捕获异常 |
复现:`node .scratch/verify-fitter.mjs`(离线算式)、`node .scratch/test-resize.mjs`(resize 行为)。
## 附带修复
Chromium 会自动请求 `/favicon.ico` 并在控制台留下 404。已在 `dist/index.html` 加
`<link rel="icon" href="data:," />` 消除,使"0 console 报错"这条验收真正可达成。
@@ -1,17 +1,40 @@
# 05 WE 属性扩展:音源 combo、fps 限制
Status: ready-for-agent
Status: resolved
## 内容
1. **音源(音源作用域已定)**:新增 `project.json` combo `bgm`,列表是所有壁纸音源声明的**并集**(WE 的 combo 是静态列表,只能手工同步);
每档壁纸在自己 `preset.js` 的 `audioChoices` 里声明可选音源。切换壁纸时,若当前音源不属于新壁纸,回落"随预设"。
2. **fps 限制**:`properties.fps` 经 `applyGeneralProperties` 下发,WE 不会替壁纸限流,需自行实现。
实现方式:包裹实例上的 `player.drawFrame`(循环用箭头闭包懒查,因此可以门控);注意 `config.frame/update/draw`
都在下一帧排程之后运行,用它们限不了流。
3. `setPaused` 暂不实现(WE 会整体冻结进程);除非用户在 WE 里实测发现音频仍在响。
1. **音源**:`project.json` 新增 combo `bgm`,列表是所有壁纸音源声明的**并集**
(WE 的 combo 是静态列表,只能手工同步),另加一档「随预设」`auto`:
`auto` / `zaiduheni`「「再度和你」」/ `xilian`「昔涟」/ `pv37`「版本 PV」。
每档壁纸仍在自己 `preset.js` 的 `audioChoices` 里声明可选音源。
2. **fps 限制**:`properties.fps` 经 `applyGeneralProperties` 下发,WE 不会替壁纸限流,自行实现。
3. `setPaused` 不实现(WE 会整体冻结进程)。
## 实现要点
- **音源优先级**:用户自填 URL(`audio_file`)> `bgm` 选中的音源 > 本壁纸默认音源。
所选音源**只在本壁纸声明过时才生效**;不属于当前壁纸则音频回落本壁纸默认,
**选择本身保留**,切回那份壁纸时用户的选择还在。
- **门控绘制**:包裹实例上的 `drawFrame`。播放器循环写作
`requestAnimationFrame(() => this.drawFrame())`——箭头闭包在调用时才读 `this.drawFrame`,
所以在实例上换掉它就能接管排程。
- 原实现只在**真正绘制**时才排下一帧,而被限流丢掉的帧同样要排,否则循环停摆;
因此排程由包装层负责,再让原实现以 `requestNextFrame = false` 调用。
- **踩到的坑**:朴素地"距上一帧不足 `interval` 就丢"会把 rAF 抖动放大成整拍丢失——
目标 30fps 时落在 33.2ms 的那一帧被判为不足 33.33ms 而丢掉,实测只有 **22.5fps**。
改为"留 4ms 容差 + 到期时间按固定步长推进"后精确到 30.0。
- **另一个坑**:`if (properties.fps)` 的真值判断会把 `fps: 0`(取消限流)整个吞掉,
改判 `!== undefined`。
## 验收
- combo 切音源即时生效,且切壁纸时的回落行为正确。
- 设置 30/60 fps 时实际帧率符合,且不影响动画相位推进速度。
`node .scratch/test-props.mjs`:
| 项目 | 结果 |
| --- | --- |
| bgm 切音源即时生效 | ✓(10 项音源断言全过) |
| 跨壁纸回落 + 选择保留 | ✓ xilian 选「昔涟」→ 切 kv37 回落 pv37 → 切回 xilian 回落默认 |
| 自定义 URL 优先级最高且不被切壁纸清掉 | ✓ |
| 限 30 / 20 / 取消限流 | 实测 **30.0 / 20.0 / 60.0 fps** |
| 不影响动画相位推进速度 | 0.999 / 0.999 / 1.000 倍速(基准 1.000) |
@@ -1,10 +1,34 @@
# 06 打包 v3 并重新发布
Status: ready-for-agent
Status: resolved(第 4 步为人工步骤,待用户执行)
## 步骤
## 步骤与结果
1. `project.json`:`version` 升到 3,更新 `description`(提及新增音源切换等),核对 `properties` 与代码一致。
2. `preview.gif` 现在 160×160 / 50 帧 / 840 KB——合规(≤256×256、≤1 MB)但超过推荐的 500 KB,重新压缩。
3. 全量验收:0 死文件、≤35 MB、3 种比例 0 console 报错、预设往返不丢音源设置。
4. 上传到 Workshop(人工步骤,需要用户操作)。
1. **`project.json`**:`version` 升到 3;描述新增"可切换各预设自带的背景音乐""自适应窗口比例";
新增 `bgm` combo 与 `bgm_note`。核对:`preset` 的 combo 取值仍是 `xilian` / `kv37`
(用户已保存的设置依赖它,绝不能改)。**完成**。
2. **`preview.gif`**:原 160×160 / 50 帧 / 25fps / 2.0s / **821 KB**,超推荐值 500 KB。
重新压缩命令(结果可复现):
```powershell
ffmpeg -y -i dist/preview.gif -filter_complex `
"[0:v]fps=12.5,split[a][b];[a]palettegen=max_colors=128:stats_mode=full[p];[b][p]paletteuse=dither=none" `
-loop 0 .scratch/pv-I.gif
Copy-Item .scratch/pv-I.gif dist/preview.gif -Force
```
(**不能把输入输出写成同一个文件**,ffmpeg 会拒绝;必须先输出到临时文件再覆盖。)
即"每 2 帧取 1 帧 + 128 色 + 不抖动",**逐帧与源帧像素完全相同**(第 k 帧对原第 2k 帧,
抽查 0/6/12/18/24 帧全部 SSIM 1.0、max|diff| 0),只是时间采样率减半:
160×160 / 25 帧 / 12.5fps / 2.0s / **347 KB**。**完成**。
注:减色到 96/64/48 色收效甚微(604/519/474 KB)——体积由帧间变化量主导,不由调色板主导,
所以走帧采样率这条路更划算。
3. **全量验收**(`node .scratch/test-acceptance.mjs`):**全部通过**
- 总体积 **28.52 MB** / 34 个文件(≤ 35 MB)
- **0 死文件**
- `project.json` 解析正常、version 3、bgm 存在、preset 取值未变
- 21:9 / 16:9 / 9:16 三种比例:播放器就绪、可见矩形比例与画布一致、**0 控制台报错 / 0 异常**
- 预设往返 10 次:自定义音源与音量 0.2 均未丢失,仍在持续绘制,0 未捕获异常
4. **上传到 Workshop**:人工步骤,需要用户操作。
本次为破坏性较小的重构(16:9 逐像素不变),但 21:9 / 9:16 下构图按设计改变,建议在
超宽屏与竖屏各看一眼再发布。
+4 -4
View File
@@ -35,7 +35,7 @@
| --- | --- | --- |
| 01 | 资源按 游戏/壁纸 分层,预设拆进各自壁纸目录 | 完成(`09ff322`) |
| 02 | 体积:音频转 Opus + 图片无损 WebP(105.1 → 28.9 MB) | 完成 |
| 03 | 健壮性:初始化状态机、死代码、用户级覆盖语义 | 待做 |
| 04 | 比例适配:按容器比例重算视口 | 待做 |
| 05 | WE 属性扩展:音源 combo、fps 限制 | 待做 |
| 06 | 打包 v3 并重新发布 | 待做 |
| 03 | 健壮性:初始化状态机、死代码、用户级覆盖语义 | 完成(`4662856`) |
| 04 | 比例适配:立绘层取景跟随背景 cover 缩放 | 完成 |
| 05 | WE 属性扩展:音源 combo、fps 限制 | 完成 |
| 06 | 打包 v3 并重新发布 | 完成(上传为待人工执行) |