feat(livestreamassist): add Chinese live dashboard with game icons

- Add a URL-driven Chinese overlay page rendering item rate tables,
  tech levels, current research, and Dyson sphere power for streams.
- Add the offline GameIcons layer and generate_icons.py, which extracts
  every item and tech icon from a local DSP install into
  js/generated/dsp-icons.js.
- Reuse the proto extraction in generate_text.py and cover the new
  page with test_dashboard.js.
This commit is contained in:
soarqin committed 2026-09-20 03:44:27 +08:00
1 parent 63a6a6ec6c
commit 3e3e995d55
12 files changed
+787 -15

No files matched your search

@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Extract DSP item and tech icons into LiveStreamAssist JS icon data."""
from __future__ import annotations
import argparse
import base64
import io
import json
import sys
from pathlib import Path
from generate_text import DEFAULT_UNITY_VERSION, extract_proto_map, find_game_root
ICON_CLASSES = ("ItemProtoSet", "TechProtoSet")
ICON_SIZE = 80
TEXTURE_FILES = ("resources.assets", "sharedassets0.assets")
def collect_icon_names(game_root: Path, unity_version: str) -> dict[str, dict[int, str]]:
"""Map item and tech IDs to the texture name from their IconPath field."""
names: dict[str, dict[int, str]] = {}
for kind, protos in extract_proto_map(game_root, unity_version, ICON_CLASSES).items():
mapping: dict[int, str] = {}
for proto_id, proto in protos.items():
icon_path = proto.get("IconPath")
if not icon_path:
continue
mapping[proto_id] = icon_path.split("/")[-1]
names[kind] = mapping
return {kind: mapping for kind, mapping in names.items() if mapping}
def load_icon_textures(data_dir: Path, names: set[str]) -> dict[str, object]:
"""Load the named textures, preferring the standard square icon size."""
import UnityPy
textures: dict[str, tuple[object, bool]] = {}
for filename in TEXTURE_FILES:
path = data_dir / filename
if not path.is_file():
continue
env = UnityPy.load(str(path))
for obj in env.objects:
if getattr(obj.type, "name", str(obj.type)) != "Texture2D":
continue
try:
data = obj.read()
except Exception:
continue
if data.m_Name not in names:
continue
square = data.m_Width == ICON_SIZE and data.m_Height == ICON_SIZE
existing = textures.get(data.m_Name)
if existing is None or (square and not existing[1]):
textures[data.m_Name] = (data, square)
return {name: value[0] for name, value in textures.items()}
def encode_icon(texture: object) -> str:
try:
image = texture.image
except ImportError as exc:
raise SystemExit(
"Pillow is required to encode icons. Install LiveStreamAssist/js/scripts/requirements.txt."
) from exc
if image.mode != "RGBA":
image = image.convert("RGBA")
buffer = io.BytesIO()
image.save(buffer, "PNG", optimize=True)
return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")
def build_payload(game_root: Path, unity_version: str) -> tuple[dict, list[str]]:
names = collect_icon_names(game_root, unity_version)
if not names.get("item") or not names.get("tech"):
raise SystemExit("Prototype extraction did not produce item and tech icons; generated data was not written.")
textures = load_icon_textures(game_root / "DSPGAME_Data", {name for mapping in names.values() for name in mapping.values()})
icons: dict[str, dict[str, str]] = {}
missing: list[str] = []
for kind, mapping in names.items():
icons[kind] = {}
for proto_id, texture_name in sorted(mapping.items()):
texture = textures.get(texture_name)
if texture is None:
missing.append(f"{kind} {proto_id} ({texture_name})")
continue
icons[kind][str(proto_id)] = encode_icon(texture)
return {"version": "1.0.0", "icons": icons}, missing
def emit_js(payload: dict) -> str:
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
return (
"/* Generated from a local Dyson Sphere Program install by generate_icons.py. Do not edit. */\n"
"globalThis.LiveStreamAssistIconData = "
+ body
+ ";\n"
)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--game-root", help="DSP install directory containing DSPGAME_Data")
parser.add_argument("--unity-version", default=DEFAULT_UNITY_VERSION)
parser.add_argument(
"--out",
default=str(Path(__file__).resolve().parents[1] / "generated" / "dsp-icons.js"),
help="Output JS path",
)
parser.add_argument("--json-out", help="Optional JSON output path")
args = parser.parse_args(argv)
game_root = find_game_root(args.game_root)
if game_root is None:
raise SystemExit("Dyson Sphere Program install not found. Pass --game-root.")
payload, missing = build_payload(game_root, args.unity_version)
for entry in missing:
print(f"Warning: icon texture not found for {entry}", file=sys.stderr)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(emit_js(payload), encoding="utf-8", newline="\n")
if args.json_out:
json_path = Path(args.json_out)
json_path.parent.mkdir(parents=True, exist_ok=True)
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n")
item_count = len(payload["icons"].get("item", {}))
tech_count = len(payload["icons"].get("tech", {}))
print(f"Wrote {out_path} (items={item_count}, techs={tech_count}, bytes={out_path.stat().st_size})")
return 0
if __name__ == "__main__":
sys.exit(main())
+23 -7
View File
@@ -249,7 +249,10 @@ def find_game_root(explicit: str | None) -> Path | None:
return None
def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str, str]]:
def extract_proto_map(
game_root: Path, unity_version: str, class_names: set[str] | None = None
) -> dict[str, dict[int, dict]]:
"""Extract prototype entries keyed by kind and ID, keeping the raw fields."""
try:
import UnityPy
from UnityPy.helpers.TypeTreeGenerator import TypeTreeGenerator
@@ -259,6 +262,7 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
"Install LiveStreamAssist/js/scripts/requirements.txt."
) from exc
wanted = class_names or KIND_FROM_SET
data_dir = game_root / "DSPGAME_Data"
generator = TypeTreeGenerator(unity_version)
generator.load_local_game(str(game_root))
@@ -269,15 +273,15 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
continue
script = obj.read()
class_name = getattr(script, "m_ClassName", "")
if class_name in KIND_FROM_SET:
if class_name in wanted:
script_ids[obj.path_id] = class_name
resources = UnityPy.load(str(data_dir / "resources.assets"))
nodes = {
class_name: generator.get_nodes_up("Assembly-CSharp.dll", class_name)
for class_name in KIND_FROM_SET
for class_name in wanted
}
ids: dict[str, dict[str, str]] = {kind: {} for kind in KIND_FROM_SET.values()}
protos: dict[str, dict[int, dict]] = {KIND_FROM_SET[cn]: {} for cn in wanted}
for obj in resources.objects:
if getattr(obj.type, "name", str(obj.type)) != "MonoBehaviour":
continue
@@ -293,10 +297,22 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
tree = obj.read_typetree(nodes[class_name], check_read=False)
for proto in tree.get("dataArray") or []:
proto_id = proto.get("ID")
name = proto.get("Name")
if not proto_id or not name:
if not proto_id:
continue
ids[kind][str(int(proto_id))] = name
protos[kind][int(proto_id)] = proto
return {kind: mapping for kind, mapping in protos.items() if mapping}
def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str, str]]:
ids: dict[str, dict[str, str]] = {}
for kind, protos in extract_proto_map(game_root, unity_version).items():
mapping: dict[str, str] = {}
for proto_id, proto in protos.items():
name = proto.get("Name")
if not name:
continue
mapping[str(proto_id)] = name
ids[kind] = mapping
return {kind: mapping for kind, mapping in ids.items() if mapping}
+1
View File
@@ -10,6 +10,7 @@ parts = [
SRC / "client.js",
SRC / "query.js",
SRC / "text.js",
SRC / "icons.js",
SRC / "footer.js",
]
text = "".join(path.read_text(encoding="utf-8") for path in parts)
@@ -0,0 +1,226 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const vm = require("node:vm");
const { ROOT, createHarness, flush } = require("./test_helpers");
const TEXT_DATA = {
languages: { "2052": { lcid: 2052, name: "简体中文", abbr: "zh-CN", abbr2: "zh" } },
ids: {
item: { 1101: "铁矿名", 1203: "电动机名" },
tech: { 1001: "电磁学名", 1002: "高效学名" }
},
strings: {
铁矿名: { "2052": "铁矿石" },
电动机名: { "2052": "电动机" },
电磁学名: { "2052": "电磁学" },
高效学名: { "2052": "高效采集" }
}
};
function createDocument() {
const byId = new Map();
const created = [];
function makeElement(tag) {
const element = {
tagName: String(tag).toUpperCase(), children: [], parentNode: null,
textContent: "", className: "", src: "", alt: "", hidden: false,
rowSpan: 0, style: {},
classList: {
set: new Set(),
add(token) { this.set.add(token); },
remove(token) { this.set.delete(token); },
toggle(token, force) {
const next = force == null ? !this.set.has(token) : !!force;
if (next) this.set.add(token); else this.set.delete(token);
return next;
},
contains(token) { return this.set.has(token); }
},
appendChild(child) { child.parentNode = element; element.children.push(child); return child; },
removeAttribute() {},
setAttribute(name, value) { element[name] = value; }
};
Object.defineProperty(element, "id", {
get() { return element._id || ""; },
set(value) { element._id = value; if (value) byId.set(value, element); }
});
created.push(element);
return element;
}
const body = makeElement("body");
return { created, byId, document: { createElement: makeElement, getElementById: id => byId.get(id) || null, body } };
}
function openDashboard(options = {}) {
const { context, clock } = createHarness();
const { created, byId, document } = createDocument();
const calls = [];
const clients = [];
const events = new Map();
const base = context.LiveStreamAssist;
class FakeClient {
constructor(settings) { this.url = settings.url; this.connections = []; clients.push(this); }
connect(url) {
if (url != null) this.url = url;
this.connections.push(url);
if (options.failFirst && this.connections.length === 1) return Promise.reject({ kind: "CONNECT_FAILED" });
return Promise.resolve(this);
}
close() { this.infoSnapshot = null; }
systemInfo() { this.infoSnapshot = {}; return Promise.resolve(this.infoSnapshot); }
validate() { return Promise.resolve({}); }
}
class FakeQuery {
getItemRates(ids, opts) {
calls.push(["rates", ids.slice(), opts]);
if (options.pendingRates) return options.pendingRates;
return Promise.resolve(ids.map(id => ({
itemId: id, perMinute: true, production: 3, consumption: 1,
theoreticalProduction: 4, theoreticalConsumption: 2
})));
}
getTechState(id) {
calls.push(["tech", id]);
const custom = options.techStates && options.techStates[id];
return Promise.resolve(custom || { techId: id, unlocked: false, curLevel: 2, maxLevel: 10 });
}
getCurrentResearch() {
calls.push(["research"]);
return Promise.resolve(options.research || {
active: true, techId: 1001, curLevel: 0, progressPercent: 42.5,
hashUploaded: "12345", hashNeeded: "67890"
});
}
getDysonPower() {
calls.push(["dyson"]);
return Promise.resolve({ watts: "60900000" });
}
}
context.LiveStreamAssist = Object.assign({}, base, {
Client: FakeClient,
GameQuery: FakeQuery,
GameText: { fromGenerated(settings) { return new base.GameText(TEXT_DATA, settings); } },
GameIcons: {
fromGenerated() {
return { itemIcon: id => "icon-item-" + id, techIcon: id => "icon-tech-" + id };
}
}
});
for (const id of ["panel", "status"]) {
const element = document.createElement("div");
element.id = id;
document.body.appendChild(element);
}
Object.assign(context, {
location: { search: options.search || "" },
URLSearchParams,
document,
console,
addEventListener(name, callback) { events.set(name, callback); }
});
const html = fs.readFileSync(path.join(ROOT, "..", "examples", "live-dashboard.html"), "utf8");
const scripts = [...html.matchAll(/<script(?:[^>]*)>([\s\S]*?)<\/script>/g)];
vm.runInContext(scripts.map(match => match[1]).join("\n"), context, { filename: "live-dashboard.html" });
return { clock, calls, clients, events, byId, created };
}
test("live-dashboard renders the requested sections", async () => {
const dashboard = openDashboard({ search: "?items=1101,1203&techs=1001,1002&research=1&dyson=1&lang=zh-CN" });
await flush();
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "3.00");
assert.equal(dashboard.byId.get("item-1101-prodRef").textContent, "4.00");
assert.equal(dashboard.byId.get("item-1101-cons").textContent, "1.00");
assert.equal(dashboard.byId.get("item-1101-consRef").textContent, "2.00");
assert.equal(dashboard.byId.get("item-1203-prod").textContent, "3.00");
assert.equal(dashboard.byId.get("tech-1001").textContent, "2/10");
assert.equal(dashboard.byId.get("tech-1002").textContent, "2/10");
assert.equal(dashboard.byId.get("researchName").textContent, "电磁学");
assert.equal(dashboard.byId.get("researchPct").textContent, "42.5%");
assert.equal(dashboard.byId.get("researchHash").textContent, "12.3k / 67.8k 哈希");
assert.equal(dashboard.byId.get("dysonWatts").textContent, "60.9MW");
assert.equal(dashboard.byId.get("status").textContent, "已连接");
assert.ok(dashboard.created.some(element => element.tagName === "IMG" && element.src === "icon-item-1101"));
assert.ok(dashboard.calls.some(([name, ids]) => name === "rates" && ids.join() === "1101,1203"));
});
test("live-dashboard defaults to research and Dyson sections", async () => {
const dashboard = openDashboard({});
await flush();
assert.equal(dashboard.byId.get("researchName").textContent, "电磁学");
assert.equal(dashboard.byId.get("dysonWatts").textContent, "60.9MW");
assert.ok(!dashboard.byId.has("item-1101-prod"));
assert.ok(!dashboard.byId.has("tech-1001"));
assert.ok(!dashboard.calls.some(([name]) => name === "rates" || name === "tech"));
});
test("live-dashboard shows a repeatable and a one-time tech level", async () => {
const dashboard = openDashboard({
search: "?techs=1001,1002",
techStates: {
1001: { techId: 1001, unlocked: false, curLevel: 5, maxLevel: 20 },
1002: { techId: 1002, unlocked: true, curLevel: 0, maxLevel: 0 }
}
});
await flush();
assert.equal(dashboard.byId.get("tech-1001").textContent, "5/20");
assert.equal(dashboard.byId.get("tech-1002").textContent, "已解锁");
});
test("live-dashboard resumes polling after the first connection fails", async () => {
const dashboard = openDashboard({ search: "?items=1101", failFirst: true });
await flush();
assert.equal(dashboard.calls.length, 0);
dashboard.clock.advance(2000);
await flush();
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "3.00");
assert.equal(dashboard.byId.get("status").textContent, "已连接");
});
test("live-dashboard does not overlap slow polls", async () => {
let finish;
const pending = new Promise(resolve => { finish = resolve; });
const dashboard = openDashboard({ search: "?items=1101", pendingRates: pending });
await flush();
dashboard.clock.advance(10000);
await flush();
assert.equal(dashboard.calls.length, 1);
finish([{ itemId: 1101, perMinute: true, production: 6, consumption: 2, theoreticalProduction: 8, theoreticalConsumption: 4 }]);
await flush();
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "6.00");
dashboard.clock.advance(2000);
await flush();
assert.equal(dashboard.calls.length, 2);
});
test("live-dashboard stops polling on pagehide", async () => {
const dashboard = openDashboard({ search: "?research=1" });
await flush();
assert.equal(typeof dashboard.events.get("pagehide"), "function");
dashboard.events.get("pagehide")();
dashboard.clock.advance(20000);
await flush();
assert.equal(dashboard.calls.length, 1);
assert.equal(dashboard.clock.size, 0);
});
test("live-dashboard reports initialization errors without polling", async () => {
for (const search of ["?window=5min&research=1", "?techs=abc", "?items=1101&techs=0"]) {
const dashboard = openDashboard({ search });
await flush();
assert.match(dashboard.byId.get("status").textContent, /初始化失败/);
assert.equal(dashboard.calls.length, 0);
dashboard.clock.advance(10000);
await flush();
assert.equal(dashboard.calls.length, 0);
}
});
test("live-dashboard can disable the default sections explicitly", async () => {
const dashboard = openDashboard({ search: "?research=0" });
await flush();
assert.ok(!dashboard.byId.has("researchName"));
assert.ok(!dashboard.byId.has("dysonWatts"));
assert.equal(dashboard.byId.get("status").textContent, "已连接");
});
+1 -1
View File
@@ -6,7 +6,7 @@ const vm = require("node:vm");
const { ROOT, createHarness } = require("./test_helpers");
test("the packed script matches its sources", () => {
const names = ["header", "format", "client", "query", "text", "footer"];
const names = ["header", "format", "client", "query", "text", "icons", "footer"];
const sources = names.map(name => fs.readFileSync(path.join(ROOT, "src", name + ".js"), "utf8").replace(/\r\n/g, "\n")).join("");
const packed = fs.readFileSync(path.join(ROOT, "livestream-assist.js"), "utf8").replace(/\r\n/g, "\n");
assert.ok(packed === sources, "The bundle is stale; run python LiveStreamAssist/js/scripts/pack_js.py.");