一、这份索引解决什么
前面 48 节各自给了公式、参数与一份可跑脚本,但它们散在 16 章里。这份附录做三件事:把公式与阈值汇成一张表,把工具链文件汇成一套命名约定,把六层复现命令汇成一段可以照着敲的清单。最后给出两段真跑的脚本——S 层清点器与 P 层校验内核——它们对同一份工作区算出的清单与摘要逐位一致,本身就是本卷「一处生成、多处消费」主张的一次小型演示。
二、卷一工具链命名约定
本卷工作区叫 prism,所有文件一律用 sp<章号>_ 前缀:
| 目录 | 命名 | 例 |
|---|---|---|
config/ | sp<章号>_<用途>.json | config/sp07_budget.json |
sim/ | sp<章号>_<用途>.py | sim/sp07_budget.py |
core/src/ | sp<章号>/<用途>.ts | core/src/sp07/budget.ts |
core/test/ | sp<章号>_<用途>.test.ts | core/test/sp07_budget.test.ts |
web/ | build_sp<章号>_<用途>.mjs / verify_sp<章号>_<用途>.mjs | web/build_sp09_nineslice.mjs |
唯一真源是 config/visual_spec.json,共享内核是 core/src/sp00/spec.ts;这两个文件不属于任何一章,任何章节的脚本都只读不写。
# 只跑第 7 章的测试(注意引号:让 node 自己展开 glob)
node --test 'core/test/sp07_*.test.ts'
# 跑本卷全部测试
node --test 'core/test/sp*.test.ts'
前缀不要写成裸 sp*:node --test 接收的是 glob 而非目录,写 core/test/sp*_*.test.ts 才只命中本卷。另外 web/ 层的章号不在文件名首位(build_sp09_…),清点脚本要同时认这两套命名。
三、环境速查
| 项 | 本机实测值 | 说明 |
|---|---|---|
| Python | /opt/homebrew/bin/python3 = 3.14.6 | S 层与 PIL 生成一律用它 |
| 系统 Python | /usr/bin/python3 = 3.9.6 | 无 numpy / pandas,只能跑最朴素的脚本 |
| numpy / pandas / Pillow | 2.5.1 / 3.0.3 / 12.3.0 | S 层与图像生成的依赖 |
| matplotlib / scipy / colour | 均未安装 | 图表纯 xml.etree 生成 SVG;色度与色盲矩阵手写 |
| Node | v26.5.0 | strip-only:禁 enum / namespace / 参数属性 / 装饰器 |
| tsc | 未安装 | P 层靠 Node 原生类型擦除,不做类型检查 |
| Playwright | 1.59.1(全局) | W 层需 NODE_PATH=/opt/homebrew/lib/node_modules + createRequire |
| DCC | 一个都没有 | Blender / Maya / 3ds Max / Substance / ZBrush 全部标 X |
四、六层可运行性口径与复现命令
| 层 | 复现命令 |
|---|---|
| S 仿真层 | /opt/homebrew/bin/python3 sim/sp<章号>_*.py(逐个跑,产出 JSON / CSV / SVG / PNG) |
| P 内核层 | node --test 'core/test/sp<章号>_*.test.ts'(必须写全 glob) |
| W 网页层 | node web/build_sp09_nineslice.mjs 产出 HTML,再 NODE_PATH=/opt/homebrew/lib/node_modules node web/verify_sp09_nineslice.mjs |
| D 静态层 | 无独立命令:schema 由 sim/ 与 core/ 同时读入并校验 |
| X 不可复现 | 无命令:正文每处显式标注「需真实环境,命令行不可复现」 |
| B 基准 | /opt/homebrew/bin/python3 sim/sp03_consistency_bench.py(软告警,不硬失败) |
for f in sim/sp*.py; do /opt/homebrew/bin/python3 "$f" || exit 1; done
五、全书公式与参数索引
整数类(跨语言逐位一致)
| 量 | 公式 | 出处 |
|---|---|---|
| 相对亮度(千分比整数) | L = (2126*R + 7152*G + 722*B) // 10000(R/G/B 为线性通道 ×1000) | 3.1 / 4.1 |
| WCAG 对比度(×10) | contrast10 = (Lmax + 500) * 10 // (Lmin + 500) | 3.1 / 4.3 / 9.3 |
| mip 链字节 | bytes = Σ ceil(w / 2^i) * ceil(h / 2^i) * bpp(i 从 0 到链底) | 8.1 |
| 显存总量 | vram = mipChainBytes * 格式乘数 // 1000 | 8.2 |
| 装箱率(千分比) | permille = placedArea * 1000 // atlasArea | 10.2 |
| 等距投影 | sx = (tx - ty) * (tileW // 2);sy = (tx + ty) * (tileH // 2) | 11.3 |
| 细节密度(千分比) | permille = edgePixels * 1000 // tilePixels | 11.2 |
| 轮廓紧凑度(千分比) | compact = 12566 * area // (perimeter * perimeter) | 11.1 |
| 加权评审分 | weighted = Σ score_i * weight_i(score 为 ×10 整数,weight 为整数) | 14.2 |
| 返工率(千分比) | permille = reworked * 1000 // total | 13.3 |
| 人天(×100) | mandays100 = Σ 工时 * 100 | 13.3 / 15.x |
| 预算余量 | slack = budget - actual(违例字符串 <类别>:OVER:<超出字节>) | 8.3 |
浮点类(跨语言容差内一致)
| 量 | 公式 | 声明容差 |
|---|---|---|
| sRGB → 线性 | c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4 | 相对误差 ≤ 1e-9 |
| 线性 → sRGB | 上式逆函数,同一组常数 | 相对误差 ≤ 1e-9 |
| OKLab | Ottosson 同一组矩阵常数(两次矩阵乘法 + 立方根) | 相对误差 ≤ 1e-9 |
| OKLCH | 由 OKLab 取 L / C = hypot(a,b) / H = atan2(b,a) | 相对误差 ≤ 1e-9 |
| 色盲模拟 | Brettel / Viénot–Mollon 1999 同一组矩阵,输出 8-bit 整数 | 通道差 ≤ 1 |
正文一律不写「三处颜色完全相同」,只写「容差内一致,实测最大偏差 N」。本卷实测的最大偏差量级为 1e-13,比声明容差 1e-9 小四个数量级——但那是实测结果,不是承诺。
六、S 层清点脚本:把这份索引重新跑出来
下面这段只登记本卷 sp 前缀的四个清单(config/ / sim/ / core/src/ / core/test/),按路径排序后逐个登记,算总数并给一个跨语言可复算的摘要。只登记静态文件路径,不登记产物(out/ 随时会被清空重建),所以同一份工作区在任何机器上跑出的清单与摘要都逐位一致:
#!/usr/bin/env python3
# file: sim/sp17_index.py
# tier: S
# verify: /opt/homebrew/bin/python3 sim/sp17_index.py
"""附录 A 的 S 层索引清点器:只登记**本卷 `sp` 前缀**的四个清单(config / sim / core/src /
core/test),按路径排序后逐个登记,算总数并给一个跨语言可复算的摘要(digest)。
只登记**静态文件路径**,不登记产物(out/ 下随时会被清空重建),所以同一份工作区在任何
机器上跑出的清单与摘要都逐位一致;前缀过滤让两卷的数字互不干扰。digest 用两个不同
偏移量的 FNV-1a 32 位拼成 16 位十六进制,TS 侧用 Math.imul 复算,故两侧必然相同。
"""
from __future__ import annotations
import json
import os
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GROUPS = (
("config", "config", lambda rp: rp.startswith("config/sp")),
("sim", "sim", lambda rp: rp.startswith("sim/sp")),
("coreSrc", "core/src", lambda rp: rp.startswith("core/src/sp")),
("coreTest", "core/test", lambda rp: rp.startswith("core/test/sp")),
)
def listing(rel: str, pred) -> list[str]:
d = os.path.join(ROOT, rel)
out: list[str] = []
for dirpath, _dirs, files in os.walk(d):
for n in files:
rp = os.path.relpath(os.path.join(dirpath, n), ROOT)
if pred(rp):
out.append(rp)
return sorted(out)
def fnv1a(text: str, basis: int) -> int:
h = basis
for ch in text.encode("utf-8"):
h = ((h ^ ch) * 0x01000193) & 0xFFFFFFFF
return h
def digest_of(lines: list[str]) -> str:
joined = "\n".join(lines)
return f"{fnv1a(joined, 0x811C9DC5):08x}{fnv1a(joined, 0x7FFFFFFF):08x}"
def main() -> int:
groups: dict[str, list[str]] = {}
all_lines: list[str] = []
for key, rel, pred in GROUPS:
files = listing(rel, pred)
groups[key] = files
all_lines.extend(files)
spec = json.load(open(os.path.join(ROOT, "config/visual_spec.json"), encoding="utf-8"))
report = {
"project": spec["project"],
"counts": {k: len(v) for k, v in groups.items()},
"total": len(all_lines),
"digest": digest_of(all_lines),
"groups": groups,
}
with open(os.path.join(ROOT, "out/sp17_index.json"), "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
f.write("\n")
print(f"project={report['project']} total={report['total']} digest={report['digest']}")
for k, _rel, _pred in GROUPS:
print(f" {k:<9} {report['counts'][k]:>3}")
print("wrote out/sp17_index.json")
return 0
if __name__ == "__main__":
sys.exit(main())
实跑 /opt/homebrew/bin/python3 sim/sp17_index.py(前缀过滤只认本卷 sp 文件,所以卷二、卷三落盘后这三个数字不会变):
project=stardust-inn total=197 digest=49f80669b540365b
config 50
sim 51
coreSrc 48
coreTest 48
wrote out/sp17_index.json
七、P 层索引校验内核:与 Python 侧逐位对拍
同一个摘要用 TypeScript 复算一遍。关键在两处:os.walk 的顺序不可依赖,所以两侧都先排序;JS 的 32 位乘法会丢精度,所以必须用 Math.imul:
// file: core/src/sp17/index.ts
// tier: P
// verify: node --test 'core/test/sp17_*.test.ts'
// 附录 A 的 P 层索引内核。与 sim/sp17_index.py 同一套规则:只登记本卷 `sp` 前缀的四个
// 清单,按路径排序后拼接,用两个不同偏移量的 FNV-1a 32 位拼成 16 位十六进制摘要。
// 只登记静态文件路径,不登记产物,故两侧清单与摘要必然逐位一致。只允许可擦除 TS 语法。
import { readdirSync, statSync } from "node:fs";
import { join, relative, sep } from "node:path";
const GROUPS: { key: string; rel: string; pred: (rp: string) => boolean }[] = [
{ key: "config", rel: "config", pred: (rp) => rp.startsWith("config/sp") },
{ key: "sim", rel: "sim", pred: (rp) => rp.startsWith("sim/sp") },
{ key: "coreSrc", rel: "core/src", pred: (rp) => rp.startsWith("core/src/sp") },
{ key: "coreTest", rel: "core/test", pred: (rp) => rp.startsWith("core/test/sp") },
];
export function listing(root: string, rel: string, pred: (rp: string) => boolean): string[] {
const out: string[] = [];
const walk = (abs: string) => {
for (const name of readdirSync(abs)) {
const full = join(abs, name);
const rp = relative(root, full).split(sep).join("/");
if (statSync(full).isDirectory()) walk(full);
else if (pred(rp)) out.push(rp);
}
};
walk(join(root, rel));
return out.sort();
}
export function fnv1a(text: string, basis: number): number {
let h = basis >>> 0;
const bytes = Buffer.from(text, "utf8");
for (const b of bytes) h = Math.imul(h ^ b, 0x01000193) >>> 0;
return h;
}
export function digestOf(lines: string[]): string {
const joined = lines.join("\n");
const a = fnv1a(joined, 0x811c9dc5).toString(16).padStart(8, "0");
const b = fnv1a(joined, 0x7fffffff).toString(16).padStart(8, "0");
return a + b;
}
export function indexWorkspace(root: string): { counts: Record<string, number>; total: number; digest: string; groups: Record<string, string[]> } {
const groups: Record<string, string[]> = {};
const counts: Record<string, number> = {};
const all: string[] = [];
for (const g of GROUPS) {
const files = listing(root, g.rel, g.pred);
groups[g.key] = files;
counts[g.key] = files.length;
all.push(...files);
}
return { counts, total: all.length, digest: digestOf(all), groups };
}
配套测试 core/test/sp17_index.test.ts 一边读 Python 落盘的 out/sp17_index.json 做跨语言对照,一边用内存清单构造两条负例(摘要必须内容敏感、空清单必须有确定值)。实跑 node --test 'core/test/sp17_*.test.ts':
✔ 索引清点:TS 复算与 Python 产物逐位一致 (18.670875ms)
✔ 正例:四个清单都非空,且 total 等于四者之和 (15.245083ms)
✔ 负例:摘要内容敏感,改一个字符必须换一个摘要 (0.115667ms)
✔ 负例:空清单有确定摘要,且与单元素清单不同 (0.072708ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
两侧的 total=197 与 digest=49f80669b540365b 一致——这就是本卷反复强调的那句话的一次最小演示:同一份输入,两套语言,一个结论。
八、一键复现与排错顺序(四步,不要跳步)
- 先跑环境自检:
/opt/homebrew/bin/python3 sim/sp00_env_check.py。它不通过,后面全是噪音。 - 再跑 S 层:
for f in sim/sp*.py; do /opt/homebrew/bin/python3 "$f" || exit 1; done。S 层失败通常是配置被改坏了,先看是哪一章的config/sp<章号>_*.json。 - 然后跑 P 层:
node --test 'core/test/sp*.test.ts'。P 层的跨语言对照失败几乎总是因为第 2 步没跑——它读的是 S 层落盘的 JSON。 - 最后跑 W 层与产物门禁:
node web/build_sp09_nineslice.mjs+verify_sp09_nineslice.mjs;先跑/opt/homebrew/bin/python3 sim/sp_gen_spec.py,让规范自己把色卡、图集与等距网格三张 PNG 造出来,再跑prism_rungen.py断言它们的尺寸、模式与颜色数符合 spec 声明。
三个最常见的坑:用了系统 python3(无 numpy,报 ModuleNotFoundError);没写全 glob(node --test core/test/ 找不到任何 .ts,静默 0 测试);只跑 P 层没跑 S 层(对照文件不存在,报 ENOENT)。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。