fix: enforce complete building and offline viewer gates

This commit is contained in:
2026-07-10 14:04:10 +08:00
parent cab4d320c0
commit a761175c09
13 changed files with 401 additions and 25 deletions

View File

@@ -568,6 +568,7 @@ def evaluate_gates(
}
)
gates.append(frame_ledger_gate(config, frames))
gates.append(vertical_storey_continuity_gate(spec))
gates.append(declared_area_gate(spec, config))
gates.append(storey_count_gate(spec, config))
return gates
@@ -681,6 +682,60 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
}
def vertical_storey_continuity_gate(spec: dict[str, Any]) -> dict[str, Any]:
"""A final full-building model may not jump from F2 directly to F16.
Representative typical-floor drawings are source evidence, not permission
to leave the repeated storeys absent from the delivered building. The
repeated floors must be instantiated and labelled as derived repetitions.
"""
import re as _re
numbered: list[tuple[int, str, dict[str, Any]]] = []
for key, floor in spec.get("floors", {}).items():
match = _re.fullmatch(r"F(\d+)", str(key))
if match:
numbered.append((int(match.group(1)), str(key), floor))
numbered.sort()
if len(numbered) < 2:
return {
"name": "vertical_storey_continuity",
"status": "PASS",
"detail": f"{len(numbered)} numbered storey; no internal continuity gap to test.",
}
missing: list[str] = []
z_gaps: list[str] = []
for (left_no, left_key, left), (right_no, right_key, right) in zip(numbered, numbered[1:]):
if right_no != left_no + 1:
missing.append(f"{left_key}->{right_key}")
continue
left_z = float(left.get("z", 0.0))
right_z = float(right.get("z", 0.0))
nominal = max(float(left.get("height", 0.0)), float(right.get("height", 0.0)), 1.0)
if right_z - left_z > max(8.0, nominal * 2.0):
z_gaps.append(f"{left_key}->{right_key}={round(right_z - left_z, 2)}m")
if missing or z_gaps:
parts = []
if missing:
parts.append("missing numbered ranges " + ", ".join(missing))
if z_gaps:
parts.append("unexplained elevation gaps " + ", ".join(z_gaps))
return {
"name": "vertical_storey_continuity",
"status": "FAIL",
"detail": (
"; ".join(parts)
+ ". Instantiate source-supported repeated typical floors; do not deliver separated floor islands."
),
}
return {
"name": "vertical_storey_continuity",
"status": "PASS",
"detail": f"Numbered storeys are contiguous from {numbered[0][1]} to {numbered[-1][1]}.",
}
def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""Above-ground storey count must match the declared count (总图 22F 标签 / 标高梯级数).

View File

@@ -914,9 +914,12 @@ def main() -> int:
blend_path = out_dir / f"{args.name}.blend"
glb_path = out_dir / f"{args.name}.glb"
raw_glb_path = out_dir / f"{args.name}.raw.glb"
png_path = out_dir / f"{args.name}.png"
metadata_path = out_dir / "model_metadata.json"
bpy.ops.wm.save_as_mainfile(filepath=str(blend_path))
# Retain a decoder-free GLB for the self-contained r147 offline viewer.
bpy.ops.export_scene.gltf(filepath=str(raw_glb_path), export_format="GLB")
# Draco compression keeps the Web GLB lightweight (typically -85~92% size).
# The Web template registers a DRACOLoader to decode it; keep both in sync.
bpy.ops.export_scene.gltf(
@@ -939,6 +942,7 @@ def main() -> int:
{
"blend": str(blend_path),
"glb": str(glb_path),
"raw_glb": str(raw_glb_path),
"png": str(png_path),
"metadata": str(metadata_path),
"objects": len(bpy.data.objects),

View File

@@ -254,6 +254,24 @@ def run_browser_smoke(pipeline: Pipeline, web_dir: Path, report: Path, screensho
server.wait(timeout=5)
def run_offline_browser_smoke(pipeline: Pipeline, viewer: Path, report: Path, screenshot: Path) -> None:
"""Open the single-file viewer through file:// and prove that its model renders."""
pipeline.run(
"offline_browser_smoke",
[
"node",
str(SCRIPTS / "offline_viewer_smoke.mjs"),
"--viewer",
str(viewer),
"--out",
str(report),
"--screenshot",
str(screenshot),
],
[report, screenshot],
)
def doctor() -> int:
modules = ["ezdxf", "jsonschema", "numpy", "scipy", "shapely", "trimesh", "matplotlib", "PIL", "pygltflib"]
checks = []
@@ -457,7 +475,11 @@ def run_pipeline(args: argparse.Namespace) -> int:
standard = bundle / "variants" / "standard" / "standard.glb"
offline = out_dir / "viewer.html"
offline_browser_report = out_dir / "offline_browser_smoke_report.json"
if args.offline:
offline_source = standard.with_name("standard.raw.glb")
if not offline_source.exists():
offline_source = standard
pipeline.run(
"offline",
python_script(
@@ -465,7 +487,7 @@ def run_pipeline(args: argparse.Namespace) -> int:
"--spec",
str(spec),
"--glb",
str(standard),
str(offline_source),
"--out",
str(offline),
"--title",
@@ -473,6 +495,23 @@ def run_pipeline(args: argparse.Namespace) -> int:
),
[offline],
)
if not args.web:
pipeline.run(
"offline_node_dependencies",
["npm", "install", "--prefix", str(ROOT), "--ignore-scripts"],
[ROOT / "node_modules" / "playwright" / "package.json"],
)
pipeline.run(
"offline_browser_runtime",
[str(ROOT / "node_modules" / ".bin" / "playwright"), "install", "chromium"],
[],
)
run_offline_browser_smoke(
pipeline,
offline,
offline_browser_report,
out_dir / "offline_browser_smoke.png",
)
preview = out_dir / "verify_previews.png"
pipeline.run(
@@ -514,7 +553,14 @@ def run_pipeline(args: argparse.Namespace) -> int:
["--web-dir", str(web_dir), "--browser-report", str(browser_report), "--require-browser-report"]
)
if args.offline:
verify_cmd.extend(["--offline-viewer", str(offline)])
verify_cmd.extend(
[
"--offline-viewer",
str(offline),
"--offline-browser-report",
str(offline_browser_report),
]
)
if args.require_browser_report and not args.web:
verify_cmd.append("--require-browser-report")
if args.scope_manifest:
@@ -560,7 +606,11 @@ def parser() -> argparse.ArgumentParser:
run.add_argument("--offline", action="store_true")
run.add_argument("--browser-report")
run.add_argument("--require-browser-report", action="store_true")
run.add_argument("--scope-manifest", help="Single-building/campus scope ledger included in final verification")
run.add_argument(
"--scope-manifest",
required=True,
help="Required single-building/campus scope ledger included in final verification",
)
run.add_argument(
"--waiver",
action="append",

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env node
/** Prove that the self-contained offline viewer loads from file:// in Chromium. */
import fs from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
function arg(name, fallback = null) {
const index = process.argv.indexOf(name);
return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback;
}
const viewer = arg("--viewer");
const out = arg("--out", "offline_browser_smoke_report.json");
const screenshot = arg("--screenshot", "offline_browser_smoke.png");
if (!viewer) {
throw new Error("Usage: offline_viewer_smoke.mjs --viewer viewer.html --out report.json --screenshot smoke.png");
}
let chromium;
try {
({ chromium } = await import("playwright"));
} catch (error) {
throw new Error("Missing Playwright. Install dependencies and Chromium before running this smoke test.", {
cause: error,
});
}
await fs.mkdir(path.dirname(out), { recursive: true });
await fs.mkdir(path.dirname(screenshot), { recursive: true });
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
const checks = [];
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText || "failed"}`));
try {
const url = pathToFileURL(path.resolve(viewer)).href;
await page.goto(url, { waitUntil: "load", timeout: 60000 });
await page.waitForFunction(
() => window.__offlineReady || document.getElementById("load")?.textContent?.includes("加载失败"),
null,
{ timeout: 60000 },
);
const state = await page.evaluate(() => ({
viewport: { width: window.innerWidth, height: window.innerHeight },
ready: window.__offlineReady || null,
loadText: document.getElementById("load")?.textContent || "",
canvas: Boolean(document.querySelector("canvas")),
renders: window.__renders || 0,
}));
const viewportPass = state.viewport.width === 1440 && state.viewport.height === 900;
checks.push({
name: "offline:viewport",
status: viewportPass ? "PASS" : "FAIL",
detail: `${state.viewport.width}x${state.viewport.height} expected 1440x900`,
});
checks.push({
name: "offline:model-ready",
status: state.ready?.meshes > 0 && !state.loadText ? "PASS" : "FAIL",
detail: state.ready ? `${state.ready.meshes} mesh(es)` : state.loadText || "readiness marker missing",
});
checks.push({ name: "offline:canvas", status: state.canvas ? "PASS" : "FAIL" });
checks.push({
name: "offline:render",
status: state.renders > 0 ? "PASS" : "FAIL",
detail: `${state.renders} render(s)`,
});
await page.screenshot({ path: screenshot, fullPage: true });
} catch (error) {
checks.push({ name: "offline:load", status: "FAIL", detail: error.message });
await page.screenshot({ path: screenshot, fullPage: true }).catch(() => {});
} finally {
await page.close();
await browser.close();
}
const failedChecks = checks.filter((item) => item.status === "FAIL");
const status = failedChecks.length || consoleErrors.length || pageErrors.length || failedRequests.length ? "FAIL" : "PASS";
const report = {
status,
detail: `${checks.length - failedChecks.length}/${checks.length} checks passed`,
viewer: path.resolve(viewer),
checks,
console_errors: consoleErrors,
page_errors: pageErrors,
failed_requests: failedRequests,
};
await fs.writeFile(out, JSON.stringify(report, null, 2));
process.stdout.write(`${JSON.stringify({ status, report: out })}\n`);
if (status === "FAIL") process.exitCode = 3;

View File

@@ -201,7 +201,7 @@ def inspect_offline(path: Path, checks: list[dict[str, Any]]) -> None:
add_check(checks, "offline:payload", "FAIL", f"Embedded payload decode failed: {exc}")
def inspect_browser_report(path: Path, checks: list[dict[str, Any]]) -> None:
def inspect_browser_report(path: Path, checks: list[dict[str, Any]], name: str = "browser:smoke") -> None:
try:
report = json.loads(path.read_text(encoding="utf-8"))
passed = (
@@ -211,9 +211,9 @@ def inspect_browser_report(path: Path, checks: list[dict[str, Any]]) -> None:
and not report.get("failed_requests")
)
detail = report.get("detail") or json.dumps(report, ensure_ascii=False)[:500]
add_check(checks, "browser:smoke", "PASS" if passed else "FAIL", detail)
add_check(checks, name, "PASS" if passed else "FAIL", detail)
except Exception as exc:
add_check(checks, "browser:smoke", "FAIL", f"Browser report invalid: {exc}")
add_check(checks, name, "FAIL", f"Browser report invalid: {exc}")
def inspect_audit(path: Path, checks: list[dict[str, Any]]) -> None:
@@ -350,6 +350,7 @@ def main() -> int:
parser.add_argument("--variants-manifest")
parser.add_argument("--web-dir")
parser.add_argument("--offline-viewer")
parser.add_argument("--offline-browser-report")
parser.add_argument("--render", nargs="*", default=[])
parser.add_argument("--audit")
parser.add_argument("--scope-manifest")
@@ -443,6 +444,15 @@ def main() -> int:
inspect_scope(Path(args.scope_manifest), checks)
if args.offline_viewer:
inspect_offline(Path(args.offline_viewer), checks)
if args.offline_browser_report:
inspect_browser_report(Path(args.offline_browser_report), checks, "offline:browser-smoke")
else:
add_check(
checks,
"offline:browser-smoke",
"SKIP",
"Offline viewer has no real file:// browser smoke report",
)
if args.browser_report:
inspect_browser_report(Path(args.browser_report), checks)
elif args.web_dir or args.require_browser_report:
@@ -460,6 +470,7 @@ def main() -> int:
"evidence_version": 1,
"generated_at": datetime.now(timezone.utc).isoformat(),
"status": status,
"waivers": [{"check": name, "reason": reason} for name, reason in sorted(waivers.items())],
"checks": checks,
"artifacts": artifacts,
}

View File

@@ -27,6 +27,7 @@ import argparse
import base64
import gzip
import json
import struct
from pathlib import Path
import showcase_schema
@@ -53,6 +54,18 @@ def group_of(key: str) -> str:
return "主体"
def glb_extensions(path: Path) -> set[str]:
"""Return extensionsUsed from the GLB JSON chunk without extra dependencies."""
data = path.read_bytes()
if len(data) < 20 or data[:4] != b"glTF":
raise SystemExit(f"Not a valid GLB: {path}")
chunk_length, chunk_type = struct.unpack_from("<II", data, 12)
if chunk_type != 0x4E4F534A or 20 + chunk_length > len(data):
raise SystemExit(f"GLB JSON chunk is missing or truncated: {path}")
document = json.loads(data[20 : 20 + chunk_length].decode("utf-8").rstrip("\x00 \t\r\n"))
return set(document.get("extensionsUsed", []))
MAIN_JS = r"""
(async function(){
const $load = document.getElementById('load');
@@ -119,6 +132,7 @@ MAIN_JS = r"""
}
if (cat === 'trees') o.visible = false;
});
window.__offlineReady = {meshes:nodes.length};
if (TREES.length) {
const ti = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.14,0.2,1.4,6),
new THREE.MeshStandardMaterial({color:0x6b4a2e, roughness:0.9}), TREES.length);
@@ -212,6 +226,12 @@ def main() -> int:
glb_path = Path(args.glb)
if not glb_path.exists() or glb_path.stat().st_size == 0:
raise SystemExit(f"GLB not found or empty: {glb_path}")
extensions = glb_extensions(glb_path)
if "KHR_draco_mesh_compression" in extensions:
raise SystemExit(
"Offline single-file viewer requires an uncompressed GLB; "
f"KHR_draco_mesh_compression found in {glb_path}. Pass the matching *.raw.glb instead."
)
spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)