election-game/art/optimize-3d.mjs

99 lines
4.8 KiB
JavaScript
Raw Normal View History

選戰卡牌第五版:趕場、政見支票、資源瘦身、新主畫面圖示、修 Bug 資源與載入(docs/27 第 1 節):首頁下載 8.7 → 1.6 MB、載入畫面 4.4 → 1.5 秒,進一局 5.0 → 1.3 MB - 中文字型切成 unicode-range 小片,照畫面出現的頻率排(art/fonts/split-webfonts.py),拿掉 Google Fonts; canvas 上的字(3D 看板、名牌、分享圖)字型片載好再畫一次(ui/canvasFont.ts) - 3D 模型 meshopt 壓縮、只留用到的動作(art/optimize-3d.mjs、game/gltf.ts),5.5 → 1.0 MB - 卡圖 320 px 小圖+srcset(art/cards-small.sh);木紋貼圖縮小;背景音樂改 Opus 96 kbps(art/music-opus.sh) - 新增 GET /api/scenarios/list 只回大廳用到的欄位(1.52 → 0.44 MB);伺服器沒有這條路由時前端改抓舊的清單 玩法(docs/27 第 2–4 節,研究桌遊機制後挑兩個做): - 趕場(推運氣):每週可以翻牌庫頂的牌免費打,越翻越容易翻車(POST /api/rogue/runs/:id/overtime) - 政見支票(藏起來的長期目標):第 1 週開跑記者會三選一或不開,開票時兌現全市加票、跳票掉票 新主畫面圖示:重畫投票箱(art/icon/icon.svg、render-icons.sh),apple-touch 滿版不透明,加 Android maskable 修 Bug: - 舊版伺服器沒有新路由時,首頁、政治生涯的紅色「Not Found」改成照樣能用;版本對不上時寫中文說明 - 捏人物「存起來,去政治生涯」直接選好剛捏的角色、跳到選家鄉 - 政見支票:開票畫面的兌現與否和開票結果一致(照投票日的票數判定);跳過=不開;模擬玩家都不開 - 趕場翻到的免費牌只免費一次 - 劇本清單算錯一次後不會一直回錯誤 - 分享圖的標語、減少動態效果時的 3D 看板,字型晚到後重畫 - Safari 解不開 OGG 時改放 MP3 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:04:19 +00:00
// 3D 模型(web/public/assets/3d,Kenney CC0)壓小:首頁、政策島、政治生涯的小鎮一開始要下載 3 MB 多的模型。
// - 角色只留程式用到的動作(static、idle、emote-yes、jump;原本每個角色 32 段)
// - 拿掉用不到的頂點資料(沒有法線貼圖就不要切線、沒用第二組貼圖座標就不要 TEXCOORD_1)
// - 量化+meshopt 壓縮(EXT_meshopt_compression,前端 game/gltf.ts 用 three.js 附的 MeshoptDecoder 解)
// 貼圖維持外部檔(Textures/*.png,好幾個模型共用一張,瀏覽器只抓一次)。已經壓過的檔案會跳過。
//
// 用法:cd art && npm i --no-save @gltf-transform/core@4 @gltf-transform/extensions@4 @gltf-transform/functions@4 meshoptimizer@0.22 && node optimize-3d.mjs
import { readdirSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { NodeIO } from "@gltf-transform/core";
import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
import { dedup, meshopt, prune, resample } from "@gltf-transform/functions";
import { MeshoptDecoder, MeshoptEncoder } from "meshoptimizer";
const ROOT = process.env.MODELS_DIR ?? new URL("../web/public/assets/3d/", import.meta.url).pathname;
/** 程式用到的角色動作(hero3d、island3d、careerBoard3d、board3d/effects 的 findByName;static 是找不到時的預設) */
const KEEP_CLIPS = new Set(["static", "idle", "emote-yes", "jump"]);
await MeshoptEncoder.ready;
await MeshoptDecoder.ready;
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.encoder": MeshoptEncoder, "meshopt.decoder": MeshoptDecoder });
const files = readdirSync(ROOT, { recursive: true })
.map(String)
.filter((f) => f.endsWith(".glb"))
.sort();
let before = 0;
let after = 0;
for (const rel of files) {
const path = join(ROOT, rel);
const size = statSync(path).size;
const doc = await io.read(path);
const root = doc.getRoot();
if (root.listExtensionsUsed().some((e) => e.extensionName === "EXT_meshopt_compression")) {
console.log(`跳過(已經壓過)${rel}`);
continue;
}
if (rel.startsWith("characters/"))
for (const a of root.listAnimations()) {
if (KEEP_CLIPS.has(a.getName())) continue;
// 通道、取樣器要一起丟,不然它們還指著關鍵影格,prune 不會清掉
for (const c of a.listChannels()) c.dispose();
for (const s of a.listSamplers()) s.dispose();
a.dispose();
}
const usesNormalMap = root.listMaterials().some((m) => m.getNormalTexture());
const usesUv1 = root.listMaterials().some((m) => [m.getBaseColorTextureInfo(), m.getNormalTextureInfo(), m.getOcclusionTextureInfo(), m.getEmissiveTextureInfo(), m.getMetallicRoughnessTextureInfo()].some((t) => t && t.getTexCoord() === 1));
for (const mesh of root.listMeshes())
for (const prim of mesh.listPrimitives()) {
if (!usesNormalMap) prim.setAttribute("TANGENT", null);
if (!usesUv1) prim.setAttribute("TEXCOORD_1", null);
}
await doc.transform(dedup(), prune(), resample(), meshopt({ encoder: MeshoptEncoder, level: "medium" }));
writeFileSync(path, await writeKeepingTextures(doc));
const out = statSync(path).size;
before += size;
after += out;
console.log(`${rel}:${(size / 1024).toFixed(0)} → ${(out / 1024).toFixed(0)} KB`);
}
console.log(`合計 ${(before / 1024).toFixed(0)} → ${(after / 1024).toFixed(0)} KB`);
/**
* 寫成 .glb,但外部貼圖(Textures/*.png)維持外部檔:GLB 格式一定會把圖片嵌進去,
* 所以先換成 1 byte 的佔位圖,寫完再把 JSON 裡的圖片改回原本的檔名(佔位的 1 byte 留在檔案裡沒有用到)
*/
async function writeKeepingTextures(doc) {
const textures = doc.getRoot().listTextures();
const uris = textures.map((t) => t.getURI());
for (const [i, t] of textures.entries()) if (uris[i]) t.setImage(new Uint8Array([0]));
const glb = await io.writeBinary(doc);
const view = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
const jsonLength = view.getUint32(12, true);
const json = JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + jsonLength)));
for (const [i, uri] of uris.entries()) {
const image = json.images?.[i];
if (!uri || !image) continue;
delete image.bufferView;
delete image.mimeType;
image.uri = uri;
}
let text = JSON.stringify(json);
while (text.length % 4) text += " ";
const jsonBytes = new TextEncoder().encode(text);
const rest = glb.subarray(20 + jsonLength);
const out = new Uint8Array(20 + jsonBytes.length + rest.length);
const w = new DataView(out.buffer);
w.setUint32(0, 0x46546c67, true);
w.setUint32(4, 2, true);
w.setUint32(8, out.length, true);
w.setUint32(12, jsonBytes.length, true);
w.setUint32(16, 0x4e4f534a, true);
out.set(jsonBytes, 20);
out.set(rest, 20 + jsonBytes.length);
return out;
}