Files
occupancy-fitting/web/app.js
T
2026-11-25 23:11:00 +08:00

964 lines
28 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* global THREE, OCCUPANCY_DATA */
(function () {
"use strict";
const data = window.OCCUPANCY_DATA;
const $ = (id) => document.getElementById(id);
const fmtInt = new Intl.NumberFormat("en-US");
function showError(message) {
const el = $("error");
if (!el) return;
el.hidden = false;
el.innerHTML = message;
const loading = $("loading");
if (loading) loading.classList.add("hidden");
}
if (!data) {
showError(
"没有找到 <code>web/data.js</code>。<br>请先在项目根目录运行:" +
"<br><br><code>ven/bin/python src/inference.py</code><br><br>" +
"然后重新打开本页(或运行 <code>python src/serve.py</code>)。"
);
return;
}
const meta = data.meta;
const VREF = meta.volumeRefM3;
// ---------------------------------------------------------------- helpers
function b64bytes(b64) {
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
function decodeF32(b64) {
return new Float32Array(b64bytes(b64).buffer);
}
function decodeU32(b64) {
return new Uint32Array(b64bytes(b64).buffer);
}
function decodeU16(b64) {
return new Uint16Array(b64bytes(b64).buffer);
}
function clamp(v, lo, hi) {
return Math.max(lo, Math.min(hi, v));
}
function pct(v, digits) {
return (v * 100).toFixed(digits == null ? 1 : digits);
}
function signedPct(v, digits) {
const s = (v * 100).toFixed(digits == null ? 1 : digits);
return (v > 0 ? "+" : "") + s;
}
// ------------------------------------------------------------------ state
const defaultIndex = Math.max(
0,
data.sizes.findIndex((s) => s.sizeCm === meta.defaultSizeCm)
);
const state = {
sizeIndex: defaultIndex,
threshold: clamp(meta.defaultThresholdPct / 100, 0, 1),
cubeMode: "aabb",
showCar: true,
showVoxels: true,
showCube: true,
showGrid: true,
autoRotate: false,
viewMode: "car",
};
let current = null;
const sizeCache = new Map();
// ------------------------------------------------------------- size data
function getSizeData(index) {
if (sizeCache.has(index)) return sizeCache.get(index);
const sd = data.sizes[index];
const dims = sd.dims;
const indices = decodeU32(sd.indicesB64);
const rawFrac = decodeU16(sd.fractionsB64);
const n = indices.length;
// Sorting by fraction descending turns "fraction >= threshold" into a
// prefix of the instance buffer, so changing the threshold only needs
// `mesh.count = prefixLength` — no per-instance matrix update.
const order = new Array(n);
for (let i = 0; i < n; i++) order[i] = i;
order.sort((a, b) => rawFrac[b] - rawFrac[a]);
const positions = new Float32Array(n * 3);
const colors = new Float32Array(n * 3);
const fracs = new Uint16Array(n);
const origin = sd.originM;
const s = sd.sizeM;
const zmin = meta.bboxMinMm[2] / 1000;
const zmax = meta.bboxMaxMm[2] / 1000;
const zspan = Math.max(1e-6, zmax - zmin);
const col = new THREE.Color();
for (let q = 0; q < n; q++) {
const src = order[q];
const idx = indices[src];
const k = idx % dims[2];
const t = Math.floor(idx / dims[2]);
const j = t % dims[1];
const i = Math.floor(t / dims[1]);
const x = origin[0] + (i + 0.5) * s;
const y = origin[1] + (j + 0.5) * s;
const z = origin[2] + (k + 0.5) * s;
positions[q * 3] = x;
positions[q * 3 + 1] = y;
positions[q * 3 + 2] = z;
const h = clamp((z - zmin) / zspan, 0, 1);
col.setHSL(0.56 - 0.52 * h, 0.95, 0.5);
colors[q * 3] = col.r;
colors[q * 3 + 1] = col.g;
colors[q * 3 + 2] = col.b;
fracs[q] = rawFrac[src];
}
// Histograms: suffix sums give N(t) and sum(fraction) for any threshold.
const count = new Uint32Array(1001);
const sumFrac = new Float64Array(1001);
for (let q = 0; q < n; q++) {
const f = fracs[q];
count[f] += 1;
sumFrac[f] += f;
}
const nGe = new Float64Array(1001);
const fGe = new Float64Array(1001);
let nc = 0;
let fs = 0;
for (let f = 1000; f >= 0; f--) {
nc += count[f];
fs += sumFrac[f];
nGe[f] = nc;
fGe[f] = fs;
}
const obj = {
sd,
n,
positions,
colors,
fracs,
nGe,
fGe,
};
sizeCache.set(index, obj);
return obj;
}
// ------------------------------------------------------------- three.js
const viewport = $("viewport");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance",
});
} catch (err) {
showError("无法创建 WebGL 上下文:" + String(err));
return;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(viewport.clientWidth || 800, viewport.clientHeight || 600);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.toneMapping = THREE.NoToneMapping;
renderer.toneMappingExposure = 1.0;
renderer.domElement.style.zIndex = "0";
viewport.insertBefore(renderer.domElement, viewport.firstChild);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 38, 120);
const camera = new THREE.PerspectiveCamera(
42,
(viewport.clientWidth || 800) / (viewport.clientHeight || 600),
0.05,
250
);
camera.position.set(12, 8, 14);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.07;
controls.screenSpacePanning = true;
controls.minDistance = 1.6;
controls.maxDistance = 90;
controls.maxPolarAngle = Math.PI / 2 - 0.02;
controls.autoRotateSpeed = 0.7;
// Model coordinates are x = length, y = width, z = up. Rotate the whole
// model group so three.js' y axis becomes the car's height.
const modelRoot = new THREE.Group();
modelRoot.rotation.x = -Math.PI / 2;
scene.add(modelRoot);
// Lights
scene.add(new THREE.AmbientLight(0xb8d4f0, 0.18));
scene.add(new THREE.HemisphereLight(0xbfe6ff, 0x22130a, 0.28));
const key = new THREE.DirectionalLight(0xffffff, 0.65);
key.position.set(9, 13, 7);
scene.add(key);
const rim = new THREE.DirectionalLight(0x5ab8ff, 0.35);
rim.position.set(-10, 7, -9);
scene.add(rim);
const warm = new THREE.PointLight(0xffa04a, 0.25, 24);
warm.position.set(4.5, 3.5, 2);
scene.add(warm);
// Ground
const ground = new THREE.Mesh(
new THREE.CircleGeometry(9.5, 96),
new THREE.MeshBasicMaterial({
color: 0x050b13,
transparent: true,
opacity: 0.85,
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.012;
scene.add(ground);
const grid = new THREE.GridHelper(16, 32, 0x22405f, 0x102036);
grid.position.y = 0;
grid.material.transparent = true;
grid.material.opacity = 0.6;
scene.add(grid);
// Car mesh ------------------------------------------------------------
const carGeom = new THREE.BufferGeometry();
{
const pos = decodeF32(data.mesh.positionsB64);
const idx = decodeU32(data.mesh.indicesB64);
carGeom.setAttribute("position", new THREE.BufferAttribute(pos, 3));
carGeom.setIndex(new THREE.BufferAttribute(idx, 1));
carGeom.computeVertexNormals();
carGeom.computeBoundingSphere();
}
const carMat = new THREE.MeshPhysicalMaterial({
color: 0x4fb8e8,
metalness: 0.12,
roughness: 0.28,
clearcoat: 0.25,
clearcoatRoughness: 0.3,
transparent: true,
opacity: 0.2,
side: THREE.DoubleSide,
depthWrite: false,
depthTest: false,
emissive: 0x0a2a40,
emissiveIntensity: 0.6,
});
const carMesh = new THREE.Mesh(carGeom, carMat);
carMesh.renderOrder = 20;
modelRoot.add(carMesh);
// Bounding cubes ------------------------------------------------------
const axisCube = meta.axisCube;
const minCube = meta.minCube;
const uprightBox = meta.uprightBox || {
dims_m: meta.dimsM,
volume_m3: meta.dimsM[0] * meta.dimsM[1] * meta.dimsM[2],
center_m: [
(meta.bboxMinMm[0] + meta.bboxMaxMm[0]) / 2000,
(meta.bboxMinMm[1] + meta.bboxMaxMm[1]) / 2000,
(meta.bboxMinMm[2] + meta.bboxMaxMm[2]) / 2000,
],
rotation: null,
};
function makeEnvelopeGroup(center, dims, rotation, color, opacity) {
const group = new THREE.Group();
group.position.set(center[0], center[1], center[2]);
if (rotation) {
const R = rotation;
const m = new THREE.Matrix4().set(
R[0][0], R[0][1], R[0][2], 0,
R[1][0], R[1][1], R[1][2], 0,
R[2][0], R[2][1], R[2][2], 0,
0, 0, 0, 1
);
group.setRotationFromMatrix(m);
}
const geom = new THREE.BoxGeometry(dims[0], dims[1], dims[2]);
// Wireframe only: a translucent face filled the viewport and hid the car.
// depthTest=false keeps the envelope readable through the car/voxels.
const edgeMat = new THREE.LineBasicMaterial({
color: color,
transparent: true,
opacity: opacity,
depthWrite: false,
depthTest: false,
});
const edges = new THREE.LineSegments(new THREE.EdgesGeometry(geom), edgeMat);
edges.renderOrder = 30;
group.add(edges);
return group;
}
const axisGroup = makeEnvelopeGroup(
axisCube.center_m,
[axisCube.side_m, axisCube.side_m, axisCube.side_m],
null,
0xff9a3c,
0.9
);
const minGroup = makeEnvelopeGroup(
minCube.center_m,
[minCube.side_m, minCube.side_m, minCube.side_m],
minCube.rotation,
0xb388ff,
0.95
);
const boxGroup = makeEnvelopeGroup(
uprightBox.center_m,
uprightBox.dims_m,
null,
0x5dffb0,
0.95
);
modelRoot.add(axisGroup);
modelRoot.add(minGroup);
modelRoot.add(boxGroup);
// Voxel instancing ----------------------------------------------------
const boxGeom = new THREE.BoxGeometry(1, 1, 1, 1, 1, 1);
// three.js r128 only multiplies vColor into the fragment colour when
// USE_COLOR is defined (instanceColor alone is not enough). A white
// per-vertex colour attribute + vertexColors makes the per-instance colours
// visible without tinting the boxes.
{
const n = boxGeom.attributes.position.count;
const white = new Float32Array(n * 3);
white.fill(1);
boxGeom.setAttribute("color", new THREE.BufferAttribute(white, 3));
}
const voxelMat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.65,
metalness: 0.02,
transparent: false,
opacity: 1.0,
emissive: 0x000a12,
emissiveIntensity: 0.4,
});
let voxelMesh = null;
function rebuildVoxels(index) {
const obj = getSizeData(index);
if (voxelMesh) {
modelRoot.remove(voxelMesh);
voxelMesh = null;
}
const mesh = new THREE.InstancedMesh(boxGeom, voxelMat, obj.n);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
mesh.renderOrder = 10;
const m = new THREE.Matrix4();
const q = new THREE.Quaternion();
const pos = new THREE.Vector3();
const scale = new THREE.Vector3(
obj.sd.sizeM,
obj.sd.sizeM,
obj.sd.sizeM
);
for (let i = 0; i < obj.n; i++) {
pos.set(
obj.positions[i * 3],
obj.positions[i * 3 + 1],
obj.positions[i * 3 + 2]
);
m.compose(pos, q, scale);
mesh.setMatrixAt(i, m);
}
const col = new THREE.Color();
for (let i = 0; i < obj.n; i++) {
col.setRGB(
obj.colors[i * 3],
obj.colors[i * 3 + 1],
obj.colors[i * 3 + 2]
);
mesh.setColorAt(i, col);
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.count = obj.n;
modelRoot.add(mesh);
voxelMesh = mesh;
current = obj;
updateVisibility();
}
// ------------------------------------------------------------- metrics
function thresholdIndex() {
return clamp(Math.round(state.threshold * 1000), 0, 1000);
}
function currentEnvelope() {
if (state.cubeMode === "box") return uprightBox;
if (state.cubeMode === "min") return meta.minCube;
return meta.axisCube;
}
function envelopeDims(env) {
return env.dims_m || [env.side_m, env.side_m, env.side_m];
}
function metrics() {
if (!current) return null;
const t = thresholdIndex();
const n = current.nGe[t];
const sumFrac = current.fGe[t];
const cellVol = current.sd.sizeM ** 3;
const vFit = n * cellVol;
const vTrueIn = (sumFrac / 1000) * cellVol;
const env = currentEnvelope();
const envVol = env.volume_m3;
const envDims = envelopeDims(env);
const precision = vFit > 0 ? vTrueIn / vFit : 0;
const recall = vTrueIn / VREF;
const union = vFit + VREF - vTrueIn;
const iou = union > 0 ? vTrueIn / union : 0;
return {
n,
vFit,
vTrueIn,
precision,
recall,
iou,
error: (vFit - VREF) / VREF,
occupancy: vFit / envVol,
trueOccupancy: VREF / envVol,
envVol,
envDims,
cover: current.n,
};
}
function updateStats() {
const m = metrics();
if (!m) return;
$("vFit").textContent = m.vFit.toFixed(3);
const errEl = $("vErr");
errEl.textContent = signedPct(m.error, 1);
errEl.classList.remove("pos", "neg");
if (m.error > 0.001) errEl.classList.add("pos");
if (m.error < -0.001) errEl.classList.add("neg");
$("vCount").textContent = fmtInt.format(m.n);
$("vIou").textContent = m.iou.toFixed(3);
$("vPrec").textContent = pct(m.precision, 1) + "%";
$("vRec").textContent = pct(m.recall, 1) + "%";
$("vCubeSide").textContent = m.envDims.map((v) => v.toFixed(3)).join(" × ");
$("vCubeVol").textContent = m.envVol.toFixed(2);
$("vOcc").textContent = pct(m.occupancy, 2);
$("vTrueOcc").textContent = pct(m.trueOccupancy, 2);
$("vRef").textContent = VREF.toFixed(3);
$("vCad").textContent = meta.volumeCadSumM3.toFixed(3);
$("vCover").textContent = fmtInt.format(m.cover);
$("thrHint").textContent =
"保留占据概率 ≥ " + Math.round(state.threshold * 100) + "% 的立方体";
$("cubeHint").textContent =
state.cubeMode === "aabb"
? "轴对齐立方体;边长 = 车辆最大尺寸"
: state.cubeMode === "min"
? "旋转数值最优;含 20 mm 网格余量"
: "最小正置长方体;紧贴车辆轴对齐包围盒";
const envRows = [
["aabb", "立方体", meta.axisCube.volume_m3],
["min", "旋转最小", meta.minCube.volume_m3],
["box", "正置长方体", uprightBox.volume_m3],
];
$("envCompare").innerHTML = envRows
.map(([mode, label, vol]) => {
const on = state.cubeMode === mode ? "on" : "";
return `<div class="${on}"><span>${label}</span><b>${vol.toFixed(
2
)} m³</b><em>${pct(VREF / vol, 2)}%</em></div>`;
})
.join("");
const t = thresholdIndex();
if (voxelMesh) voxelMesh.count = current.nGe[t];
drawChart();
}
function updateVisibility() {
if (carMesh) carMesh.visible = state.showCar;
if (voxelMesh) {
voxelMesh.visible = state.showVoxels;
voxelMesh.count = current ? current.nGe[thresholdIndex()] : 0;
}
axisGroup.visible = state.showCube && state.cubeMode === "aabb";
minGroup.visible = state.showCube && state.cubeMode === "min";
boxGroup.visible = state.showCube && state.cubeMode === "box";
grid.visible = state.showGrid;
ground.visible = state.showGrid;
controls.autoRotate = state.autoRotate;
updateStats();
}
function applyCubeMode(mode) {
state.cubeMode = mode;
document.querySelectorAll("#cubeMode button").forEach((b) => {
b.classList.toggle("active", b.dataset.mode === mode);
});
updateVisibility();
}
// --------------------------------------------------------------- camera
function modelToWorld(v) {
return new THREE.Vector3(v[0], v[2], -v[1]);
}
const bmin = meta.bboxMinMm.map((v) => v / 1000);
const bmax = meta.bboxMaxMm.map((v) => v / 1000);
const carCenterModel = [
(bmin[0] + bmax[0]) / 2,
(bmin[1] + bmax[1]) / 2,
(bmin[2] + bmax[2]) / 2,
];
const carCenterWorld = modelToWorld(carCenterModel);
const carRadius =
0.5 *
Math.hypot(bmax[0] - bmin[0], bmax[1] - bmin[1], bmax[2] - bmin[2]);
function fitSphere(target, radius, dir, factor) {
const fov = (camera.fov * Math.PI) / 180;
const dist = (radius / Math.sin(fov / 2)) * (factor || 1.1);
camera.up.set(0, 1, 0);
camera.position.copy(target).addScaledVector(dir.clone().normalize(), dist);
controls.target.copy(target);
controls.update();
}
function fitView(mode) {
state.viewMode = mode;
document.querySelectorAll(".cam-buttons button").forEach((b) => {
b.classList.toggle("active", b.dataset.view === mode);
});
if (mode === "car") {
fitSphere(
carCenterWorld,
carRadius,
new THREE.Vector3(1.0, 0.55, 1.2),
1.18
);
} else if (mode === "cube") {
const env = currentEnvelope();
const c = modelToWorld(env.center_m);
const dims = envelopeDims(env);
fitSphere(
c,
0.5 * Math.hypot(dims[0], dims[1], dims[2]),
new THREE.Vector3(1.0, 0.58, 1.15),
1.02
);
} else {
const target = carCenterWorld.clone();
const dist = carRadius * 3.7;
camera.up.set(0, 1, 0);
camera.position.set(
target.x + dist * 0.16,
target.y + dist,
target.z + dist * 0.42
);
controls.target.copy(target);
controls.update();
}
}
// ---------------------------------------------------------------- chart
const chart = $("chart");
const chartTip = $("chartTip");
let chartGeom = null;
function resizeChart() {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const rect = chart.getBoundingClientRect();
chart.width = Math.max(10, Math.round(rect.width * dpr));
chart.height = Math.max(10, Math.round(rect.height * dpr));
const ctx = chart.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function niceStep(range) {
const raw = Math.max(1e-6, range / 4);
const mag = Math.pow(10, Math.floor(Math.log10(raw)));
const norm = raw / mag;
const step = norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 5 ? 5 : 10;
return step * mag;
}
function errorsForThreshold(t) {
return data.sizes.map((sd, i) => {
const obj = getSizeData(i);
const n = obj.nGe[t];
const v = n * sd.sizeM ** 3;
return ((v - VREF) / VREF) * 100;
});
}
function drawChart() {
const rect = chart.getBoundingClientRect();
const w = rect.width;
const h = rect.height;
if (w < 20 || h < 20) return;
const ctx = chart.getContext("2d");
ctx.clearRect(0, 0, w, h);
const t = thresholdIndex();
const errors = errorsForThreshold(t);
const n = errors.length;
const padL = 33;
const padR = 8;
const padT = 9;
const padB = 21;
const pw = Math.max(10, w - padL - padR);
const ph = Math.max(10, h - padT - padB);
let lo = Math.min(0, ...errors);
let hi = Math.max(0, ...errors);
if (hi - lo < 8) {
lo -= 4;
hi += 4;
}
lo -= Math.max(1.5, (hi - lo) * 0.08);
hi += Math.max(1.5, (hi - lo) * 0.08);
lo = clamp(lo, -110, 230);
hi = clamp(hi, -110, 230);
if (hi - lo < 4) hi = lo + 4;
const y = (v) => padT + ((hi - v) / (hi - lo)) * ph;
const x = (i) => padL + (n <= 1 ? 0 : (i / (n - 1)) * pw);
// horizontal grid + labels
ctx.font = "9px " + getComputedStyle(document.body).fontFamily;
ctx.textAlign = "right";
ctx.textBaseline = "middle";
const step = niceStep(hi - lo);
let tick = Math.ceil(lo / step) * step;
while (tick <= hi + 1e-9) {
const yy = y(tick);
ctx.strokeStyle = Math.abs(tick) < 1e-9 ? "rgba(110,140,175,0.35)" : "#122136";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padL, yy);
ctx.lineTo(w - padR, yy);
ctx.stroke();
ctx.fillStyle = Math.abs(tick) < 1e-9 ? "#7f95b3" : "#40546f";
const digits = step < 0.1 ? 2 : step < 1 ? 1 : 0;
ctx.fillText(
(tick > 0 ? "+" : "") + tick.toFixed(digits) + "%",
padL - 5,
yy
);
tick += step;
}
// filled area to zero
const y0 = y(0);
ctx.beginPath();
ctx.moveTo(x(0), y(errors[0]));
for (let i = 1; i < n; i++) ctx.lineTo(x(i), y(errors[i]));
ctx.lineTo(x(n - 1), y0);
ctx.lineTo(x(0), y0);
ctx.closePath();
const grad = ctx.createLinearGradient(0, padT, 0, padT + ph);
grad.addColorStop(0, "rgba(86,225,255,0.10)");
grad.addColorStop(0.5, "rgba(86,225,255,0.025)");
grad.addColorStop(1, "rgba(255,122,122,0.035)");
ctx.fillStyle = grad;
ctx.fill();
// line
ctx.beginPath();
ctx.moveTo(x(0), y(errors[0]));
for (let i = 1; i < n; i++) ctx.lineTo(x(i), y(errors[i]));
ctx.strokeStyle = "rgba(86,225,255,0.75)";
ctx.lineWidth = 1.6;
ctx.stroke();
// points
for (let i = 0; i < n; i++) {
const isCurrent = i === state.sizeIndex;
ctx.beginPath();
ctx.arc(x(i), y(errors[i]), isCurrent ? 4.2 : 2.2, 0, Math.PI * 2);
ctx.fillStyle = errors[i] >= 0 ? "#56e1ff" : "#ff9a62";
ctx.fill();
if (isCurrent) {
ctx.strokeStyle = "#eaf8ff";
ctx.lineWidth = 1.4;
ctx.stroke();
}
}
// current vertical marker
const cx = x(state.sizeIndex);
ctx.setLineDash([3, 3]);
ctx.strokeStyle = "rgba(180,220,255,0.25)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(cx, padT);
ctx.lineTo(cx, padT + ph);
ctx.stroke();
ctx.setLineDash([]);
// x labels
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.fillStyle = "#40546f";
const wanted = [4, 10, 20, 30, 40];
data.sizes.forEach((sd, i) => {
if (!wanted.includes(sd.sizeCm)) return;
ctx.fillText(sd.sizeCm === 40 ? "40cm" : String(sd.sizeCm), x(i), h - padB + 7);
});
// current value pill
const label = data.sizes[state.sizeIndex].sizeCm + "cm " + signedPct(errors[state.sizeIndex] / 100, 1) + "%";
ctx.font = "9px " + getComputedStyle(document.body).fontFamily;
const tw = ctx.measureText(label).width;
let lx = clamp(cx - tw / 2 - 5, 2, w - tw - 12);
const ly = padT + 1;
ctx.fillStyle = "rgba(7,14,26,0.9)";
ctx.strokeStyle = "#1b2a42";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.roundRect
? ctx.roundRect(lx, ly, tw + 10, 15, 4)
: ctx.rect(lx, ly, tw + 10, 15);
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#dcecff";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(label, lx + 5, ly + 8);
chartGeom = {
padL,
padR,
padT,
padB,
pw,
ph,
x,
y,
errors,
w,
h,
};
}
function chartIndexAt(clientX) {
if (!chartGeom) return null;
const rect = chart.getBoundingClientRect();
const local = clientX - rect.left;
if (local < chartGeom.padL - 4 || local > rect.width - chartGeom.padR + 4)
return null;
let best = 0;
let bestD = Infinity;
for (let i = 0; i < data.sizes.length; i++) {
const d = Math.abs(chartGeom.x(i) - local);
if (d < bestD) {
bestD = d;
best = i;
}
}
return best;
}
chart.addEventListener("mousemove", (e) => {
const i = chartIndexAt(e.clientX);
if (i == null) {
chartTip.style.opacity = "0";
return;
}
const obj = getSizeData(i);
const t = thresholdIndex();
const err =
((obj.nGe[t] * data.sizes[i].sizeM ** 3 - VREF) / VREF) * 100;
chartTip.textContent =
data.sizes[i].sizeCm +
" cm · " +
(err > 0 ? "+" : "") +
err.toFixed(1) +
"% · " +
fmtInt.format(obj.nGe[t]) +
" cubes";
chartTip.style.left = e.clientX + 12 + "px";
chartTip.style.top = e.clientY - 30 + "px";
chartTip.style.opacity = "1";
});
chart.addEventListener("mouseleave", () => {
chartTip.style.opacity = "0";
});
chart.addEventListener("click", (e) => {
const i = chartIndexAt(e.clientX);
if (i != null) setSizeIndex(i);
});
// ------------------------------------------------------------------- UI
const sizeInput = $("size");
sizeInput.min = "0";
sizeInput.max = String(data.sizes.length - 1);
sizeInput.value = String(state.sizeIndex);
$("sizeOut").textContent = data.sizes[state.sizeIndex].sizeCm + " cm";
const thresholdInput = $("threshold");
thresholdInput.value = String(Math.round(state.threshold * 100));
$("thrOut").textContent = Math.round(state.threshold * 100) + "%";
let sizeTimer = null;
function setSizeIndex(index) {
index = clamp(index, 0, data.sizes.length - 1);
state.sizeIndex = index;
sizeInput.value = String(index);
$("sizeOut").textContent = data.sizes[index].sizeCm + " cm";
rebuildVoxels(index);
drawChart();
}
function scheduleSize(index) {
state.sizeIndex = index;
$("sizeOut").textContent = data.sizes[index].sizeCm + " cm";
clearTimeout(sizeTimer);
sizeTimer = setTimeout(() => setSizeIndex(index), 55);
}
sizeInput.addEventListener("input", () => {
scheduleSize(parseInt(sizeInput.value, 10));
});
sizeInput.addEventListener("change", () => {
clearTimeout(sizeTimer);
setSizeIndex(parseInt(sizeInput.value, 10));
});
function setThreshold(percent) {
percent = clamp(percent, 0, 100);
state.threshold = percent / 100;
thresholdInput.value = String(percent);
$("thrOut").textContent = percent + "%";
updateVisibility();
}
thresholdInput.addEventListener("input", () => {
setThreshold(parseInt(thresholdInput.value, 10));
});
$("calibrate").addEventListener("click", () => {
if (!current) return;
const auto = Math.round(current.sd.autoThresholdPct);
setThreshold(auto);
$("thrHint").textContent = "体积校准:阈值 " + auto + "% ≈ 体积零误差";
});
$("resetView").addEventListener("click", () => fitView("car"));
$("cubeMode").addEventListener("click", (e) => {
const btn = e.target.closest("button");
if (btn) applyCubeMode(btn.dataset.mode);
});
document.querySelectorAll(".cam-buttons button").forEach((btn) => {
btn.addEventListener("click", () => fitView(btn.dataset.view));
});
$("showCar").addEventListener("change", (e) => {
state.showCar = e.target.checked;
updateVisibility();
});
$("showVoxels").addEventListener("change", (e) => {
state.showVoxels = e.target.checked;
updateVisibility();
});
$("showCube").addEventListener("change", (e) => {
state.showCube = e.target.checked;
updateVisibility();
});
$("showGrid").addEventListener("change", (e) => {
state.showGrid = e.target.checked;
grid.visible = state.showGrid;
ground.visible = state.showGrid;
});
$("autoRotate").addEventListener("change", (e) => {
state.autoRotate = e.target.checked;
controls.autoRotate = state.autoRotate;
});
window.addEventListener("resize", () => {
const w = viewport.clientWidth;
const h = viewport.clientHeight;
if (w < 2 || h < 2) return;
renderer.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
resizeChart();
drawChart();
});
if (window.ResizeObserver) {
const ro = new ResizeObserver(() => {
if (!viewport.clientWidth) return;
renderer.setSize(viewport.clientWidth, viewport.clientHeight);
camera.aspect = viewport.clientWidth / viewport.clientHeight;
camera.updateProjectionMatrix();
resizeChart();
drawChart();
});
ro.observe(viewport);
}
// --------------------------------------------------------------- startup
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
function boot() {
$("genAt").textContent = (meta.generatedAt || "").slice(0, 10);
rebuildVoxels(state.sizeIndex);
applyCubeMode(state.cubeMode);
fitView("car");
resizeChart();
updateStats();
setTimeout(() => {
$("loading").classList.add("hidden");
}, 160);
animate();
}
try {
boot();
} catch (err) {
console.error(err);
showError(
"构建场景失败:<br><code>" +
String(err && err.message ? err.message : err) +
"</code><br><br>请检查浏览器控制台,或运行 <code>python src/serve.py</code> 后通过 HTTP 打开。"
);
}
// Debug handle (handy from the console / automated screenshots).
window.__OCC_DEBUG = {
scene,
camera,
controls,
modelRoot,
carMesh,
axisGroup,
minGroup,
boxGroup,
get voxelMesh() {
return voxelMesh;
},
};
})();