Files
occupancy-fitting/preview/index.html
T

2821 lines
3.3 MiB
HTML
Raw Normal View History

2026-11-28 21:35:06 +08:00
<!-- offline preview generated by src/build_preview.py; do not edit this file by hand -->
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Occupancy Fitting · AURORA A1</title>
<style>
/* style.css inlined */
:root {
--bg: #060a12;
--panel: #0a111e;
--panel-2: #0d1627;
--line: #1b2a42;
--line-soft: #142033;
--text: #e7f1ff;
--muted: #7f95b3;
--faint: #4d6380;
--cyan: #56e1ff;
--cyan-dim: #2b8ca8;
--amber: #ffb45a;
--green: #6df5b1;
--red: #ff7a7a;
--violet: #b991ff;
--mono: "SFMono-Regular", "Cascadia Code", "Roboto Mono", Consolas, monospace;
--sans: "Inter", "Segoe UI", "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", system-ui, -apple-system, sans-serif;
}
* { box-sizing: border-box; }
html, body {
height: 100%;
margin: 0;
background: var(--bg);
color: var(--text);
font-family: var(--sans);
-webkit-font-smoothing: antialiased;
}
body { overflow: hidden; }
#app {
display: grid;
grid-template-columns: 392px minmax(0, 1fr);
height: 100vh;
width: 100vw;
}
/* ------------------------------------------------------------------ panel */
#panel {
position: relative;
z-index: 2;
overflow-y: auto;
overflow-x: hidden;
padding: 22px 22px 18px;
background:
radial-gradient(1200px 400px at -20% -10%, rgba(86, 225, 255, 0.08), transparent 55%),
linear-gradient(180deg, #0b1424 0%, var(--panel) 35%, #080e19 100%);
border-right: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #20344f transparent;
}
#panel::-webkit-scrollbar { width: 8px; }
#panel::-webkit-scrollbar-thumb { background: #20344f; border-radius: 4px; }
#panel::-webkit-scrollbar-track { background: transparent; }
.brand { padding-bottom: 18px; }
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.18em;
font-weight: 600;
text-transform: uppercase;
}
.eyebrow .dot {
width: 6px; height: 6px; border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px var(--green);
}
h1 {
margin: 12px 0 10px;
font-family: "Arial Narrow", "Helvetica Neue", var(--sans);
font-size: 42px;
line-height: 0.92;
letter-spacing: 0.02em;
font-weight: 800;
}
h1 span { color: var(--cyan); }
.sub {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.block {
padding: 16px 0;
border-top: 1px solid var(--line-soft);
}
.block-title {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 11px;
letter-spacing: 0.13em;
text-transform: uppercase;
color: var(--muted);
font-weight: 700;
margin-bottom: 12px;
}
.block-title .live {
font-family: var(--mono);
font-size: 9px;
color: var(--green);
border: 1px solid rgba(109, 245, 177, 0.3);
border-radius: 20px;
padding: 2px 7px;
letter-spacing: 0.12em;
}
.block-title .sub2 {
font-size: 9px;
color: var(--faint);
letter-spacing: 0.05em;
text-transform: none;
}
/* ---------------------------------------------------------------- controls */
.label-row {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 8px;
}
.label-row.second { margin-top: 18px; }
.label-row label { color: var(--muted); font-size: 12px; }
.label-row output {
font-family: var(--mono);
font-size: 20px;
color: var(--cyan);
font-weight: 600;
letter-spacing: -0.02em;
}
input[type="range"] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 4px;
border-radius: 4px;
background: linear-gradient(90deg, var(--cyan-dim), #1d3550);
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 15px; height: 15px;
border-radius: 50%;
background: var(--cyan);
border: 3px solid #06101d;
box-shadow: 0 0 0 1px var(--cyan), 0 0 14px rgba(86, 225, 255, 0.55);
}
input[type="range"]::-moz-range-thumb {
width: 15px; height: 15px;
border-radius: 50%;
background: var(--cyan);
border: 3px solid #06101d;
box-shadow: 0 0 0 1px var(--cyan);
}
input[type="range"]::-moz-range-track {
height: 4px; border-radius: 4px;
background: linear-gradient(90deg, var(--cyan-dim), #1d3550);
}
.hint {
margin-top: 8px;
color: var(--faint);
font-size: 10.5px;
line-height: 1.5;
}
.button-row { display: flex; gap: 8px; margin-top: 14px; }
button {
font-family: var(--sans);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.04em;
border-radius: 7px;
padding: 9px 13px;
cursor: pointer;
border: 1px solid var(--line);
background: #0d1728;
color: var(--text);
transition: border-color 120ms ease, background 120ms ease, color 120ms ease;
}
button:hover { border-color: var(--cyan-dim); }
button.primary {
flex: 1;
background: linear-gradient(180deg, rgba(86, 225, 255, 0.16), rgba(86, 225, 255, 0.06));
border-color: rgba(86, 225, 255, 0.4);
color: var(--cyan);
}
button.primary:hover { background: rgba(86, 225, 255, 0.18); }
button.ghost { flex: 1; color: var(--muted); }
/* ------------------------------------------------------------------- stats */
.metric {
display: flex;
align-items: baseline;
gap: 6px;
margin: 6px 0;
}
.metric .k {
flex: 1;
color: var(--muted);
font-size: 11px;
}
.metric .v {
font-family: var(--mono);
font-size: 18px;
font-weight: 600;
color: var(--text);
letter-spacing: -0.02em;
}
.metric.big .v { font-size: 27px; color: var(--cyan); }
.metric.big:nth-of-type(2) .v { color: var(--amber); }
.metric .v.small { font-size: 14px; }
.metric .u { color: var(--faint); font-size: 10px; font-family: var(--mono); }
.metric.big:nth-of-type(2) .v.neg { color: var(--red); }
.metric.big:nth-of-type(2) .v.pos { color: var(--green); }
.grid2 {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.mini {
background: rgba(12, 23, 40, 0.75);
border: 1px solid var(--line-soft);
border-radius: 7px;
padding: 8px 9px;
}
.mini .k {
display: block;
color: var(--faint);
font-size: 9.5px;
letter-spacing: 0.04em;
margin-bottom: 3px;
}
.mini b {
font-family: var(--mono);
font-size: 14px;
font-weight: 600;
color: var(--text);
}
.divider {
height: 1px;
background: var(--line-soft);
margin: 13px 0 10px;
}
.segmented {
display: flex;
gap: 0;
margin-top: 14px;
border: 1px solid var(--line);
border-radius: 7px;
overflow: hidden;
}
.segmented button {
flex: 1;
border: 0;
border-radius: 0;
background: transparent;
color: var(--faint);
padding: 8px 6px;
font-size: 10px;
}
.segmented button.active {
background: rgba(255, 180, 90, 0.12);
color: var(--amber);
box-shadow: inset 0 -2px 0 var(--amber);
}
.ref-row {
display: flex;
align-items: baseline;
gap: 6px;
font-size: 10.5px;
color: var(--muted);
margin: 5px 0;
}
.ref-row b {
margin-left: auto;
font-family: var(--mono);
font-weight: 500;
color: #b9cce4;
}
.ref-row span:last-child { color: var(--faint); font-family: var(--mono); font-size: 9px; }
.ref-note {
margin-top: 9px;
color: var(--faint);
font-size: 10px;
line-height: 1.55;
}
/* ------------------------------------------------------------------- chart */
.chart-block { padding-bottom: 8px; }
.chart-wrap { position: relative; width: 100%; height: 158px; }
#chart { width: 100%; height: 100%; display: block; cursor: crosshair; }
.chart-legend {
display: flex;
justify-content: flex-end;
gap: 12px;
font-family: var(--mono);
font-size: 9px;
color: var(--faint);
padding-top: 2px;
}
.chart-legend .pos { color: var(--cyan-dim); }
.chart-legend .neg { color: #b06a4a; }
.chart-tip {
position: fixed;
z-index: 20;
pointer-events: none;
padding: 5px 8px;
border-radius: 5px;
border: 1px solid var(--line);
background: #0b1525;
color: var(--text);
font-family: var(--mono);
font-size: 10px;
opacity: 0;
transition: opacity 80ms ease;
white-space: nowrap;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
}
/* ----------------------------------------------------------------- toggles */
.toggles {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 10px;
}
.switch {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 10.5px;
cursor: pointer;
user-select: none;
}
.switch input {
appearance: none;
-webkit-appearance: none;
width: 26px; height: 14px;
border-radius: 10px;
background: #16253b;
border: 1px solid #233a58;
position: relative;
cursor: pointer;
transition: background 120ms ease;
flex: none;
}
.switch input::after {
content: "";
position: absolute;
width: 8px; height: 8px;
top: 2px; left: 2px;
border-radius: 50%;
background: #7085a0;
transition: transform 120ms ease, background 120ms ease;
}
.switch input:checked { background: rgba(86, 225, 255, 0.2); border-color: rgba(86, 225, 255, 0.45); }
.switch input:checked::after { transform: translateX(12px); background: var(--cyan); }
/* ------------------------------------------------------------------ method */
.method {
border-top: 1px solid var(--line-soft);
padding: 14px 0 8px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.65;
}
.method summary {
color: var(--faint);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
outline: none;
list-style: none;
}
.method summary::-webkit-details-marker { display: none; }
.method summary::before { content: "+ "; color: var(--cyan-dim); }
.method[open] summary::before { content: "- "; }
.method p { margin: 10px 0 0; }
.method .formula {
font-family: var(--mono);
font-size: 10px;
color: #a9c1dc;
background: #08101d;
border: 1px solid var(--line-soft);
border-radius: 6px;
padding: 9px 10px;
line-height: 1.8;
}
.foot {
display: flex;
justify-content: space-between;
gap: 8px;
padding-top: 13px;
border-top: 1px solid var(--line-soft);
color: #41546d;
font-size: 8.5px;
font-family: var(--mono);
line-height: 1.5;
}
/* ---------------------------------------------------------------- viewport */
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(ellipse at 50% 38%, rgba(31, 67, 105, 0.24), transparent 58%),
linear-gradient(180deg, #07111f 0%, #05090f 70%);
}
#viewport canvas { position: absolute; inset: 0; display: block; }
.viewport-toolbar {
position: absolute;
z-index: 5;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.cam-buttons {
display: flex;
gap: 4px;
padding: 4px;
border-radius: 9px;
border: 1px solid rgba(45, 70, 100, 0.6);
background: rgba(7, 14, 26, 0.72);
backdrop-filter: blur(10px);
pointer-events: auto;
}
.cam-buttons button {
border: 0;
background: transparent;
color: var(--faint);
padding: 6px 10px;
font-size: 10px;
}
.cam-buttons button.active { color: var(--cyan); background: rgba(86, 225, 255, 0.1); }
.cam-buttons button:hover { color: var(--text); }
.legend {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 10px;
border-radius: 8px;
border: 1px solid rgba(45, 70, 100, 0.55);
background: rgba(7, 14, 26, 0.65);
backdrop-filter: blur(10px);
pointer-events: auto;
}
.legend-label, .legend-ends { font-size: 8.5px; color: var(--faint); font-family: var(--mono); }
.legend-bar {
width: 74px; height: 6px; border-radius: 4px;
background: linear-gradient(90deg, #2f9dff, #5dffd0 35%, #ffe36b 65%, #ff8c42);
box-shadow: 0 0 12px rgba(86, 225, 255, 0.25);
}
.viewport-hint {
position: absolute;
z-index: 4;
left: 22px;
bottom: 16px;
color: #3d516b;
font-size: 9.5px;
letter-spacing: 0.04em;
pointer-events: none;
}
.loading {
position: absolute;
z-index: 10;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: var(--cyan-dim);
font-family: var(--mono);
font-size: 12px;
background: rgba(5, 9, 15, 0.7);
transition: opacity 250ms ease;
}
.loading.hidden { opacity: 0; pointer-events: none; }
.error {
position: absolute;
z-index: 11;
inset: 28px;
display: flex;
align-items: center;
justify-content: center;
padding: 30px;
border: 1px solid rgba(255, 122, 122, 0.35);
border-radius: 12px;
background: rgba(30, 8, 12, 0.9);
color: #ffb0b0;
font-size: 13px;
line-height: 1.7;
text-align: center;
}
/* ---------------------------------------------------------------- responsive */
@media (max-width: 920px) {
body { overflow: auto; }
#app {
grid-template-columns: 1fr;
grid-template-rows: auto minmax(420px, 58vh);
height: auto;
min-height: 100vh;
}
#panel {
max-height: none;
border-right: 0;
border-bottom: 1px solid var(--line);
padding: 18px 16px;
}
h1 { font-size: 34px; }
#viewport { min-height: 58vh; }
.viewport-toolbar { top: 12px; left: 12px; right: 12px; }
.legend { display: none; }
}
/* The [hidden] UA rule is overridden by .error { display:flex }; make it explicit. */
.error[hidden] { display: none; }
.method .source {
color: #526987;
font-size: 9.5px;
}
.method .source a {
color: var(--cyan-dim);
text-decoration: none;
border-bottom: 1px dotted rgba(86, 225, 255, 0.25);
}
.method .source a:hover { color: var(--cyan); }
/* envelope comparison (cube / rotated cube / upright cuboid) */
.env-compare {
margin-top: 9px;
padding: 7px 9px;
border: 1px solid var(--line-soft);
border-radius: 6px;
background: rgba(8, 17, 30, 0.75);
font-family: var(--mono);
font-size: 9px;
line-height: 1.55;
color: var(--faint);
}
.env-compare div {
display: flex;
align-items: baseline;
gap: 6px;
}
.env-compare span { flex: 1; }
.env-compare b { font-weight: 500; color: #b9cce4; }
.env-compare em {
font-style: normal;
color: var(--faint);
width: 52px;
text-align: right;
}
.env-compare div.on span,
.env-compare div.on b,
.env-compare div.on em { color: var(--green); }
/* ------------------------------------------------------------------ page tabs */
.page-tabs {
display: flex;
gap: 5px;
margin: 0 0 16px;
}
.page-tabs a {
flex: 1;
padding: 7px 8px;
text-align: center;
font-size: 10.5px;
letter-spacing: 0.08em;
color: var(--muted);
text-decoration: none;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(8, 15, 26, 0.6);
transition: color 0.15s, border-color 0.15s;
}
.page-tabs a:hover {
color: var(--text);
border-color: var(--cyan-dim);
}
.page-tabs a.active {
color: #04121a;
font-weight: 700;
border-color: transparent;
background: linear-gradient(180deg, #8beaff, #4fd3f2);
}
</style>
</head>
<body>
<div id="app">
<aside id="panel">
<nav class="page-tabs">
<a class="active" href="index.html">占用拟合</a>
<a href="packing.html">装箱模拟</a>
</nav>
<header class="brand">
<div class="eyebrow"><span class="dot"></span> OCP · STEP → VOXEL</div>
<h1>OCCUPANCY<br /><span>FITTING</span></h1>
<p class="sub">用可调立方体逼近一辆 F1 概念车<br />FSD 占用网络 · 可解释沙盒</p>
</header>
<section class="block controls">
<div class="label-row">
<label for="size">立方体边长</label>
<output id="sizeOut">8 cm</output>
</div>
<input id="size" type="range" min="0" max="0" step="1" value="0" />
<div class="label-row second">
<label for="threshold">占据阈值</label>
<output id="thrOut">30%</output>
</div>
<input id="threshold" type="range" min="0" max="100" step="1" value="30" />
<div class="hint" id="thrHint">概率 ≥ 30% 的体素被保留</div>
<div class="button-row">
<button id="calibrate" class="primary" title="把阈值设为当前边长下体积最接近真实值的水平">体积校准</button>
<button id="resetView" class="ghost">重置视角</button>
</div>
</section>
<section class="block chart-block">
<div class="block-title"><span>体积差异 vs 边长</span><span class="sub2">点击折线切换</span></div>
<div class="chart-wrap">
<canvas id="chart"></canvas>
<div class="chart-tip" id="chartTip"></div>
</div>
<div class="chart-legend"><span class="pos">偏大</span><span class="zero">0</span><span class="neg">偏小</span></div>
</section>
<section class="block stats">
<div class="block-title"><span>推理结果</span><span class="live">LIVE</span></div>
<div class="metric big">
<span class="k">拟合体积</span>
<span class="v" id="vFit">—</span><span class="u">m³</span>
</div>
<div class="metric big">
<span class="k">体积差异</span>
<span class="v" id="vErr">—</span><span class="u">%</span>
</div>
<div class="grid2">
<div class="mini"><span class="k">立方体数量</span><b id="vCount">—</b></div>
<div class="mini"><span class="k">IoU</span><b id="vIou">—</b></div>
<div class="mini"><span class="k">精确率</span><b id="vPrec">—</b></div>
<div class="mini"><span class="k">召回率</span><b id="vRec">—</b></div>
</div>
<div class="divider"></div>
<div class="metric">
<span class="k">包络尺寸</span>
<span class="v small" id="vCubeSide">—</span><span class="u">m</span>
</div>
<div class="metric">
<span class="k">立方体体积</span>
<span class="v small" id="vCubeVol">—</span><span class="u">m³</span>
</div>
<div class="metric">
<span class="k">拟合占用度</span>
<span class="v small" id="vOcc">—</span><span class="u">%</span>
</div>
<div class="metric">
<span class="k">真实占用度</span>
<span class="v small" id="vTrueOcc">—</span><span class="u">%</span>
</div>
<div class="segmented" id="cubeMode" role="group" aria-label="包络体类型">
<button data-mode="aabb" class="active">标准立方体</button>
<button data-mode="min">数学最小</button>
<button data-mode="box">最小长方体</button>
</div>
<div class="hint" id="cubeHint">轴对齐立方体;边长 = 车辆最大尺寸</div>
<div class="env-compare" id="envCompare">—</div>
<div class="divider"></div>
<div class="ref-row"><span>真实体积参考</span><b id="vRef">—</b><span>m³</span></div>
<div class="ref-row"><span>CAD 实体体积和</span><b id="vCad">—</b><span>m³</span></div>
<div class="ref-row"><span>候选体素(覆盖)</span><b id="vCover">—</b></div>
<div class="ref-note">参考体积为 4 mm 并集体素;CAD 体积和包含零件重叠,故更大。</div>
</section>
<section class="block toggles">
<label class="switch"><input type="checkbox" id="showCar" checked /><span>半透明车辆</span></label>
<label class="switch"><input type="checkbox" id="showVoxels" checked /><span>立方体拟合</span></label>
<label class="switch"><input type="checkbox" id="showCube" checked /><span>包络立方体</span></label>
<label class="switch"><input type="checkbox" id="showGrid" checked /><span>地面网格</span></label>
<label class="switch"><input type="checkbox" id="autoRotate" /><span>自动旋转</span></label>
</section>
<details class="method">
<summary>方法与 FSD 占用网络类比</summary>
<p>
STEP 通过 OCP 读取并精确计算 B-Rep 体积,再网格化为 90,964 个三角形。
对每个实体分别沿 Y 轴做射线奇偶填充,得到 4 mm 精细占据栅格;
再聚合成 4–40 cm 的立方体,每个立方体带有 0–100% 的占据概率。
</p>
<p>
这与 FSD 类占用网络的关键表示一致:3D voxel grid + occupancy
probability + 阈值化。区别是这里用 CAD 真值代替摄像头感知,因此可以
精确量化体积误差、IoU、精确率与召回率。
</p>
<p class="formula">
V_fit = N · s³ &nbsp;&nbsp;|&nbsp;&nbsp;
error = (V_fit − V_ref) / V_ref<br />
occupancy = V_fit / S_cube³
</p>
<p class="source">
模型来源:
<a href="https://github.com/Sunwood-ai-labs/aurora-a1-freecad" target="_blank" rel="noreferrer">Sunwood-ai-labs / aurora-a1-freecad</a>
· 仅用于本地研究与演示
</p>
</details>
<footer class="foot">
<div>AURORA A1 · 130 solids · 2.059 m³ CAD</div>
<div>OCP 8.0 · three.js · <span id="genAt">—</span></div>
</footer>
</aside>
<main id="viewport">
<div class="viewport-toolbar">
<div class="cam-buttons">
<button data-view="car" class="active">车辆视角</button>
<button data-view="cube">立方体视角</button>
<button data-view="top">俯视</button>
</div>
<div class="legend">
<span class="legend-label">高度</span>
<span class="legend-bar"></span>
<span class="legend-ends">低 / 高</span>
</div>
</div>
<div class="viewport-hint">拖动旋转 · 滚轮缩放 · 右键平移</div>
<div class="loading" id="loading">正在装配场景…</div>
<div class="error" id="error" hidden></div>
</main>
</div>
<script>
/* three.js r128 inlined by build_preview.py */
/**
* @license
* Copyright 2010-2021 Three.js Authors
* SPDX-License-Identifier: MIT
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).THREE={})}(this,(function(t){"use strict";const e="128",n=100,i=300,r=301,s=302,a=303,o=304,l=306,c=307,h=1e3,u=1001,d=1002,p=1003,m=1004,f=1005,g=1006,v=1007,y=1008,x=1009,_=1012,w=1014,b=1015,M=1016,S=1020,T=1022,E=1023,A=1026,L=1027,R=33776,C=33777,P=33778,D=33779,I=35840,N=35841,B=35842,z=35843,F=37492,O=37496,H=2300,G=2301,U=2302,k=2400,V=2401,W=2402,j=2500,q=2501,X=3e3,Y=3001,Z=3007,J=3002,Q=3004,K=3005,$=3006,tt=7680,et=35044,nt=35048,it="300 es";class rt{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e<i;e++)n[e].call(this,t);t.target=null}}}const st=[];for(let t=0;t<256;t++)st[t]=(t<16?"0":"")+t.toString(16);let at=1234567;const ot=Math.PI/180,lt=180/Math.PI;function ct(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(st[255&t]+st[t>>8&255]+st[t>>16&255]+st[t>>24&255]+"-"+st[255&e]+st[e>>8&255]+"-"+st[e>>16&15|64]+st[e>>24&255]+"-"+st[63&n|128]+st[n>>8&255]+"-"+st[n>>16&255]+st[n>>24&255]+st[255&i]+st[i>>8&255]+st[i>>16&255]+st[i>>24&255]).toUpperCase()}function ht(t,e,n){return Math.max(e,Math.min(n,t))}function ut(t,e){return(t%e+e)%e}function dt(t,e,n){return(1-n)*t+n*e}function pt(t){return 0==(t&t-1)&&0!==t}function mt(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function ft(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}var gt=Object.freeze({__proto__:null,DEG2RAD:ot,RAD2DEG:lt,generateUUID:ct,clamp:ht,euclideanModulo:ut,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:dt,damp:function(t,e,n,i){return dt(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(ut(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){return void 0!==t&&(at=t%2147483647),at=16807*at%2147483647,(at-1)/2147483646},degToRad:function(t){return t*ot},radToDeg:function(t){return t*lt},isPowerOfTwo:pt,ceilPowerOfTwo:mt,floorPowerOfTwo:ft,setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}});class vt{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(thi
</script>
<script>
/* OrbitControls inlined by build_preview.py */
( function () {
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
//
// Orbit - left mouse / touch: one-finger move
// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
const _changeEvent = {
type: 'change'
};
const _startEvent = {
type: 'start'
};
const _endEvent = {
type: 'end'
};
class OrbitControls extends THREE.EventDispatcher {
constructor( object, domElement ) {
super();
if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' );
if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
this.object = object;
this.domElement = domElement; // Set to false to disable this control
this.enabled = true; // "target" sets the location of focus, where the object orbits around
this.target = new THREE.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
this.minDistance = 0;
this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
this.minZoom = 0;
this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
// Range is 0 to Math.PI radians.
this.minPolarAngle = 0; // radians
this.maxPolarAngle = Math.PI; // radians
// How far you can orbit horizontally, upper and lower limits.
// If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
this.minAzimuthAngle = - Infinity; // radians
this.maxAzimuthAngle = Infinity; // radians
// Set to true to enable damping (inertia)
// If damping is enabled, you must call controls.update() in your animation loop
this.enableDamping = false;
this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
// Set to false to disable zooming
this.enableZoom = true;
this.zoomSpeed = 1.0; // Set to false to disable rotating
this.enableRotate = true;
this.rotateSpeed = 1.0; // Set to false to disable panning
this.enablePan = true;
this.panSpeed = 1.0;
this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
this.keyPanSpeed = 7.0; // pixels moved per arrow key push
// Set to true to automatically rotate around the target
// If auto-rotate is enabled, you must call controls.update() in your animation loop
this.autoRotate = false;
this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
// The four arrow keys
this.keys = {
LEFT: 'ArrowLeft',
UP: 'ArrowUp',
RIGHT: 'ArrowRight',
BOTTOM: 'ArrowDown'
}; // Mouse buttons
this.mouseButtons = {
LEFT: THREE.MOUSE.ROTATE,
MIDDLE: THREE.MOUSE.DOLLY,
RIGHT: THREE.MOUSE.PAN
}; // Touch fingers
this.touches = {
ONE: THREE.TOUCH.ROTATE,
TWO: THREE.TOUCH.DOLLY_PAN
}; // for reset
this.target0 = this.target.clone();
this.position0 = this.object.position.clone();
this.zoom0 = this.object.zoom; // the target DOM element for key events
this._domElementKeyEvents = null; //
// public methods
//
this.getPolarAngle = function () {
return spherical.phi;
};
this.getAzimuthalAngle = function () {
return spherical.theta;
};
this.listenToKeyEvents = function ( domElement ) {
domElement.addEventListener( 'keydown', onKeyDown );
this._domElementKeyEvents = domElement;
};
this.saveState = function () {
scope.target0.copy( scope.target );
scope.position0.copy( scope.object.position );
scope.zoom0 = scope.object.zoom;
};
this.reset = function () {
scope.target.copy( scope.target0 );
scope.object.position.copy( scope.position0 );
scope.object.zoom = scope.zoom0;
scope.object.updateProjectionMatrix();
scope.dispatchEvent( _changeEvent );
scope.update();
state = STATE.NONE;
}; // this method is exposed, but perhaps it would be better if we can make it private...
this.update = function () {
const offset = new THREE.Vector3(); // so camera.up is the orbit axis
const quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) );
const quatInverse = quat.clone().invert();
const lastPosition = new THREE.Vector3();
const lastQuaternion = new THREE.Quaternion();
const twoPI = 2 * Math.PI;
return function update() {
const position = scope.object.position;
offset.copy( position ).sub( scope.target ); // rotate offset to "y-axis-is-up" space
offset.applyQuaternion( quat ); // angle from z-axis around y-axis
spherical.setFromVector3( offset );
if ( scope.autoRotate && state === STATE.NONE ) {
rotateLeft( getAutoRotationAngle() );
}
if ( scope.enableDamping ) {
spherical.theta += sphericalDelta.theta * scope.dampingFactor;
spherical.phi += sphericalDelta.phi * scope.dampingFactor;
} else {
spherical.theta += sphericalDelta.theta;
spherical.phi += sphericalDelta.phi;
} // restrict theta to be between desired limits
let min = scope.minAzimuthAngle;
let max = scope.maxAzimuthAngle;
if ( isFinite( min ) && isFinite( max ) ) {
if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
if ( min <= max ) {
spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
} else {
spherical.theta = spherical.theta > ( min + max ) / 2 ? Math.max( min, spherical.theta ) : Math.min( max, spherical.theta );
}
} // restrict phi to be between desired limits
spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
spherical.makeSafe();
spherical.radius *= scale; // restrict radius to be between desired limits
spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); // move target to panned location
if ( scope.enableDamping === true ) {
scope.target.addScaledVector( panOffset, scope.dampingFactor );
} else {
scope.target.add( panOffset );
}
offset.setFromSpherical( spherical ); // rotate offset back to "camera-up-vector-is-up" space
offset.applyQuaternion( quatInverse );
position.copy( scope.target ).add( offset );
scope.object.lookAt( scope.target );
if ( scope.enableDamping === true ) {
sphericalDelta.theta *= 1 - scope.dampingFactor;
sphericalDelta.phi *= 1 - scope.dampingFactor;
panOffset.multiplyScalar( 1 - scope.dampingFactor );
} else {
sphericalDelta.set( 0, 0, 0 );
panOffset.set( 0, 0, 0 );
}
scale = 1; // update condition is:
// min(camera displacement, camera rotation in radians)^2 > EPS
// using small-angle approximation cos(x/2) = 1 - x^2 / 8
if ( zoomChanged || lastPosition.distanceToSquared( scope.object.position ) > EPS || 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
scope.dispatchEvent( _changeEvent );
lastPosition.copy( scope.object.position );
lastQuaternion.copy( scope.object.quaternion );
zoomChanged = false;
return true;
}
return false;
};
}();
this.dispose = function () {
scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
scope.domElement.removeEventListener( 'wheel', onMouseWheel );
scope.domElement.removeEventListener( 'touchstart', onTouchStart );
scope.domElement.removeEventListener( 'touchend', onTouchEnd );
scope.domElement.removeEventListener( 'touchmove', onTouchMove );
scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
if ( scope._domElementKeyEvents !== null ) {
scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
} //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
}; //
// internals
//
const scope = this;
const STATE = {
NONE: - 1,
ROTATE: 0,
DOLLY: 1,
PAN: 2,
TOUCH_ROTATE: 3,
TOUCH_PAN: 4,
TOUCH_DOLLY_PAN: 5,
TOUCH_DOLLY_ROTATE: 6
};
let state = STATE.NONE;
const EPS = 0.000001; // current position in spherical coordinates
const spherical = new THREE.Spherical();
const sphericalDelta = new THREE.Spherical();
let scale = 1;
const panOffset = new THREE.Vector3();
let zoomChanged = false;
const rotateStart = new THREE.Vector2();
const rotateEnd = new THREE.Vector2();
const rotateDelta = new THREE.Vector2();
const panStart = new THREE.Vector2();
const panEnd = new THREE.Vector2();
const panDelta = new THREE.Vector2();
const dollyStart = new THREE.Vector2();
const dollyEnd = new THREE.Vector2();
const dollyDelta = new THREE.Vector2();
function getAutoRotationAngle() {
return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
}
function getZoomScale() {
return Math.pow( 0.95, scope.zoomSpeed );
}
function rotateLeft( angle ) {
sphericalDelta.theta -= angle;
}
function rotateUp( angle ) {
sphericalDelta.phi -= angle;
}
const panLeft = function () {
const v = new THREE.Vector3();
return function panLeft( distance, objectMatrix ) {
v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
v.multiplyScalar( - distance );
panOffset.add( v );
};
}();
const panUp = function () {
const v = new THREE.Vector3();
return function panUp( distance, objectMatrix ) {
if ( scope.screenSpacePanning === true ) {
v.setFromMatrixColumn( objectMatrix, 1 );
} else {
v.setFromMatrixColumn( objectMatrix, 0 );
v.crossVectors( scope.object.up, v );
}
v.multiplyScalar( distance );
panOffset.add( v );
};
}(); // deltaX and deltaY are in pixels; right and down are positive
const pan = function () {
const offset = new THREE.Vector3();
return function pan( deltaX, deltaY ) {
const element = scope.domElement;
if ( scope.object.isPerspectiveCamera ) {
// perspective
const position = scope.object.position;
offset.copy( position ).sub( scope.target );
let targetDistance = offset.length(); // half of the fov is center to top of screen
targetDistance *= Math.tan( scope.object.fov / 2 * Math.PI / 180.0 ); // we use only clientHeight here so aspect ratio does not distort speed
panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
} else if ( scope.object.isOrthographicCamera ) {
// orthographic
panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
} else {
// camera neither orthographic nor perspective
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
scope.enablePan = false;
}
};
}();
function dollyOut( dollyScale ) {
if ( scope.object.isPerspectiveCamera ) {
scale /= dollyScale;
} else if ( scope.object.isOrthographicCamera ) {
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
scope.object.updateProjectionMatrix();
zoomChanged = true;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
scope.enableZoom = false;
}
}
function dollyIn( dollyScale ) {
if ( scope.object.isPerspectiveCamera ) {
scale *= dollyScale;
} else if ( scope.object.isOrthographicCamera ) {
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
scope.object.updateProjectionMatrix();
zoomChanged = true;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
scope.enableZoom = false;
}
} //
// event callbacks - update the object state
//
function handleMouseDownRotate( event ) {
rotateStart.set( event.clientX, event.clientY );
}
function handleMouseDownDolly( event ) {
dollyStart.set( event.clientX, event.clientY );
}
function handleMouseDownPan( event ) {
panStart.set( event.clientX, event.clientY );
}
function handleMouseMoveRotate( event ) {
rotateEnd.set( event.clientX, event.clientY );
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
const element = scope.domElement;
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
rotateStart.copy( rotateEnd );
scope.update();
}
function handleMouseMoveDolly( event ) {
dollyEnd.set( event.clientX, event.clientY );
dollyDelta.subVectors( dollyEnd, dollyStart );
if ( dollyDelta.y > 0 ) {
dollyOut( getZoomScale() );
} else if ( dollyDelta.y < 0 ) {
dollyIn( getZoomScale() );
}
dollyStart.copy( dollyEnd );
scope.update();
}
function handleMouseMovePan( event ) {
panEnd.set( event.clientX, event.clientY );
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
scope.update();
}
function handleMouseUp( ) { // no-op
}
function handleMouseWheel( event ) {
if ( event.deltaY < 0 ) {
dollyIn( getZoomScale() );
} else if ( event.deltaY > 0 ) {
dollyOut( getZoomScale() );
}
scope.update();
}
function handleKeyDown( event ) {
let needsUpdate = false;
switch ( event.code ) {
case scope.keys.UP:
pan( 0, scope.keyPanSpeed );
needsUpdate = true;
break;
case scope.keys.BOTTOM:
pan( 0, - scope.keyPanSpeed );
needsUpdate = true;
break;
case scope.keys.LEFT:
pan( scope.keyPanSpeed, 0 );
needsUpdate = true;
break;
case scope.keys.RIGHT:
pan( - scope.keyPanSpeed, 0 );
needsUpdate = true;
break;
}
if ( needsUpdate ) {
// prevent the browser from scrolling on cursor keys
event.preventDefault();
scope.update();
}
}
function handleTouchStartRotate( event ) {
if ( event.touches.length == 1 ) {
rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
} else {
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
rotateStart.set( x, y );
}
}
function handleTouchStartPan( event ) {
if ( event.touches.length == 1 ) {
panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
} else {
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
panStart.set( x, y );
}
}
function handleTouchStartDolly( event ) {
const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
const distance = Math.sqrt( dx * dx + dy * dy );
dollyStart.set( 0, distance );
}
function handleTouchStartDollyPan( event ) {
if ( scope.enableZoom ) handleTouchStartDolly( event );
if ( scope.enablePan ) handleTouchStartPan( event );
}
function handleTouchStartDollyRotate( event ) {
if ( scope.enableZoom ) handleTouchStartDolly( event );
if ( scope.enableRotate ) handleTouchStartRotate( event );
}
function handleTouchMoveRotate( event ) {
if ( event.touches.length == 1 ) {
rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
} else {
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
rotateEnd.set( x, y );
}
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
const element = scope.domElement;
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
rotateStart.copy( rotateEnd );
}
function handleTouchMovePan( event ) {
if ( event.touches.length == 1 ) {
panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
} else {
const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
panEnd.set( x, y );
}
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
}
function handleTouchMoveDolly( event ) {
const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
const distance = Math.sqrt( dx * dx + dy * dy );
dollyEnd.set( 0, distance );
dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
dollyOut( dollyDelta.y );
dollyStart.copy( dollyEnd );
}
function handleTouchMoveDollyPan( event ) {
if ( scope.enableZoom ) handleTouchMoveDolly( event );
if ( scope.enablePan ) handleTouchMovePan( event );
}
function handleTouchMoveDollyRotate( event ) {
if ( scope.enableZoom ) handleTouchMoveDolly( event );
if ( scope.enableRotate ) handleTouchMoveRotate( event );
}
function handleTouchEnd( ) { // no-op
} //
// event handlers - FSM: listen for events and reset state
//
function onPointerDown( event ) {
if ( scope.enabled === false ) return;
switch ( event.pointerType ) {
case 'mouse':
case 'pen':
onMouseDown( event );
break;
// TODO touch
}
}
function onPointerMove( event ) {
if ( scope.enabled === false ) return;
switch ( event.pointerType ) {
case 'mouse':
case 'pen':
onMouseMove( event );
break;
// TODO touch
}
}
function onPointerUp( event ) {
switch ( event.pointerType ) {
case 'mouse':
case 'pen':
onMouseUp( event );
break;
// TODO touch
}
}
function onMouseDown( event ) {
// Prevent the browser from scrolling.
event.preventDefault(); // Manually set the focus since calling preventDefault above
// prevents the browser from setting it automatically.
scope.domElement.focus ? scope.domElement.focus() : window.focus();
let mouseAction;
switch ( event.button ) {
case 0:
mouseAction = scope.mouseButtons.LEFT;
break;
case 1:
mouseAction = scope.mouseButtons.MIDDLE;
break;
case 2:
mouseAction = scope.mouseButtons.RIGHT;
break;
default:
mouseAction = - 1;
}
switch ( mouseAction ) {
case THREE.MOUSE.DOLLY:
if ( scope.enableZoom === false ) return;
handleMouseDownDolly( event );
state = STATE.DOLLY;
break;
case THREE.MOUSE.ROTATE:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
if ( scope.enablePan === false ) return;
handleMouseDownPan( event );
state = STATE.PAN;
} else {
if ( scope.enableRotate === false ) return;
handleMouseDownRotate( event );
state = STATE.ROTATE;
}
break;
case THREE.MOUSE.PAN:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
if ( scope.enableRotate === false ) return;
handleMouseDownRotate( event );
state = STATE.ROTATE;
} else {
if ( scope.enablePan === false ) return;
handleMouseDownPan( event );
state = STATE.PAN;
}
break;
default:
state = STATE.NONE;
}
if ( state !== STATE.NONE ) {
scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
scope.dispatchEvent( _startEvent );
}
}
function onMouseMove( event ) {
if ( scope.enabled === false ) return;
event.preventDefault();
switch ( state ) {
case STATE.ROTATE:
if ( scope.enableRotate === false ) return;
handleMouseMoveRotate( event );
break;
case STATE.DOLLY:
if ( scope.enableZoom === false ) return;
handleMouseMoveDolly( event );
break;
case STATE.PAN:
if ( scope.enablePan === false ) return;
handleMouseMovePan( event );
break;
}
}
function onMouseUp( event ) {
scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
if ( scope.enabled === false ) return;
handleMouseUp( event );
scope.dispatchEvent( _endEvent );
state = STATE.NONE;
}
function onMouseWheel( event ) {
if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE ) return;
event.preventDefault();
scope.dispatchEvent( _startEvent );
handleMouseWheel( event );
scope.dispatchEvent( _endEvent );
}
function onKeyDown( event ) {
if ( scope.enabled === false || scope.enablePan === false ) return;
handleKeyDown( event );
}
function onTouchStart( event ) {
if ( scope.enabled === false ) return;
event.preventDefault(); // prevent scrolling
switch ( event.touches.length ) {
case 1:
switch ( scope.touches.ONE ) {
case THREE.TOUCH.ROTATE:
if ( scope.enableRotate === false ) return;
handleTouchStartRotate( event );
state = STATE.TOUCH_ROTATE;
break;
case THREE.TOUCH.PAN:
if ( scope.enablePan === false ) return;
handleTouchStartPan( event );
state = STATE.TOUCH_PAN;
break;
default:
state = STATE.NONE;
}
break;
case 2:
switch ( scope.touches.TWO ) {
case THREE.TOUCH.DOLLY_PAN:
if ( scope.enableZoom === false && scope.enablePan === false ) return;
handleTouchStartDollyPan( event );
state = STATE.TOUCH_DOLLY_PAN;
break;
case THREE.TOUCH.DOLLY_ROTATE:
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
handleTouchStartDollyRotate( event );
state = STATE.TOUCH_DOLLY_ROTATE;
break;
default:
state = STATE.NONE;
}
break;
default:
state = STATE.NONE;
}
if ( state !== STATE.NONE ) {
scope.dispatchEvent( _startEvent );
}
}
function onTouchMove( event ) {
if ( scope.enabled === false ) return;
event.preventDefault(); // prevent scrolling
switch ( state ) {
case STATE.TOUCH_ROTATE:
if ( scope.enableRotate === false ) return;
handleTouchMoveRotate( event );
scope.update();
break;
case STATE.TOUCH_PAN:
if ( scope.enablePan === false ) return;
handleTouchMovePan( event );
scope.update();
break;
case STATE.TOUCH_DOLLY_PAN:
if ( scope.enableZoom === false && scope.enablePan === false ) return;
handleTouchMoveDollyPan( event );
scope.update();
break;
case STATE.TOUCH_DOLLY_ROTATE:
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
handleTouchMoveDollyRotate( event );
scope.update();
break;
default:
state = STATE.NONE;
}
}
function onTouchEnd( event ) {
if ( scope.enabled === false ) return;
handleTouchEnd( event );
scope.dispatchEvent( _endEvent );
state = STATE.NONE;
}
function onContextMenu( event ) {
if ( scope.enabled === false ) return;
event.preventDefault();
} //
scope.domElement.addEventListener( 'contextmenu', onContextMenu );
scope.domElement.addEventListener( 'pointerdown', onPointerDown );
scope.domElement.addEventListener( 'wheel', onMouseWheel, {
passive: false
} );
scope.domElement.addEventListener( 'touchstart', onTouchStart, {
passive: false
} );
scope.domElement.addEventListener( 'touchend', onTouchEnd );
scope.domElement.addEventListener( 'touchmove', onTouchMove, {
passive: false
} ); // force an update at start
this.update();
}
} // This set of controls performs orbiting, dollying (zooming), and panning.
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
// This is very similar to OrbitControls, another set of touch behavior
//
// Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
// Pan - left mouse, or arrow keys / touch: one-finger move
class MapControls extends OrbitControls {
constructor( object, domElement ) {
super( object, domElement );
this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up
this.mouseButtons.LEFT = THREE.MOUSE.PAN;
this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE;
this.touches.ONE = THREE.TOUCH.PAN;
this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE;
}
}
THREE.MapControls = MapControls;
THREE.OrbitControls = OrbitControls;
} )();
</script>
<script>
/* OCCUPANCY_DATA (mesh + all voxel sizes) inlined by build_preview.py */
/* generated by src/inference.py — do not edit by hand */
window.OCCUPANCY_DATA = {"meta":{"title":"Occupancy Fitting","subtitle":"AURORA A1 · CAD ground truth → 3D voxel cubes","modelName":"AURORA A1 — F1 concept car","sourceRepo":"https://github.com/Sunwood-ai-labs/aurora-a1-freecad","sourceFile":"aurora_a1/AURORA_A1.step","licenseNote":"The source repository does not declare a license. The STEP file is used here for local research/demo purposes only; do not redistribute the model without permission.","generatedAt":"2026-11-25T15:08:56+00:00","runtimeSec":22.15,"stepUnits":"mm","nSolids":130,"nTriangles":90964,"nRenderVertices":44971,"nRenderTriangles":90964,"surfaceAreaM2":56.266087755135814,"volumeCadSumM3":2.058946186136728,"volumeMeshCheckM3":2.0383916422484294,"volumeRefM3":1.758480448,"finePitchMm":4.0,"meshDeflectionMm":10.0,"fineDims":[1411,502,243],"bboxMinMm":[-1120.0,-1001.2,0.0],"bboxMaxMm":[4520.0,1001.2,965.0],"dimsMm":[5640.0,2002.4,965.0],"dimsM":[5.64,2.0024,0.965],"axisCube":{"side_m":5.64,"volume_m3":179.40614399999998,"center_m":[1.7,0.0,2.82],"rotation":null,"margin_mm":0.0,"note":"最小轴对齐包络立方体;沿 x/y 居中,底面与车辆最低点对齐"},"minCube":{"side_m":4.131143836240798,"volume_m3":70.50354411322064,"center_m":[1.619036216411297,-0.00030724817324604786,0.24822376909897242],"rotation":[[0.4483619107232079,0.44831030320880894,-0.7732977880800255],[-0.7066954999716717,0.7075176929622742,0.0004294940394790059],[0.5473144135982745,0.5462934982060164,0.6340428585556421]],"margin_mm":20.0,"note":"数值搜索得到的最小旋转包络立方体;含 20 mm 网格误差余量"},"uprightBox":{"dims_m":[5.64,2.0024,0.965],"volume_m3":10.89826224,"center_m":[1.7,0.0,0.4825],"rotation":null,"note":"最小正置长方体(轴对齐 AABB,基于 10 mm 网格;底面与车辆最低点对齐)"},"envelopes":{"standardCube":{"volume_m3":179.40614399999998,"true_occupancy":0.009801673503444788},"rotatedMinCube":{"volume_m3":70.50354411322064,"true_occupancy":0.024941731229512112},"uprightBox":{"dims_m":[5.64,2.0024,0.965],"volume_m3":10.89826224,"true_occupancy":0.16135420576923099}},"sizesCm":[4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40],"defaultSizeCm":8,"defaultThresholdPct":30.0,"chartThresholds":[0.1,0.2,0.3,0.4,0.5]},"mesh":{"vertexCount":44971,"triangleCount":90964,"positionsB64":"KVyPv6Rwfb+PwnU8KVyPv6Rwfb/NzMw8KVyPv3sUbr+PwnU8KVyPv3sUbr/NzMw8KVyPv3sUbj+PwnU8KVyPv3sUbj/NzMw8KVyPv6RwfT+PwnU8KVyPv6RwfT/NzMw8zcyMvwAAgL+PwnU8zcyMvwAAgL+amRk+zcyMv6Rwfb+PwnU8zcyMv6Rwfb/NzMw8zcyMv6Rwfb+amRk+zcyMv6RwfT+PwnU8zcyMv6RwfT/NzMw8zcyMv6RwfT+amRk+zcyMvwAAgD+PwnU8zcyMvwAAgD+amRk+ecyMv8bctTuamZk9AcGMv/evrDv0/ZQ9IqaMv917uDs0nZ09F4KMv2/1nDvvA5A9oE+Mv3XlszsYz6A9YhCMv/NUhzvBxYo93c2Lvypvl762oaI9l8qLv3JtqDvBOaM9cr+Lv5I/mL5OC549gqiLvww8l74LtaY9L6iLv82SsD4ZHKU9Z5uLv/EpsD48ZqA9LIKLv7SrsD7rOak9RnyLv3ehmb78NZk9i2yLvyE8WjubcoU9LVuLv/94rz59XJs9BVGLv3Wrl74eFqo9qiuLv6d0sD6CkKw9pBmLv5m7ljur56Q9qwSLv/yMm757MZQ9gueKv+SDrj7TE5Y9CMmKvyi4mL7wxKw9TKaKv6btrz6gGq89iZiKv1JJHTswL4A9S1mKvxfxnb44Mo89X0GKvy9RrT5vu5A9FD+Kv9OffTsO86U9kzWKv8VyU7+RuMc9LSaKv12KU7+0AsM9fxOKv1hWmr450a49jBCKv99sU7/Y9cs9CvSJv44erz588rA9BOKJv6ezU79qGL49trmJv/t5U78ahs89mpmJv/YofL89Ctc9mpmJv/YofD89Ctc9p5aJvx7htDrKiXY9i4mJv/YofL+mRNI9i4mJv/YofD+mRNI9cHyJvw6+oL4kYoo9OnWJv/YofL8/V9s9OnWJv/YofD8/V9s9EmuJv1vrqz6Agos9x2iJvwPsU7/oE7k9v0OJv/YofL/fT809v0OJv/YofD/fT809LT6Jv6abRDula6Y9CTOJv+p4nL70T7A9DjKJv8iYU79ZadI9ER6Jv/YofL889949ER6Jv/YofD889949KxiJv+0Nrj6SIrI93siIv/YofL/hQMg93siIv/YofD/hQMg9F7yIvyMyVL/jGbQ9wJWIv/YofL907+E9wJWIv/YofD907+E9MXyIv/fHU7+NtNQ9uXCIv5jdo77s+oU9f2qIv0X11jlT0G09PGaIv5Zbqj7wp4Y9mSqIv9QOn74ZVrE9NxqIv/phBDtfe6Y9jxmIv/YofL+eQcM9jxmIv/YofD+eQcM9oBWIv1DCrD5YyrI96N6Hv/YofL9iSuQ96N6Hv/YofD9iSuQ9mN2Hv7aEVL/IXq89Z5uHv+IGVL8yctY9bTmHv1w9p764QII9cTiHv/YofL+Dhr49cTiHv/YofD+Dhr49IjeHvw2rqD5rZYI9rReHvy5WVLrNr2Y9cv6Gvx0Dor4dA7I9JvyGv/YofL8AHeY9JvyGv/YofD8AHeY9s++Gv9RIqz4EBLM9H9eGv7YQZDo3N6Y9PtCGvx7hVL9DHKs9o5KGv49TVL9/vNc9ZmaGv9S3TL3fMkc+ZmaGv8xdS70bLz0+ZmaGv/H0Sr1u3U0+ZmaGv5+OR72pnzc+ZmaGv65kR71YylI+ZmaGvz90Qb0tlVc+ZmaGvz4FQL2UwTE+ZmaGvy4EOb15Hlw+ZmaGv9ydNb1YrSw+ZmaGv4L/Lb1EUWA+ZmaGvxN+K
</script>
<script>
/* occupancy application inlined by build_preview.py */
/* 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;
},
};
})();
</script>
</body>
</html>